Many frameworks have been proposed which provide distributed algorithms encapsulated as middleware services to simplify application design. The developers of such algorithms are faced with two opposing forces. One is to design generic algorithms that are reusable in a large number of applications. Efficiency considerations, on the other hand, force the algorithms to be customized to specific operational contexts. This problem is often attacked by simply re-implementing all or large portions of an algorithm. The goals of this project are to (a) Develop techniques to design distributed algorithms amenable to customization, (b) Develop infrastructure to analyze applications and the target platform spcifications to determine when customization can take place, (c) Develop tools to perform the necessary code transformation and compositions to carry out the identified optimizations in the algorithms. We are pursuing a number of different approaches to achieve these goals. We have developed two frameworks, FRAMES and InDiGO, which provides tools and techniques to perform optimization following two different approaches. We have performed experimental studies to demonstrate the advantages of our infrastructure. Another approach based on proof-based optimization is also being pursued. This paper highlights the results from these efforts and discuss our future work plans to apply these techniques to distributed sensor network middleware.