A few optimizations, mostly got rid of duplicated search