Added more javadoc. Some refactoring.