heavy cleanup and restructuring of program for readability