refactored the code and bug fixed