More code cleanup & bugfixes