various optimizations, bug fixes and unnecessary code deleted