Added more comments. Minor code refactoring.