This sounds to me like a classic recursion problem. The
trick is to have one function you call on a directory which
goes throught the listing, calling itself for each
directory found. This should should allow you to traverse
an entire directory tree without any trouble.
In case your code is working correctly on some but
not all servers, consider that you are dealing with a
slow network bound system. Don't make a lot of
children trying to open a bunch of directories at once.
Consider it could fail if the server is busy.
Check the listing you get back and make sure you aren't
trying to get the same (.) directory repeatedly or recursing
upwards beyond the public readable folder, etc.
Basically if you can do exactly what your program is supposed
to do, perhaps interactively telling it to go one step at a
time and seeing what it sees, you should be able to debug.