// recursiveTiffConvert.txt
// Written by Curtis Rueden
// Last updated on 2011 Feb 22

// Recursively converts files to TIFF using Bio-Formats.

// It was originally written to convert Gatan DM3 files, but you can easily
// change the code to work with any or all extensions of your choice.

// Thanks to Chris Zahm for suggestions and improvements:
//   - Save as OME-TIFF using Bio-Formats Exporter, to preserve metadata
//   - Run garbage collection after each exported file

ext = "DM3"; // this variable controls the extension of source files

requires("1.39u");
inDir = getDirectory("Choose Directory Containing " + ext + " Files ");
outDir = getDirectory("Choose Directory for TIFF Output ");
setBatchMode(true);
processFiles(inDir, outDir, "");
print("-- Done --");

function processFiles(inBase, outBase, sub) {
  flattenFolders = true; // this flag controls output directory structure
  print("-- Processing folder: " + sub + " --");
  list = getFileList(inBase + sub);
  if (!flattenFolders) File.makeDirectory(outBase + sub);
  for (i=0; i<list.length; i++) {
    path = sub + list[i];
    upath = toUpperCase(path);
    if (endsWith(path, "/")) {
      // recurse into subdirectories
      processFiles(inBase, outBase, path);
    }
    else if (endsWith(upath, "." + ext)) {
      print("-- Processing file: " + path + " --");
      run("Bio-Formats Importer", "open='" + inBase + path + "' color_mode=Default view=[Standard ImageJ] stack_order=Default use_virtual_stack");
      outFile = outBase + path + ".ome.tif";
      if (flattenFolders) outFile = replace(outFile, "/", "_");
      run("Bio-Formats Exporter", "save=[" + outFile + "] compression=Uncompressed");
      close();
      run("Collect Garbage");
    }
  }
}
