Plug leaks and other random edits

When looking at this as a result of a Stack Overflow reference, I noticed a few leaks (probably the only significant change I'm suggesting) and have fixed those in commit 38330c7.

Then while looking at the code, I noticed a few other little things, so I fixed the more obvious issues.