Educational rewrite.

Rewrote the original code to learn how the program worked.