minor bugfixes.
Major refactoring.