Tidied and fixed code