Some bugfixes, code rewrites.