Improve code and add javadoc