optimize code and fix bugs