added comments, code cleaning and refactoring