rewriting to improve readability and adding in javadoc style comments