code cleanup, optimization, refactoring and documentation