big refactoring, adds configurability, code cleanup