Refactored the code and Corrected the bugs