simplified code and added javadoc