added some comments and did a bit of refactoring