Lots of bugfixes, typos and cleanup