Word of warning, on larger sites the queries that count the number of messages will dramatically slow down the page and since they don't use the do_query function, they weren't being timed or counted:
Generated in 8.893 seconds in which 8.884 seconds were spent on a total of 11 queries.
There are three numrow calls to count messages; the second of which appears to be a near duplicate of the $pmsaved query; not sure but maybe this can be done only once. All three are near duplicates in themselves, only checking for different status codes.