refactoring
add backtracking (still need tests)