package nxm.sys.prim;

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

/**
  Copies data from one file to another in reverse order.

  @author Jeff Schoen

*/
public class flip extends Primitive {

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

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

  public int open() {

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

    ho = MA.getDataFile ("OUT",hi,0);
    ho.setDelta(-hi.getDelta());
    ho.setStart(hi.getStart()+hi.size*hi.getDelta());
    ho.open();

    if (hi.getURL().equals(ho.getURL())) M.error("Cannot flip file onto itself");

    xfer = MA.getL("/TL", 1);
    data = hi.getDataBuffer(xfer);
    offset = hi.size-xfer;

    return (NORMAL);
  }

  public int process() {
    int n = hi.read(data,offset);
    if (n<0) return (FINISH);
    ho.write(data,n);
    offset -= n;
    if (offset<0) return (FINISH);
    else return (NORMAL);
  }

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

}
