fix bugs optimize, refactor, and fix more bugs