Code cleanup and two bugfixes