Update: Thanks to stardt whose script works! The pdf is a page of another one. I tried the script on the other one, and it also correctly spit each pdf page
I'd like to add that you have to pay attention that your mediaBox variables are not shared across the copies p and q.
This can easily happen if you read from p.mediaBox before taking the copy.
In that case, writing to e.g. p.mediaBox.upperRight may modify q.mediaBox and vice versa.
@moraes' solution takes care of this by explicitly copying the mediaBox.