Important optimizations, refactor, fixes