First stab at a fix.
Fix all known issues.
Add some documentation. Break some code out to its own function.