fix errors and refine code