Some code refactoring and documentation