add debug mode, minor refactoring