Refactored the code and added fixes