Can we pull most of the logic into a reusable function so it's easier to share across *Stan?
I think for this pull request, that would mean a function that starts at line 488 and encapsulates it down to the end of the while loop. It should also have an input for the output stream. (Btw, this note was for me as it was for anyone else... whoever has time can fix it.)