Refactorings to remove duplicate code and added some javadocs