fixed a bug and refactored