Best way to handle these type of problems is remove as much stuff you believe unrelated to the problem. In this case I would start with the tests for max count and max size. Even the sorter and it's call.
You must check the return values!
opendir Returns a directory handle resource on success, or FALSE on failure.
rename Returns TRUE on success or FALSE on failure.
unlink Returns TRUE on success or FALSE on failure.
read_dir This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
You need to be more verbose. Try adding things like:
echo "<!-- type is " . $type . " -->
This won't show up on the screen, but use view source and see it.
THis way you don't even need to remove these when debugging is done