# [Wolfram Language (Mathematica)], 176 bytes {a_,b_}~B~S_:=Fold[Switch[#2,"f",{a,#[[2]]},"F",{#[[1]],b},"e",{0,#[[2]]},"E",{#[[1]],0},"p",#+{-1,1}Min[#[[1]],b-#[[2]]],"P",#+{1,-1}Min[#[[2]],a-#[[1]]]]&,{0,0},Characters@S] [Try it online!][TIO-jz5kou5i] [Wolfram Language (Mathematica)]: https://www.wolfram.com/wolframscript/ [TIO-jz5kou5i]: https://tio.run/##dYzBCoJAFEX3fYWM0KY3oNYqCMTIXTDgcnjI0xSFNLGBFoN@S9/Sj01TUm1yee499zakqqIhVedkjKYUsnQYozFJt7v4cj7J5FarvJJuAKxkoAlcKQPEAVhs0YKPCJnFwqL3aw@/1rPYMXBXmvvgD8e6lZ8dn3wEJt6CD/wr2ByITybi8vVun/YV9ZSror@GCRrR161ywsc9knoNzmYAhzFc/ItjUcw3Yr4tu7kZQ/ME "Wolfram Language (Mathematica) – Try It Online" Debugging is done by [replacing `Fold` with `FoldList`][1]. [1]: https://tio.run/##dYzBCoJAFEX3fYWM0KY3oNYqCMTIVYHgcnjIy0YcSBMdaCH6LX1LP2ZTUm5yee499xakc1mQVikNQ0sJnJOuD/o42e7C2/VyVI0W8V3pNBe2Byxj0BLYQniIHbDQoAEXEc4GpUFnag9T6xisGNirlrvgdidViu@Ojz4Ciz6CC/wnmByIjybi8v1unvY51ZRqWTd@jENUq1Jb/vMRiHYN1qYDizFc/IvDSM430XybVXMzhsML