Yeah, I didn't know what to name this.

toPlan first checks for cycles via the Visited map, and if there's no cycle it delegate to toPlan2 which does the real work.