fixed a bug and refactored some code