A lot of cleanups and some bugfixes