Greatly optimised and refactored code.