bunch of fixes, optimizations, formating