optimization and fix bugs