// dvSplitTimePoints.txt
// Written by Sebastien Huart
// Last updated on 2008 May 7

// Splits timepoints/channels on all .dv files in a folder.

macro "SplitDVTimePoints [F2]"
{
  run("Bio-Formats Macro Extensions");
  srcDir=getDirectory("Choose source directory");
  outDir=getDirectory("Choose output directory");
  tmpfiles=getFileList(srcDir);
  files=filterFileNames(tmpfiles,".DV",true);
  for (i=0;i<files.length;i++)
  {
    srcPath=srcDir+files[i];
    basename=substring(files[i],0,lastIndexOf(files[i],"."));
    print(srcPath);
    splitT(srcPath,outDir,basename);
  }
}

function filterFileNames(filelist,extension,ignorecase)
{
  tmpfiles=newArray(filelist.length);
  count=0;
  pattern=extension;
  for(i=0;i<filelist.length;i++)
  {
    strin=filelist[i];
    if (ignorecase)
    {
      strin=toLowerCase(strin);
      pattern=toLowerCase(pattern);
    }
    if (endsWith(strin,pattern))
    {
      tmpfiles[count]=filelist[i];
      count++;
    }
  }
  filteredList=newArray(count);
  for (i=0;i<count;i++)
  {
    filteredList[i]=tmpfiles[i];
  }
  return filteredList;
}

function zero_padd(in, maxint)
{
  smax=lengthOf(""+maxint);
  tmp=""+in;
  while (lengthOf(tmp)<smax)
  {
    tmp="0"+tmp;
  }
  return tmp;
}

function bfImport(path,channels,zs,times)
{
  bfDimOrders=newArray("XYZCT","XYZTC","XYCZT","XYCTZ","XYTZC","XYTCZ");
  dimOrder="";
  Ext.getDimensionOrder(dimOrder);
  Ext.getSizeT(numT);
  print(dimOrder+" numT="+numT);
  options="open=["+path+
    "] view=[Standard ImageJ] stack_order="+dimOrder+" specify_ranges ";
  cOpts="c_begin="+ channels[0]+ " c_end="+channels[1]+" c_step="+channels[2];
  zOpts="z_begin="+zs[0]+" z_end="+zs[1]+" z_step="+zs[2];
  tOpts="t_begin="+times[0]+" t_end="+times[1]+" t_step="+times[2];
  options=options+cOpts+" "+zOpts+" "+tOpts;
  run("Bio-Formats Importer",options);
  id=getImageID();
  return id;
}

function splitT(path,outdir,basename)
{
  Ext.setId(path);
  Ext.getSizeT(numT);
  Ext.getSizeZ(numZ);
  Ext.getSizeC(numC);
  wavelength=newArray(numC);

  for (i=1;i<=numC;i++)
  {
    metafield="Wavelength "+i+" (in nm)";
    wtmp="";
    Ext.getMetadataValue(metafield,wtmp);
    wavelength[i-1]=wtmp;
  }

  for (i=1;i<=numT;i++)
  {
    for (c=0;c<numC;c++)
    {
      coptions=newArray(c,c,1);
      toptions=newArray(i,i,1);
      zoptions=newArray(1,numZ,1);
      srcId=bfImport(path,coptions,zoptions,toptions);
      seqNum=zero_padd(i,numT);
      newName=basename+"_W"+wavelength[c]+"_T"+seqNum+".tif";
      rename(newName);
      outPath=outdir+newName;
      saveAs("tiff",outPath);
      print("saved:"+outPath);
      close();
    }
  }
  Ext.close();
}
