Bugfixes and rewrites