Tidying up code, still need to test edge cases