Memory abuse fixes

Various places that valgrind complained about bad memory accesses, mostly reading unset memory.
In some cases, the code was too confused to make it easy to work out what the bad access was; I tidied the code up in such cases, in an effort to make it easier to see what the problem is, if valgrind still grumbles.
In a few cases, it was actually clear what the problem was, so I fixed it (and, again, it typically involved messy code, so I tidied it up).