refactor structure and fix bugs