more code optimizations and bug fixes