Tidied up code, simplified some logic