Added a lot of bug fixes and optimization