Reworked code.

Brought code up to an acceptable state; before it was more of a mess.