Refactored the code and added javadoc.