If you want to keep your sanity while programming,
Highly desirable. :)
you'll encode all of the nesting logic into a data structure,
Any chance I could get you to give a short example of such a data structure?
and all the code blocks marked with #... in your example into a dispatch table.
Hm. Haven't used dispatch tables before. Searching around a bit, it seems to be just a hash where the keys are "command" names and the values are references to functions. Will have a closer look at "When should I use a dispatch table?" and "Implementing Dispatch Tables", because I'm still not sure what it buys me over just calling the functions directly.
Then you write a small dispatching program that walks through the data structure, prints the prompt, analyses the results, makes a transition into the next state and calls your callback (maybe in a different order).
Oooh. Would love to see pseudocode if you were of a mind to take the time to write it out.