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;

/**
  Demux a complex input file to its real and imaginary components.

  @author Jeff Schoen
*/
public class demux extends Primitive {

  private DataFile hc,hr,hi;
  private Data dc,dr,di;

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

  public int open() {

    hc = MA.getDataFile("COMP", "1000", "C#", 0);
    hc.open();

    hr = MA.getDataFile("REAL", hc, 0);
    hr.setFormatMode(SCALAR);
    hr.open(BaseFile.OPTIONAL);

    hi = MA.getDataFile("IMAG", hc, 0);
    hi.setFormatMode(SCALAR);
    hi.open(BaseFile.OPTIONAL);

    xfer = Math.max(1,(int)(bufSize/hc.dbpe));
    xfer = MA.getL("/TL",xfer);

    dc = hc.getDataBuffer(xfer);
    dr = hr.getDataBuffer(xfer,dc.getFormatType()); // NXM-4033 fixed to honor Data Type
    di = hi.getDataBuffer(xfer,dc.getFormatType());

    return NORMAL;
  }

  public int process() {
    int n = hc.read(dc);
    if (n==0) return NOOP;
    else if (n<0) return FINISH;
    if (hr.isOpen) {
      DataOp.copy (dc,0*dc.bps,dc.bpe, dr,0,dr.bpe, dr.bpe,n);
      hr.write(dr,n);
    }
    if (hi.isOpen) {
      DataOp.copy (dc,1*dc.bps,dc.bpe, di,0,di.bpe, di.bpe,n);
      hi.write(di,n);
    }
    return NORMAL;
  }

  public int close() {
    hc.close();
    hr.close();
    hi.close();
    return NORMAL;
  }

}