Fixed a bug in the code, refactored code