Extensive comments added, minor refactoring