Lots of cleanup to prepare code for generalization