Bugfixes and some restructuring