There is indeed a nasty bug in the code! The attached script should have it fixed. I've included code to check the total number of pages reported with the total number of pages processed, that outputs an error messages if a discrepancy exist (to alert for any other flaw the algorithm may have). Try it against a big number of PDFs, and let me know if any error message shows up.