Cleaned up the code a bit

I rewrote a bunch of copy-pasta'd code blocks into more sensible for-loops and
checked to make sure the output was all still the same. I'm still thinking
about the normalization...

Signed-off-by: Ted Gibbons <ted.codes@gmail.com>