Add comments and refactoring to make code clearer (hopefully)