various minor fixes and lots of optimization