General bugfixing and cleanup