major optimizations and refactor