Sorry for the delay in reply, this is off my phone so can't code.
You can Do this but will need another foreach loop between c the inner loop looking for documents and settings or users.
This would make it os proof :)
Think the code can be improved so will try tomorrow