A stack seems helpful.