Code cleanup and refactoring.
Added additional documentation