Bugfixes

Fix various bugs and do some cleanup