Made some bug fixes, improvements and optimizations