Refactor and cleanup

Refactoring and cleanup of code.