added misc optimizations, refactored some parts of code