Tidy up as well as possible for now

Some changes still to make, e.g. variable names and
length of functions/number of variables, but egregious
problems are resolved.

Can't test this, so it is possible I've broken things.