Refactored the entire code