first pass with some basic optimizations