I have never seen a while loop hang before
Which while loop do you think is hanging? I don't think that is your problem.
char messageline[] = "This is only a test on page: ";
char lpstring[] = "lastpage: ";
char int_string[10];
itoa(lastpage, int_string, 10); // make string of the pagenumber
strcat(messageline, int_string); //append to the messagline string
messageline is exactly large enough to hold the text you provided and the trailing NULL. There are exactly 0 bytes extra, in which you try to store at least one more byte. Fail.
Now that you have stomped on memory you don't own, unpredictable results will occur. It is not even worth the effort to read further. You absolutely MUST fix this problem before we can even think about looking at the rest of the code.