Initial refactoring and adding doc comments