Numerous bugfixes