Some cleanup, refactoring and documentation