Some bug-fixes and optimizing code