package nxm.sys.prim;

import nxm.sys.lib.BaseFile;
import nxm.sys.lib.Data;
import nxm.sys.lib.DataFile;
import nxm.sys.lib.DataOp;
import nxm.sys.lib.Primitive;

/**
 Groups multiple inputs into a type 3000 file

 @author Ken Smith
*/
public class group extends Primitive  {

  private DataFile ho,hi[];
  private Data dbo,dbi[];
  private int nrec, rlen, nfiles, iper;

  /** default constructor */
  public group () {}

  public int open(){

    // count input files
    nfiles = MA.nargs - 1;
    hi = new DataFile[nfiles];
    dbi = new Data[nfiles];
    boolean warn = MA.getState ("/WARN", true);

    // open input files
    double size = 0.0;
    for (int i=0; i<nfiles; i++) {
      DataFile h = MA.getDataFile(MA.getKey(i+2),"1000,2000,3000,5000","",0);
      h.open();
      if (i==0) {
        ho = MA.getDataFile("OUT",h,0);
        ho.setSubSize(0);
        ho.setRecLength(0);
        if (h.typeClass!=3 && h.typeClass!=5) ho.setType(3000);
      }
      if (h.typeClass==3) {
        for (int irec=0; irec<h.getSubSize(); irec++) {
          String name = ho.getUniqueRecName("SR00",ho.getSubSize()+1, h.getRecName(irec), warn);
          ho.addSubRec(name,h.getRecFormat(irec));
        }
      }
      else if (h.typeClass==5) {
        for (int irec=0; irec<h.getSubSize(); irec++) {
          String name = ho.getUniqueRecName("SR00",ho.getSubSize()+1,
                                             h.getRecName(irec), warn);
          ho.addComp(name,h.getCompFormat(irec),h.getCompType(irec), h.getCompUnits(irec));
        }
      }
      else {
        if (h.typeClass==2) nrec=h.getSubSize(); else nrec=1;
        for (int irec=0; irec<nrec; irec++) {
          String name = ho.getUniqueRecName("SR00",ho.getSubSize()+1,null,warn);
          ho.addSubRec(name,h.getFormat());
        }
      }
      if (i==0 || h.getSize()<size) size = h.getSize();
      hi[i] = h;
    }

    // now open the output file
    ho.setSize(size);
    ho.open(BaseFile.OUTPUT);

    // get the data buffers
    rlen = (int)ho.dbpe;
    iper = MA.getL("/TL",16384/rlen);
    dbo = ho.getDataBuffer(iper);
    for (int i=0; i<nfiles; i++) dbi[i] = hi[i].getDataBuffer(iper);

    return NORMAL;
  }

  public int process() {
    // read each file, and interleave data in output buffer
    for (int i=0,ioff=0; i<nfiles; i++) {
      int ngot = hi[i].read(dbi[i]);
      if (ngot<=0) return FINISH;
      if (ngot<iper) iper=ngot;
      int bytes = (int) hi[i].dbpe;
      DataOp.copy (dbi[i],0,bytes, dbo,ioff,rlen, bytes,iper);
      ioff += bytes;
    }
    ho.write(dbo,iper);

    return NORMAL;
  }

  public int close() {
    ho.close();
    for (int i=0; i<nfiles; i++) hi[i].close();
    return NORMAL;
  }

}
