Documentation and Refactoring

Some function documentation and source code refactoring