added optimizations and tests