cleanup and optimise code, add more comments