Bug fixed. Refactored code