Refactored code. Fixed bug.