Fixed up, and reorganized, code