// zvi2HyperStack.txt
// Written by Sebastien Huart
// Last updated on 2008 May 6

// Reads in a ZVI file using Bio-Formats, synthesizes the LUT using
// emission wavelength metadata, and displays the result as a hyperstack.

//arbitrary boundary wavelength for each channel...
var luts=newArray(470,540,615);

//wavelength->LUT name
function asLut(wl)
{
  retstr="";
  if (wl<luts[0])
  {
    retstr="Blue";
  }
  else if ((wl>=luts[0]) && (wl<luts[1]))
  {
    retstr="Green";
  }
  else if (wl>=luts[1])
  {
    retstr="Red";
  }
  else
  {
    retstr="Grays";
  }
  return retstr;
}


function zviToHS(path)
{
  run("Bio-Formats Macro Extensions");
  Ext.setId(path);
  print("path set to:"+path);
  showStatus("reading metadata");
  MAXNWL=10;
  nwl=0;
  Ext.getSizeC(nwl);
  emwl=newArray(nwl);
  print("sizeC:"+nwl);
  wlidx=0;
  for(i=0;i<MAXNWL;i++)
  {
    field="Emission Wavelength "+i;
    val="";
    Ext.getMetadataValue(field,val);
    if (val != 0)
    {
      emwl[wlidx]=val;
      wlidx++;
    }
  }
  dimOrder="";
  Ext.getDimensionOrder(dimOrder);
  Ext.getSizeT(numT);
  print("sizeT:"+numT);
  Ext.getSizeZ(numZ);
  print("sizeZ:"+numZ);
  options="open=["+path+"] view=[Standard ImageJ] stack_order="+dimOrder+" autoscale";
  showStatus("opening file");
  run("Bio-Formats Importer",options);
  order=toLowerCase(dimOrder);
  if(order=="xyczt")
    order=order+"(default)";

  run("Stack to Hyperstack...", "order="+order+" channels="+nwl+" slices="+numZ+" frames="+numT+" display=Color");
  id=getImageID();
  for(i=1;i<=nwl;i++)
  {
    progress=i/nwl;
    Stack.setChannel(i);
    LUT=asLut(emwl[i-1]);
    print("Channel "+i+":"+LUT);
    run(LUT);
  }
  Ext.close();
  return id;
}

macro "zviOpen [F1]"
{
  path=File.openDialog("Choose ZVI file")
    zviToHS(path);
}
