package nxm.sys.prim;

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

/**
  Copies data from an SDDS formatted file or SDDS network to an ordinary Midas file.

  @author Jeff Schoen

*/
public class sourcesdds extends Primitive {

  private DataFile hi,ho;
  private Data data;
  private SDDSPacket pkho, pkh = new SDDSPacket();
  private boolean strip,swap,live;

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

  public int open() {

    hi = MA.getDataFile ("IN","1000","SN,SB,SI",0);
    live = hi.getURL().startsWith("udp://");
    hi.open();

    ho = MA.getDataFile ("OUT",hi,0);

    if (hi.getPacketHandler()==null) M.error("Input is not an SDDS formatted file");

    strip = MA.getState("/STRIP",true);
    if (strip) ho.setPacketHandler(null);
    ho.open(); // moved here in 4.1.2 so strip works wNXM-3919

    xfer = (int)(1024/hi.dbpe);
    data = hi.getDataBuffer(xfer);
    swap = (data.bps==2) && !Convert.isBigEndian(data.rep);

    return (NORMAL);
  }

  public int process() {
    int n = hi.read(data);
    if (n>0) {
      if (swap) Convert.swap2 (data.buf,0,n);
      ho.write(data);
    }
    else if (n==0) return (NOOP);
    else return (FINISH);
    return (NORMAL);
  }

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

}
