Further cleaned up code and bugfixes