I really dislike using a stack as it introduces an internal state. Sadly there doesn't seem to be an easy way around this.