Cleaning up code and modularising functionality