Cleanup and refactoring

general cleanup, some comments, but also detected a couple of serious issues. Tests have been added (but commented out and marked with TODO comments for now)