Tidied and cleaned up code