Major refactoring to factor out common code and eliminate some dead one.