(Somewhat) Tidied up code