some refactoring, more comments added