Add comments to code and some minor refactoring