Major cleanup and comments added.