added some optimizations and some bug fixes