Major code cleanup, various improvements and bugfixes