Merging SchroedingerHepcat's fixes into the program.
I've made slight modifications to them by replacing the for loops with linq queries
and simplifing some of the conditionals.
Merge branch 'SchroedingerHepcat-master'