rewrite the backtracking logic in a way that makes sense to me