Working version.
Final version. Still pretty gross, lots of uncommented functions and possibly redundant clauses.