refactoring to tidy and simplify code
added a few more header comments