fixes #1; huge number of refactorings and fixes