Cleaned up and organised code a bit