Extensive and comprehensive refactor spanning over 104 lines, improving performance and cleaning up the code.