Bug fix and refine code