Fixed by 274f8bf05ef526d65f01614313dda65bc7ec7a87. Thanks for the analysis! (the code wasn't really all that difficult after that...)