Adjusted code to use the state stack