Major restructuring and a minor bugfix