#include "mdb.h"
#include "SDDS.h"
#include "scan.h"

#define SET_PIPE 0
#define N_OPTIONS 1

char *option[N_OPTIONS] = {
  "pipe"};
char *USAGE = "carriageReturn2newline [<inputFile>] [<outputFile>] [-pipe[=in][,out]]";

int main(int argc, char **argv) {
  FILE *fid, *fid2;
  char *input, *output;
  SCANNED_ARG *scanned;
  long iArg;
  unsigned long pipeFlags;
  int character, nl = 0;

  SDDS_RegisterProgramName(argv[0]);
  argc = scanargs(&scanned, argc, argv);
  if (argc < 3)
    bomb(NULL, USAGE);
  input = output = NULL;
  pipeFlags = 0;

  for (iArg = 1; iArg < argc; iArg++) {
    if (scanned[iArg].arg_type == OPTION) {
      switch (match_string(scanned[iArg].list[0], option, N_OPTIONS, 0)) {
      case SET_PIPE:
        if (!processPipeOption(scanned[iArg].list + 1, scanned[iArg].n_items - 1, &pipeFlags))
          SDDS_Bomb("invalid -pipe syntax");
        break;
      default:
        bomb("invalid option seen", USAGE);
        break;
      }
    } else {
      if (!input)
        input = scanned[iArg].list[0];
      else if (!output)
        output = scanned[iArg].list[0];
      else
        bomb("too many filenames", USAGE);
    }
  }

  processFilenames("carriageReturn2newline", &input, &output, pipeFlags, 0, NULL);
  if (input) {
    if (!fexists(input))
      SDDS_Bomb("input file not found");
    if (!(fid = fopen(input, "r")))
      SDDS_Bomb("problem opening input file");
  } else {
    fid = stdin;
  }
  if (output) {
    fid2 = fopen(output, "w");
  } else {
    fid2 = stdout;
  }

  while (1) {
    character = fgetc(fid);
    if (character == EOF) {
      fclose(fid);
      fclose(fid2);
      return (0);
    } else {
      if (character == '\r') {
        fputc(10, fid2); /*newline*/
        nl = 1;
      } else if (character == '\n') {
        if (!nl)
          fputc(character, fid2); /*newline*/
        nl = 0;
      } else {
        fputc(character, fid2);
        nl = 0;
      }
    }
  }
  return (0);
}
