Refactored the code. Greatly reduced the number of lines and improved the structure.