package nxm.audio.prim;

import java.io.IOException;

import nxm.audio.lib.AudioWriter;
import nxm.sys.lib.DataFile;
import nxm.sys.lib.MidasException;
import nxm.sys.lib.Primitive;

/**
  Converts a AU file into BLUE format.

  @author Wayne G. Dengel II
*/
public class blue2au_g2 extends Primitive {

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

  public int open() {
    DataFile    inHcb = MA.getDataFile("INFILE");
    String      fname = MA.getS("OUTFILE");
    boolean     mulaw = MA.isPresent("/MULAW");

    String aux_write  = MR.getS("AUX.WRITE");
    String write_path = MR.getS("AUX."+aux_write);
    String user       = MR.getS("ENV.USER");

    int badchar = write_path.indexOf('+');
    if (badchar != -1) {
      write_path = new String(write_path.substring(0,badchar)+user+"/");
    }
    String outFile = new String(write_path+fname);

    inHcb.open();
    if (!inHcb.isOpen) return FINISH;

    int data_avail = 0;
    try {
      data_avail = (int) inHcb.avail();
      if (data_avail==0) {
        M.info("No data to read");
        return FINISH;
      }
      data_avail = data_avail*(int)inHcb.getBPE();
    }
    catch(Exception e) {
      throw new MidasException("Exception on AVAIL", e);
      // NTN: The line below discards any nested exception and makes debugging difficult.
      //      Additionally the code below M.error(..) is never executed.
      // M.error("Exception on AVAIL "+e);
      // return (FINISH);
    }
    byte[] data = new byte[data_avail];
    try {
      int got = inHcb.read(data,0,data_avail);
      AudioWriter.write(outFile.toLowerCase(),mulaw,data,(float)8000.0);
    }
    catch (IOException e) {
      M.error(e);
      return FINISH;
    }
    return FINISH;
  }
}
