Index: filemanager.module
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/filemanager/filemanager.module,v
retrieving revision 1.9.2.2
diff -u -r1.9.2.2 filemanager.module
--- filemanager.module	28 Oct 2005 22:37:21 -0000	1.9.2.2
+++ filemanager.module	14 Jan 2006 04:16:42 -0000
@@ -670,13 +670,18 @@
     $file->directory = 0;
     $directories = db_query("SELECT directory, count(1) filecount FROM {file} WHERE private = '%s' GROUP BY directory ORDER BY directory ASC", $file->private);
 
+    // this while loop requires the $directories array to be ordered in ascending order
     while ($directory = db_fetch_object($directories)) {
-       // If the next directory in the list skips the current directory
-       // number use it or if the current directory has less than the file
-       // limit in it.
-      if ($directory > $file->directory || $directory->filecount < variable_get('filemanager_max_file_count', '2000')) {
-        // If the directory is ok now lets make sure we don't already
-        // have this filename in the directory.
+      // The idea here is to find a directory where the filename doesn't exist
+      // and we haven't hit the maximum file limit. The directories are named
+      // numerically and the first part of the test makes sure that the they're
+      // filled in sequenceially. $file->directory is incremented by 1 each time
+      // but $directory->directory comes from the database. If
+      // $directory->directory > $file->directory, then $file->directory doesn't
+      // exist and would be a safe place to save the file.
+      if ($directory->directory > $file->directory || $directory->filecount < variable_get('filemanager_max_file_count', '2000')) {
+        // If the directory is ok now lets make sure we don't already have this
+        // filename in the directory (checking both working and active).
         if (!file_exists(filemanager_create_path($file, FALSE)) && !file_exists(filemanager_create_path($file, TRUE))) {
           break;
         }

