Major restructure and bugfixes