Rewrote the majority of the code.

All changes are defined in there, so you can see the fixes I made.