various performance optimizations and general cleanup contributed by Michal Valach.  thank you!