Some major refactoring and commenting.