package nxm.sys.prim;

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

/**
  Copies data from one file and appends it to another.

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

  private DataFile hi,ho;
  private Data data;
  int replay;
  double offset;

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

  public int open() {

    hi = MA.getDataFile ("IN");
    hi.open();

    ho = MA.getDataFile ("OUT");
    if (ho.find(-1)) {
      ho.open(BaseFile.INOUT|BaseFile.APPEND);
      String fi=hi.getFormat(), fo=ho.getFormat();
      if (!fi.equals(fo)) M.warning("Input format="+fi+" not equal to output format="+fo);
      int ti=hi.getType(), to=ho.getType();
      if (ti!=to) M.warning("Input type="+ti+" not equal to output type="+to);
    }
    else {
      ho = MA.getDataFile ("OUT",hi,0);
      ho.open();
    }

    offset = MA.getD("/OFFSET");
    if (offset>=0.0) ho.seek(offset);

    xfer = Math.max(1,(int)(bufSize/hi.dbpe));
    xfer = MA.getL("/TL",xfer);
    data = hi.getDataBuffer(xfer);
    replay = MA.getL("/REPLAY",1);

    return NORMAL;
  }

  public int process() {
    int n = hi.read(data);
    // write byte buffer directly to avoid reformatting
    if (n>0) ho.write(data.buf,0,(int)(n*hi.dbpe));
    else if (n==0) return NOOP;
    else if (--replay>0) hi.seek(0.0);
    else return FINISH;
    return NORMAL;
  }

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

}
