Major restructuring, bugfixes