Tidyed up code and added missing comments