Refactored code, fixed a bug