add javadoc and clarify some confusing code