Ejemplo n.º 1
0
int main(int argc, char **argv)
{
  FILE *fileID;
  SDDS_LAYOUT *layout=NULL;
  SDDS_FILEBUFFER *fBuffer=NULL;

  SDDS_DATASET SDDS_dataset, SDDS_dummy;
  SCANNED_ARG *s_arg;
  long i, j, i_arg, retval, page_number=0, size, columnOrder=0;
  int32_t rows=0;
  char *input, *output;
  unsigned long pipeFlags=0, flags=0;
  long noWarnings=0, tmpfile_used=0;
  long labeled = 0;
  
  long *parameterType, *columnType, *parameterIndex, *columnIndex;
  char **parameterUnits;
  void **columnData;
  char *buffer;
  static char printBuffer[SDDS_MAXLINE*16];
  static char formatbuffer[100], formatbuffer2[100];

  long binary=0, noRowCount=0;
  char *separator;
  char **parameter, **parameterFormat;
  char **column, **columnFormat, **columnUnits;
  long parameters=0, columns=0;

  input = output = NULL;
  parameter = column = parameterFormat = columnFormat = NULL;
  separator = NULL;

  parameterType = columnType = parameterIndex = columnIndex = NULL;
  columnData = NULL;
  parameterUnits = columnUnits = NULL;

  buffer = tmalloc(sizeof(char)*16);

  SDDS_RegisterProgramName(argv[0]);
  argc = scanargs(&s_arg, argc, argv);
  if (argc<3) 
    bomb(NULL, USAGE);
  
  for (i_arg=1; i_arg<argc; i_arg++) {
    if (s_arg[i_arg].arg_type==OPTION) {
      switch (match_string(s_arg[i_arg].list[0], option, N_OPTIONS, 0)) {
      case SET_OUTPUTMODE:
	if (s_arg[i_arg].n_items!=2)
	  SDDS_Bomb("invalid -outputMode syntax");
	switch (match_string(s_arg[i_arg].list[1], mode_name, MODES, 0)) {
	case ASCII_MODE:
	  binary = 0;
	  break;
	case BINARY_MODE:
	  binary = 1;
	  break;
	default:
	  SDDS_Bomb("invalid -outputMode syntax");
	  break;
	}
	break;
      case SET_SEPARATOR:
	if (s_arg[i_arg].n_items!=2)
	  SDDS_Bomb("invalid -separator syntax");
	separator = s_arg[i_arg].list[1];
	break;
      case SET_NOROWCOUNT:
	if (s_arg[i_arg].n_items!=1)
	  SDDS_Bomb("invalid -noRowCount syntax");
	noRowCount = 1;
	break;
      case SET_ORDER:
	if (s_arg[i_arg].n_items!=2)
	  SDDS_Bomb("invalid -order syntax");
	switch (match_string(s_arg[i_arg].list[1], order_names, ORDERS, 0)) {
	case ROW_ORDER:
	  columnOrder = 0;
	  break;
	case COLUMN_ORDER:
	  columnOrder = 1;
	  break;
	default:
	  SDDS_Bomb("invalid -order syntax");
	  break;
	}
	break;
      case SET_PARAMETER:
	if ((s_arg[i_arg].n_items!=2) && (s_arg[i_arg].n_items!=4))
	  SDDS_Bomb("invalid -parameter syntax");
	parameter = trealloc(parameter, sizeof(*parameter)*(++parameters));
	parameterFormat = trealloc(parameterFormat, sizeof(*parameterFormat)*(parameters));
	parameter[parameters-1] = s_arg[i_arg].list[1];
	parameterFormat[parameters-1] = NULL;
	s_arg[i_arg].n_items -= 2;
	if (!scanItemList(&flags, s_arg[i_arg].list+2, &s_arg[i_arg].n_items,  0,
			  "format", SDDS_STRING, &(parameterFormat[parameters-1]), 1, 0,
			  NULL))
	  SDDS_Bomb("invalid -parameter syntax");
        if (parameterFormat[parameters-1]) {
          replaceString(formatbuffer, parameterFormat[parameters-1], "ld", PRId32, -1, 0);
          replaceString(formatbuffer2, formatbuffer, "lu", PRIu32, -1, 0);
          parameterFormat[parameters-1] = 
            malloc(sizeof(*(parameterFormat[parameters-1])) * (strlen(formatbuffer2) + 1));
          sprintf(parameterFormat[parameters-1], "%s", formatbuffer2);
        }
	break;
      case SET_COLUMN:
	if ((s_arg[i_arg].n_items<2))
	  SDDS_Bomb("invalid -column syntax");
	column = trealloc(column, sizeof(*column)*(++columns));
	columnFormat = trealloc(columnFormat, sizeof(*columnFormat)*(columns));
	column[columns-1] = s_arg[i_arg].list[1];
	columnFormat[columns-1] = NULL;
	s_arg[i_arg].n_items -= 2;
	if (!scanItemList(&flags, s_arg[i_arg].list+2, &s_arg[i_arg].n_items,  0,
			  "format", SDDS_STRING, &(columnFormat[columns-1]), 1, 0,
			  NULL))
	  SDDS_Bomb("invalid -columns syntax");
        if (columnFormat[columns-1]) {
          replaceString(formatbuffer, columnFormat[columns-1], "ld", PRId32, -1, 0);
          replaceString(formatbuffer2, formatbuffer, "lu", PRIu32, -1, 0);
          columnFormat[columns-1] = 
            malloc(sizeof(*(columnFormat[columns-1])) * (strlen(formatbuffer2) + 1));
          sprintf(columnFormat[columns-1], "%s", formatbuffer2);
        }
	break;
      case SET_PIPE:
	if (!processPipeOption(s_arg[i_arg].list+1, s_arg[i_arg].n_items-1, &pipeFlags))
	  SDDS_Bomb("invalid -pipe syntax");
	break;
      case SET_NOWARNINGS:
	if (s_arg[i_arg].n_items!=1)
	  SDDS_Bomb("invalid -nowarnings syntax");
	noWarnings = 1;
	break;
      case SET_LABELED:
        labeled = 1;
        break;
      default:
	fprintf(stderr, "error: unknown switch: %s\n", s_arg[i_arg].list[0]);
	exit(1);
	break;
      }
    } else {
      if (input == NULL) {
	input = s_arg[i_arg].list[0];
      } else if (output == NULL) {
	output = s_arg[i_arg].list[0];
      } else {
	fprintf(stderr, "too many filenames");
	exit(1);
      }
    }
  }
  
  processFilenames("sdds2plaindata", &input, &output, pipeFlags, noWarnings, &tmpfile_used);

  if (!columns && !parameters)
    SDDS_Bomb("you must specify one of the -column or the -parameter options");
  if (!separator) {
    cp_str(&separator, "");
  }

  if (!SDDS_InitializeInput(&SDDS_dataset, input)) {
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
    exit(1);
  }

  if (parameters) {
    parameterType = tmalloc(sizeof(*parameterType)*parameters);
    parameterIndex = tmalloc(sizeof(*parameterIndex)*parameters);
    parameterUnits = tmalloc(sizeof(*parameterUnits)*parameters);
    for (i=0; i<parameters; i++) {
      if ((parameterIndex[i]=SDDS_GetParameterIndex(&SDDS_dataset, parameter[i]))<0) {
	fprintf(stderr, "error: parameter %s does not exist\n", parameter[i]);
	exit(1);
      }
      if ((parameterType[i]=SDDS_GetParameterType(&SDDS_dataset, parameterIndex[i]))<=0 ||
          SDDS_GetParameterInformation(&SDDS_dataset, "units", &parameterUnits[i], SDDS_GET_BY_INDEX, parameterIndex[i])!=SDDS_STRING) {
	SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
	exit(1);
      }
    }
  }
  if (columns) {
    columnType = tmalloc(sizeof(*columnType)*columns);
    columnIndex = tmalloc(sizeof(*columnIndex)*columns);
    columnData = tmalloc(sizeof(*columnData)*columns);
    columnUnits = tmalloc(sizeof(*columnUnits)*columns);
    for (i=0; i<columns; i++) {
      if ((columnIndex[i]=SDDS_GetColumnIndex(&SDDS_dataset, column[i]))<0) {
	fprintf(stderr, "error: column %s does not exist\n", column[i]);
	exit(1);
      }
      if ((columnType[i]=SDDS_GetColumnType(&SDDS_dataset, columnIndex[i]))<=0 ||
          SDDS_GetColumnInformation(&SDDS_dataset, "units", &columnUnits[i], SDDS_GET_BY_INDEX, columnIndex[i])!=SDDS_STRING) {
	SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
	exit(1);
      }
    }
  }

  if (!output) {
    if (binary) {
#if defined(_WIN32)
      if (_setmode(_fileno(stdout), _O_BINARY) == -1) {
	fprintf(stderr, "error: unable to set stdout to binary mode\n");
	exit(1);
      }      
#endif
    }
    fileID = stdout;
  } else {
    if (binary) {
      fileID = fopen(output, "wb");
    } else {
      fileID = fopen(output, "w");
    }
  }
  if (fileID == NULL) {
    fprintf(stderr, "unable to open output file for writing\n");
    exit(1);
  }

  if (binary) {
    layout = &SDDS_dataset.layout;
    fBuffer = &SDDS_dummy.fBuffer;
    fBuffer->buffer = NULL;
    if (!fBuffer->buffer) {
      if (!(fBuffer->buffer = fBuffer->data = SDDS_Malloc(sizeof(char)*SDDS_FILEBUFFER_SIZE))) {
	fprintf(stderr, "Unable to do buffered read--allocation failure\n");
	exit(1);
      }
      fBuffer->bufferSize = SDDS_FILEBUFFER_SIZE;
      fBuffer->bytesLeft = SDDS_FILEBUFFER_SIZE;
    }
  }

  retval = -1;
  while (retval!=page_number && (retval=SDDS_ReadPage(&SDDS_dataset))>0) {
    if (page_number && retval!=page_number)
      continue;
    if (columns != 0) {
      if ((rows=SDDS_CountRowsOfInterest(&SDDS_dataset))<0) {
	SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
	exit(1);
      }
    }
    if ((binary) && (!noRowCount)) {
      if (!SDDS_BufferedWrite(&rows, sizeof(rows), fileID, fBuffer)) {
	fprintf(stderr, "Unable to write page--failure writing number of rows\n");
	exit(1);
      }
    }

    for (i=0; i<parameters; i++) {
      if (binary) {
	/*
	if (layout->parameter_definition[i].fixed_value)
	  continue;
	*/
	if (parameterType[i]==SDDS_STRING) {
	  if (!SDDS_WriteBinaryString(*((char**)SDDS_dataset.parameter[parameterIndex[i]]), fileID, fBuffer)) {
	    fprintf(stderr, "Unable to write parameters--failure writing string\n");
	    exit(1);
	  }
	}
	else if (!SDDS_BufferedWrite(SDDS_dataset.parameter[parameterIndex[i]], 
				     SDDS_type_size[layout->parameter_definition[parameterIndex[i]].type-1],
				     fileID, fBuffer)) {
	  fprintf(stderr, "Unable to write parameters--failure writing value\n");
	  exit(1);
	}
      } else {
	if (!SDDS_GetParameter(&SDDS_dataset, parameter[i], buffer)) {
	  SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
	  exit(1);
	}
	SDDS_SprintTypedValue(buffer, 0, parameterType[i], 
			      parameterFormat[i], 
			      printBuffer,
			      0);
        if (labeled) {
          fputs(parameter[i], fileID);
          fputs(separator, fileID);
          if (parameterUnits[i])
            fputs(parameterUnits[i], fileID);
          fputs(separator, fileID);
        }
	fputs(printBuffer, fileID);
	fputc('\n', fileID);
      }
    }
    
    if (!binary) {
      if (!noRowCount)
	fprintf(fileID, "\t%" PRId32 "\n", rows);
      if (labeled && columns) {
        for (j=0; j<columns; j++) {
          fputs(column[j], fileID);
          if (j!=(columns-1))
            fputs(separator, fileID);
        }
        fputc('\n', fileID);
        for (j=0; j<columns; j++) {
          if (columnUnits[j])
            fputs(columnUnits[j], fileID);
          if (j!=(columns-1))
            fputs(separator, fileID);
        }
        fputc('\n', fileID);
      }
    }

    if (columns) {
      if (rows) {
	if (binary) {
	  if (columnOrder) {
	    for (j=0; j<columns; j++) {
	      if (columnType[j]==SDDS_STRING) {
		for (i=0; i<rows; i++) {	    
		  if (!SDDS_WriteBinaryString(*((char**)SDDS_dataset.data[columnIndex[j]]+i), fileID, fBuffer)) {
		    fprintf(stderr, "Unable to write rows--failure writing string\n");
		    exit(1);
		  }
		}
	      } else {
		size = SDDS_type_size[columnType[j]-1];
		for (i=0; i<rows; i++) {	    
		  if (!SDDS_BufferedWrite((char*)SDDS_dataset.data[columnIndex[j]]+i*size, size, fileID, fBuffer)) {
		    fprintf(stderr, "Unable to write rows--failure writing string\n");
		    exit(1);
		  }
		}
	      }
	    }
	  } else {
	    for (i=0; i<rows; i++) {	    
	      for (j=0; j<columns; j++) {
		if (columnType[j]==SDDS_STRING) {
		  if (!SDDS_WriteBinaryString(*((char**)SDDS_dataset.data[columnIndex[j]]+i), fileID, fBuffer)) {
		    fprintf(stderr, "Unable to write rows--failure writing string\n");
		    exit(1);
		  }
		} else {
		  size = SDDS_type_size[columnType[j]-1];
		  if (!SDDS_BufferedWrite((char*)SDDS_dataset.data[columnIndex[j]]+i*size, size, fileID, fBuffer)) {
		    fprintf(stderr, "Unable to write rows--failure writing string\n");
		    exit(1);
		  }
		}
	      }
	    }
	  }
	} else {
	  for (i=0; i<columns; i++) {
	    if (!(columnData[i]=SDDS_GetInternalColumn(&SDDS_dataset, column[i]))) {
	      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
	      exit(1);
	    }
	  }
	  if (columnOrder) {
	    for (i=0; i<columns; i++) {
	      for (j=0; j<rows; j++) {
		SDDS_SprintTypedValue(columnData[i], j, columnType[i], 
				      columnFormat[i], 
				      printBuffer, 
				      0);
		fputs(printBuffer, fileID);
		if (j!=rows-1)
		  fprintf(fileID, separator);
	      }
	      fputc('\n', fileID);
	    }
	  } else {
	    for (j=0; j<rows; j++) {
	      for (i=0; i<columns; i++) {
		SDDS_SprintTypedValue(columnData[i], j, columnType[i], 
				      columnFormat[i], 
				      printBuffer, 
				      0);
		fputs(printBuffer, fileID);
		if (i!=columns-1)
		  fprintf(fileID, separator);
	      }
	      fputc('\n', fileID);
	    }
	  }
	}
      }
    }
    
    if (retval==0) {
      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
      exit(1);
    }
  }

  if (binary) {
    if (!SDDS_FlushBuffer(fileID, fBuffer)) {
      SDDS_SetError("Unable to write page--buffer flushing problem (SDDS_WriteBinaryPage)");
      return 0;
    }
  } else {
    fflush(fileID);
  }
  fclose(fileID);


  if (!SDDS_Terminate(&SDDS_dataset)) {
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
    exit(1);
  }

exit(0);
}
Ejemplo n.º 2
0
int main(int argc, char **argv)
{
    SDDS_TABLE SDDS_table;
    SCANNED_ARG *scanned;
    unsigned long majorOrderFlag;
    long i_arg;
    char *input, *output, *definition;
    long hsize, vsize;
    char *data, *data_name;
    char ts1[100], ts2[100];
    FILE *fpi;
    short columnMajorOrder=0;

    argc = scanargs(&scanned, argc, argv);
    if (argc<4)
        bomb(NULL, USAGE);

    input = output = data_name = NULL;
    hsize = DEFAULT_HSIZE;
    vsize = DEFAULT_VSIZE;
    definition = NULL;

    for (i_arg=1; i_arg<argc; i_arg++) {
        if (scanned[i_arg].arg_type==OPTION) {
            /* process options here */
            switch (match_string(scanned[i_arg].list[0], option, N_OPTIONS, 0)) {
            case SET_MAJOR_ORDER:
              majorOrderFlag=0;
              scanned[i_arg].n_items--;
              if (scanned[i_arg].n_items>0 &&
                  (!scanItemList(&majorOrderFlag, scanned[i_arg].list+1, &scanned[i_arg].n_items, 0,
                                 "row", -1, NULL, 0, SDDS_ROW_MAJOR_ORDER,
                                 "column", -1, NULL, 0, SDDS_COLUMN_MAJOR_ORDER,
                                   NULL)))
                SDDS_Bomb("invalid -majorOrder syntax/values");
              if (majorOrderFlag&SDDS_COLUMN_MAJOR_ORDER)
                columnMajorOrder=1;
              else if (majorOrderFlag&SDDS_ROW_MAJOR_ORDER)
                columnMajorOrder=0;
              break;
              case SET_DEFINITION:
                data_name = scanned[i_arg].list[1];
                definition = process_column_definition(scanned[i_arg].list+1, 
                                                       scanned[i_arg].n_items-1);
                if (!strstr(definition, "type=character"))
                  SDDS_Bomb("data type must be character for now");
                break;
              case SET_SIZE:
                if (scanned[i_arg].n_items!=3 ||
                    sscanf(scanned[i_arg].list[1], "%ld", &hsize)!=1 || hsize<=0 ||
                    sscanf(scanned[i_arg].list[2], "%ld", &vsize)!=1 || vsize<=0)
                    bomb("invalid -size syntax", USAGE);
                break;
            default:
              bomb("invalid option seen", USAGE);
              break;
            }
        }
        else {
          if (!input)
            input = scanned[i_arg].list[0];
          else if (!output)
            output = scanned[i_arg].list[0];
            else
              bomb("too many filenames", USAGE);
        }
    }
    if (!input)
        SDDS_Bomb("input file not seen");
    if (!output)
        SDDS_Bomb("output file not seen");
    if (!definition)
        SDDS_Bomb("definition not seen");

    sprintf(ts1, "%ld", hsize);
    sprintf(ts2, "%ld", vsize);
    if (!SDDS_InitializeOutput(&SDDS_table, SDDS_BINARY, 0, 
                               "screen image from raw file", "screen image",
                               output) ||
        SDDS_ProcessColumnString(&SDDS_table, definition, 0)<0 || 
        SDDS_DefineParameter(&SDDS_table, "NumberOfRows", NULL, NULL, "number of rows",
                              NULL, SDDS_LONG, ts1)<0 ||
        !SDDS_DefineParameter(&SDDS_table, "NumberOfColumns", NULL, NULL, 
                              "number of columns", NULL, SDDS_LONG, ts2)<0)
      SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
    SDDS_table.layout.data_mode.column_major = columnMajorOrder;
    if (!SDDS_WriteLayout(&SDDS_table) || !SDDS_StartTable(&SDDS_table, hsize*vsize))
      SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);

    data = tmalloc(sizeof(*data)*hsize*vsize);
    fpi = fopen_e(input, "r", 0);
    if (fread(data, sizeof(*data), hsize*vsize, fpi)!=hsize*vsize)
        SDDS_Bomb("unable to read (all) data from input file");
    fclose(fpi);
    if (!SDDS_SetColumn(&SDDS_table, SDDS_SET_BY_NAME, data, hsize*vsize, 
                        data_name) ||
        !SDDS_WriteTable(&SDDS_table) || !SDDS_Terminate(&SDDS_table))
        SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
    return(0);
}
Ejemplo n.º 3
0
int main( int argc, char **argv)
{
  SCANNED_ARG *s_arg;
  int i_arg;
  long address;
  long gpibDeviceHandle;
  long messages;
  long i, doStream;
  char **message;
  char reply[MAX_LENGTH], nextMessage[MAX_LENGTH];
  double sleepTime = 0.5;
  
  argc = scanargs(&s_arg, argc, argv);
  if (argc<2 || argc>(3+N_OPTIONS))  {
	usage();
	bomb("too few or too many arguments\n", NULL);
  }

  address = -1;
  messages = 0;
  message = NULL;
  doStream = 0;
  
  for (i_arg=1; i_arg<argc; i_arg++) {
    if (s_arg[i_arg].arg_type==OPTION) {
      switch (match_string(s_arg[i_arg].list[0], option, N_OPTIONS, 0)) {
      case SET_ADDRESS:
        if (s_arg[i_arg].n_items!=2 ||
            sscanf(s_arg[i_arg].list[1], "%ld", &address)!=1  ||
            address<0 || address>31) 
          bomb("invalid -address syntax\n", NULL);
        break;
      case SET_MESSAGELIST:
        if (s_arg[i_arg].n_items<2)
          bomb("invalid -messageList syntax\n", NULL);
        messages = s_arg[i_arg].n_items-1;
        if (!(message=malloc(sizeof(*message)*(s_arg[i_arg].n_items-1))))
          bomb("memory allocation failure", NULL);
        for (i=0; i<messages; i++) {
          if (!(message[i] = malloc(sizeof(**message)*(strlen(s_arg[i_arg].list[i+1])+2))))
            bomb("memory allocation failure\n", NULL);
          strcpy(message[i], s_arg[i_arg].list[i+1]);
        }
        break;
      case SET_STREAM:
        doStream = 1;
        break;
      case SET_SLEEPTIME:
        if (s_arg[i_arg].n_items!=2 ||
            sscanf(s_arg[i_arg].list[1], "%lf", &sleepTime)!=1 ||
            sleepTime<0)
          bomb("invalid -sleepTime syntax\n", NULL);
        break;
      default:
        bomb("unknown option given\n", NULL);
        break;
      }
    }
    else 
      bomb("unknown option given\n", NULL);
  }

  if (doStream && messages)
    bomb("Give -stream or -messageList, not both\n", NULL);
  
  if (address<0)
    bomb("address not given\n", NULL);
  
/*  gpibDeviceHandle = gpibOpenDevice("gpib0", address, 0, 10, 1, 10, 0,
                          NULL, GpibOpenDevice_NoDeviceClear); */

  gpibDeviceHandle = gpibOpenDevice(0, address, 0); 
  usleep(500000);

  if (messages || doStream) {
    i = 0;
    if (doStream)
      messages = 1;  /* ensures that loop doesn't terminate unless EOF is received */
    while (i!=messages) {
      if (doStream) {
        if (!fgets(nextMessage, MAX_LENGTH, stdin))
          break;
        if (strlen(nextMessage)<2)
          continue;  /* just a newline */
        nextMessage[strlen(nextMessage)-1] = 0;
      } else {
        strcpy(nextMessage, message[i]);
        i ++;
      }
      if (nextMessage[strlen(nextMessage)-1]=='?') {
        nextMessage[strlen(nextMessage)-1] = 0;
        gpibWrite(gpibDeviceHandle, nextMessage);
        usleep((long)(sleepTime*1e6));
        gpibRead(gpibDeviceHandle, reply, MAX_LENGTH-1);
        fprintf(stdout, "%s\n", reply);
        fflush(stdout);
      } else
        gpibWrite(gpibDeviceHandle, nextMessage);
      usleep((long)(sleepTime*1e6));
    }
  }
  else {
    gpibRead(gpibDeviceHandle, reply, MAX_LENGTH-1);
    fprintf(stdout, "%s\n", reply);
  }

  return 0;
}
Ejemplo n.º 4
0
int main(int argc, char **argv)
{
    SDDS_DATASET SDDS_dataset;
    SCANNED_ARG *scanned;
    long i_arg;
    char *input, *output, *definition;
    long hsize, vsize;
    char *data, *data_name;
    char header[200];
    char ts1[100], ts2[100];
    FILE *fpi;
    unsigned long pipeFlags, majorOrderFlag;
    short columnMajorOrder = 0;

    SDDS_RegisterProgramName(argv[0]);

    argc = scanargs(&scanned, argc, argv);
    if (argc<4)
        bomb(NULL, USAGE);

    input = output = data_name = NULL;
    definition = NULL;
    pipeFlags = 0;
    hsize = vsize = 0;
    for (i_arg=1; i_arg<argc; i_arg++) {
        if (scanned[i_arg].arg_type==OPTION) {
            /* process options here */
            switch (match_string(scanned[i_arg].list[0], option, N_OPTIONS, 0)) {
            case SET_MAJOR_ORDER:
              majorOrderFlag=0;
              scanned[i_arg].n_items--;
              if (scanned[i_arg].n_items>0 &&
                  (!scanItemList(&majorOrderFlag, scanned[i_arg].list+1, &scanned[i_arg].n_items, 0,
                                 "row", -1, NULL, 0, SDDS_ROW_MAJOR_ORDER,
                                 "column", -1, NULL, 0, SDDS_COLUMN_MAJOR_ORDER,
                                   NULL)))
                SDDS_Bomb("invalid -majorOrder syntax/values");
              if (majorOrderFlag&SDDS_COLUMN_MAJOR_ORDER)
                columnMajorOrder=1;
              else if (majorOrderFlag&SDDS_ROW_MAJOR_ORDER)
                columnMajorOrder=0;
              break;
            case SET_DEFINITION:
              data_name = scanned[i_arg].list[1];
              definition = process_column_definition(scanned[i_arg].list+1, 
                                                     scanned[i_arg].n_items-1);
              if (!strstr(definition, "type=character"))
                SDDS_Bomb("data type must be character for now");
              break;
            case SET_PIPE:
              if (!processPipeOption(scanned[i_arg].list+1, scanned[i_arg].n_items-1, &pipeFlags))
                SDDS_Bomb("invalid -pipe syntax");
              break;
              default:
                bomb("invalid option seen", USAGE);
                break;
            }
        }
        else {
          if (!input)
            input = scanned[i_arg].list[0];
          else if (!output)
            output = scanned[i_arg].list[0];
          else
            bomb("too many filenames", USAGE);
        }
    }
    
    processFilenames("lba2sdds", &input, &output, pipeFlags, 0, NULL);

    if (!definition)
        SDDS_Bomb("definition not seen");

    if (input)
        fpi = fopen_e(input, "r", 0);
    else
        fpi = stdin;

    if (fread(header, sizeof(*header), 200, fpi)!=200) 
        SDDS_Bomb("unable to read LBA file header");
    switch (header[0]) {
      case 'A':
        hsize = vsize = 120;
        break;
      case 'B':
        vsize = 256;
        hsize = 240;
        break;
      case 'C':
        vsize = 512;
        hsize = 480;
        break;
      default:
        SDDS_Bomb("data does not appear to be in LBA format--invalid frame type");
        break;
        }

    sprintf(ts1, "%ld", hsize);
    sprintf(ts2, "%ld", vsize);
    if (!SDDS_InitializeOutput(&SDDS_dataset, SDDS_BINARY, 0, 
                               "screen image from LBA file", "screen image",
                               output) ||
        SDDS_ProcessColumnString(&SDDS_dataset, definition, 0)<0 || 
        SDDS_DefineParameter(&SDDS_dataset, "NumberOfRows", NULL, NULL, "number of rows",
                             NULL, SDDS_LONG, ts1)<0 ||
        SDDS_DefineParameter(&SDDS_dataset, "NumberOfColumns", NULL, NULL, 
                             "number of columns", NULL, SDDS_LONG,
                             ts2)<0) 
      SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
    SDDS_dataset.layout.data_mode.column_major = columnMajorOrder;
    if (!SDDS_WriteLayout(&SDDS_dataset))
      SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
    
    data = tmalloc(sizeof(*data)*hsize*vsize);
    do {
        if (fread(data, sizeof(*data), hsize*vsize, fpi)!=hsize*vsize)
            SDDS_Bomb("unable to read (all) data from input file");
        if (!SDDS_StartPage(&SDDS_dataset, hsize*vsize) ||
            !SDDS_SetColumn(&SDDS_dataset, SDDS_SET_BY_NAME, data, hsize*vsize, 
                            data_name) ||
            !SDDS_WritePage(&SDDS_dataset))
            SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
        } while (fread(header, sizeof(*header), 200, fpi)==200) ;
    fclose(fpi);
    if (!SDDS_Terminate(&SDDS_dataset))
        SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
    return(0);
}
Ejemplo n.º 5
0
int main(int argc, char *argv[]) {
    char *filename=NULL;
    MPI_DATASET *MPI_dataset;
    SDDS_DATASET SDDS_dataset;
    char buf[256];
    int32_t total_rows=8000, i, j, mpi_code, cols=8, rows, columnOrder=0, ID_offset, myid, n_processors, collective_io=0, i_arg;
    double startTime =0;
    MPI_Comm comm;
    SCANNED_ARG *s_arg;

    MPI_Init(&argc,&argv);
    argc = scanargs(&s_arg, argc, argv);
    if (argc<2)
        bomb(NULL, USAGE);
    for (i_arg=1; i_arg<argc; i_arg++) {
        if (s_arg[i_arg].arg_type==OPTION) {
            switch (match_string(s_arg[i_arg].list[0], option, N_OPTIONS, 0)) {
            case SET_COLUMN_ORDER:
                columnOrder = 1;
                break;
            case SET_COLLECTIVE_IO:
                collective_io = 1;
                break;
            case SET_TOTAL_ROWS:
                if (s_arg[i_arg].n_items!=2)
                    SDDS_Bomb("Invalid -totalrows syntax given!");
                if (!get_long(&total_rows, s_arg[i_arg].list[1]))
                    SDDS_Bomb("Invalid -totalrows value given!");
                break;
            default:
                break;
            }
        } else if (!filename)
            filename = s_arg[i_arg].list[0];
        else
            SDDS_Bomb("Too many files.");
    }

    /* 1. set the communicator for MPI IO */
    SDDS_SetDefaultBufferSize(4000000);

    comm = MPI_COMM_WORLD;
    if (MPI_SUCCESS != (mpi_code=MPI_Comm_rank(comm, &myid)))
        SDDS_MPI_GOTO_ERROR(stderr,  "MPI_Comm_rank failed", mpi_code, 1);
    if (MPI_SUCCESS != (mpi_code=MPI_Comm_size(comm, &n_processors)))
        SDDS_MPI_GOTO_ERROR(stderr, "MPI_Comm_size failed", mpi_code, 1);
    SDDS_MPI_Setup(&SDDS_dataset, 1,  n_processors, myid, comm, 1);
    MPI_dataset = SDDS_dataset.MPI_dataset;

    /* 2. open file (all processors) */

    /* 3. initialize output, right now, only write binary files (all processors) */

    fprintf(stderr, "rank=%d, initialize input \n", myid);
    if (!SDDS_MPI_InitializeOutput(&SDDS_dataset, NULL, NULL, filename, SDDS_MPI_WRITE_ONLY, columnOrder))
        SDDS_Bomb("Unable to initalize output");
    MPI_dataset->collective_io = collective_io;
    for (i=0; i<cols; i++) {
        sprintf(buf,"col%d", i);
        if ( !SDDS_DefineSimpleColumn(&SDDS_dataset, buf, NULL, SDDS_DOUBLE))
            SDDS_MPI_BOMB("SDDS define column and parameters  failed.", &(MPI_dataset->MPI_file));
    }
    if (!SDDS_SaveLayout(&SDDS_dataset))
        SDDS_MPI_BOMB("SDDS define column and parameters  failed.", &(MPI_dataset->MPI_file));
    fprintf(stderr, "rank=%d, layout defined. \n", myid);

    startTime = MPI_Wtime();
    if (!SDDS_WriteLayout(&SDDS_dataset))
        SDDS_MPI_BOMB("SDDS_MPI_WriteLayout failed.", &(MPI_dataset->MPI_file));
    fprintf(stderr, "rank=%d, total_rows=%d, layout written spent %f seconds. \n", myid, total_rows, MPI_Wtime() - startTime);

    rows = total_rows/n_processors;
    if (myid < (ID_offset=total_rows%(n_processors))) {
        rows ++;
    }

    if (!SDDS_DisconnectFile(&SDDS_dataset))
        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    if (!SDDS_StartPage(&SDDS_dataset, rows))
        SDDS_MPI_BOMB("SDDS start page  failed.", &MPI_dataset->MPI_file);
    /* 7. set data values */
    for (i=0; i<rows/2; i++) {
        for (j=0; j<cols; j++) {
            sprintf(buf,"col%d", j);
            if (!SDDS_SetRowValues(&SDDS_dataset, SDDS_SET_BY_NAME|SDDS_PASS_BY_VALUE, i,
                                   buf, (double)i, NULL))
                SDDS_MPI_BOMB("SDDS_SetRowValues failed.", &MPI_dataset->MPI_file);
        }
    }
    fprintf(stderr, "rank=%d, row set. \n", myid);
    startTime = MPI_Wtime();
    if (!SDDS_ReconnectFile(&SDDS_dataset) || !SDDS_WritePage(&SDDS_dataset))
        SDDS_MPI_BOMB("SDDS_MPI_WritePage failed.", &MPI_dataset->MPI_file);
    fprintf(stderr, "rank=%d, page write spent %f. \n", myid, MPI_Wtime() - startTime);

    if (!SDDS_Terminate(&SDDS_dataset))
        SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
    /* close file is done inside SDDS_MPI_Terminate*/
    MPI_Finalize();
    return 0;
}
Ejemplo n.º 6
0
/*
 * Parse(): scan current portion of buffer for given tag.
 * If found, parse tag arguments and call 'func' for it.
 * The result of func is inserted at the current position
 * in the buffer.
 */
int parse(
    char **buf,         /* buffer */
    long i,             /* offset in buffer */
    char *tag,          /* tag to handle  */
    char *    (*func) (long,
                       const char **)   /* function to call for 'tag' */
    )
{
    /* the name of the vairable ... */
    char     *val;
    long      valln;
    char    **args;
    char     *end;
    long      end_offset;
    int       argc;
    size_t    taglen = strlen(tag);

    /* Current position in buffer should start with 'tag' */
    if (strncmp((*buf) + i, tag, taglen) != 0) {
        return 0;
    }
    /* .. and match exactly (a whitespace following 'tag') */
    if (!isspace(*((*buf) + i + taglen))) {
        return 0;
    }
#ifdef DEBUG_PARSER
    printf("parse(): handling tag '%s'\n", tag);
#endif

    /* Scan for arguments following the tag;
       scanargs() puts \0 into *buf ... so after scanargs it is probably
       not a good time to use strlen on buf */
    end = scanargs((*buf) + i + taglen, &argc, &args);
    if (end) {
        /* got arguments, call function for 'tag' with arguments */
        val = func(argc, (const char **) args);
        free(args-1);
    } else {
        /* next call, try parsing at current offset +1 */
        end = (*buf) + i + 1;

        val = stralloc("[ERROR: Parsing Problem with the following text\n"
                       " Check original file. This may have been altered "
                       "by parsing.]\n\n");
    }

    /* remember offset where we have to continue parsing */
    end_offset = end - (*buf);

    valln = 0;
    if (val) {
        valln = strlen(val);
    }

    /* Optionally resize buffer to hold the replacement value:
       Calculating the new length of the buffer is simple. add current
       buffer pos (i) to length of string after replaced tag to length
       of replacement string and add 1 for the final zero ... */
    if (end - (*buf) < (i + valln)) {
        /* make sure we do not shrink the mallocd block */
        size_t    newbufsize = i + strlen(end) + valln + 1;

        *buf = (char *) rrd_realloc(*buf, newbufsize);

        if (*buf == NULL) {
            perror("Realoc buf:");
            exit(1);
        };
    }

    /* Update new end pointer:
       make sure the 'end' pointer gets moved along with the 
       buf pointer when realloc moves memory ... */
    end = (*buf) + end_offset;

    /* splice the variable:
       step 1. Shift pending data to make room for 'val' */
    memmove((*buf) + i + valln, end, strlen(end) + 1);

    /* step 2. Insert val */
    if (val) {
        memmove((*buf) + i, val, valln);
        free(val);
    }
    return (valln > 0 ? valln - 1 : valln);
}
Ejemplo n.º 7
0
int main(int argc,char **argv)
{
    char reserved[100]; /* buffer to skip reserved bytes */
    short f_type; /* MCS file type */
    char trigger; /* Trigger Flag */
    char dwell_flag; /* External Dwell Flag */
    char dwell_units; /* 0=us, 1=ms, 2=sec, 3=ns */
    char acq_mode; /* Acquisition mode flag 0=replace, 1=sum */
    unsigned long dwell_913; /* Dwell time in old 913 format */
    unsigned short pass_length; /* pass length in channels */
    unsigned long pass_count;
    unsigned long pass_count_preset;
    char acq_time[9]; /* buffer for acquisition time */
    char acq_date[9]; /* buffer for acquisition date */
    unsigned short mark_chan; /* first marker channel */
    char mcs_num; /* 1-8 are valid */
    char cal_flag; /* 0=no calibration */
    char cal_units[4]; /* calibration units */
    float cal_zero; /* calibration zero intercept */
    float cal_slope; /* calibration slope */
    char id_byte; /* always 0xaa */
    char detector_len; /* Detector description length */
    char detector[65]; /* detector description */
    char sample_len; /* Sample description length */
    char sample[65]; /* Sample description */
    char disc_sel; /* 0=SCA otherwise Disc */
    char disc_edge; /* 0=falling else rising */
    float disc; /* disc setting in volts */
    float sca_uld; /* sca upper-level in volts */
    float sca_lld; /* sca lower-level in volts */
    float dwell; /* dwell time in dwell_units */
    char consistent; /* settings consistent flag */
    char mcs_id[9]; /* MCS ID string "0914-001" */
    
    FILE *fpi;
    char *input, *output;
    SDDS_DATASET SDDS_dataset;
    SCANNED_ARG *scanned;
    long i, i_arg;
    char ts1[256], ts2[256], ts3[256], ts4[256];
    unsigned long *ucount;
    long *count, *channel;
    long ascii;

    SDDS_RegisterProgramName(argv[0]);
    argc = scanargs(&scanned, argc, argv);
    if (argc<3) 
        bomb(NULL, USAGE);
    input = output = NULL;
    ascii = 0;
    for (i_arg=1; i_arg<argc; i_arg++) {
        if (scanned[i_arg].arg_type==OPTION) {
            switch (match_string(scanned[i_arg].list[0], option, N_OPTIONS, 0)) {
              case SET_ASCII:
                ascii = 1;
                break;
              default:
                bomb("invalid option seen", USAGE);
                break;
                }
            }
        else {
            if (!input)
                input = scanned[i_arg].list[0];
            else if (!output)
                output = scanned[i_arg].list[0];
            else
                bomb("too many filenames", USAGE);
            }
        }
    if (!input)
        SDDS_Bomb("input file not seen");
    if (!output)
        SDDS_Bomb("output file not seen");
    fpi = fopen_e(input, "r", 0);

    /***************************************************************************/
    /*    Header Data     */
    /* Read header info from MCS file */
    /***************************************************************************/
    /* Read filetype -4 (MCS) */
    fread(&f_type,sizeof(short),1,fpi);
    swapshort(&f_type);
    if (f_type != MCS) {
        fprintf(stderr, "Not a valid file: f_type = %hx\n", f_type);
        exit(1);
        }
    fread(&trigger,sizeof(char),1,fpi); /* Read Trigger Flag */
    fread(&dwell_flag,sizeof(char),1,fpi); /* Read dwell flag */
    fread(&dwell_units,sizeof(char),1,fpi);/* Read dwell units */
    fread(&acq_mode,sizeof(char),1,fpi);
    fread(&dwell_913,sizeof(long),1,fpi);
    swapulong(&dwell_913);
    fread(&pass_length,sizeof(short),1,fpi);
    swapushort(&pass_length);
    fread(&pass_count,sizeof(long),1,fpi);
    swapulong(&pass_count);
    fread(&pass_count_preset,sizeof(long),1,fpi);
    swapulong(&pass_count_preset);
    fread(acq_time,sizeof(char),8,fpi);
    fread(acq_date,sizeof(char),8,fpi);
    fread(&mark_chan,sizeof(short),1,fpi);
    swapushort(&mark_chan);
    fread(&mcs_num,sizeof(char),1,fpi);
    fread(&cal_flag,sizeof(char),1,fpi);
    fread(cal_units,sizeof(char),4,fpi);
    fread(&cal_zero,sizeof(float),1,fpi);
    swapfloat(&cal_zero);
    fread(&cal_slope,sizeof(float),1,fpi);
    swapfloat(&cal_slope);
    fread(reserved,sizeof(char),10,fpi);
    fread(&id_byte,sizeof(char),1,fpi);
    fread(reserved,sizeof(char),1,fpi);
    fread(&detector_len,sizeof(char),1,fpi);
    fread(detector,sizeof(char),63,fpi);
    fread(&sample_len,sizeof(char),1,fpi);
    fread(sample,sizeof(char),63,fpi);
    fread(reserved,sizeof(char),16,fpi); /* skip view info & reserved */
    fread(&disc_sel,sizeof(char),1,fpi);
    fread(&disc_edge,sizeof(char),1,fpi);
    fread(&disc,sizeof(float),1,fpi);
    swapfloat(&disc);
    fread(&sca_uld,sizeof(float),1,fpi);
    swapfloat(&sca_uld);
    fread(&sca_lld,sizeof(float),1,fpi);
    swapfloat(&sca_lld);
    fread(&dwell,sizeof(float),1,fpi);
    swapfloat(&dwell);
    fread(&consistent,sizeof(char),1,fpi);
    fread(reserved,sizeof(char),21,fpi);
    fread(mcs_id,sizeof(char),8,fpi);
    mcs_id[8]=0;

    sprintf(ts1, "%hd", mcs_num+1);
    sprintf(ts2, "%hd", pass_length);
    sprintf(ts3, "%ld", pass_count);
    sprintf(ts4, "%ld", pass_count_preset);
    
    if (!SDDS_InitializeOutput(&SDDS_dataset, ascii?SDDS_ASCII:SDDS_BINARY, 1, "Turbo MCS data", "Turbo MCS data", output) ||
        SDDS_DefineParameter(&SDDS_dataset, "MCSNumber", NULL, NULL, "MCS number", NULL, SDDS_SHORT, 
                             ts1)<0 ||
        SDDS_DefineParameter(&SDDS_dataset, "MCSID", NULL, NULL, "MCS ID", NULL, SDDS_STRING, mcs_id)<0 ||
        SDDS_DefineParameter(&SDDS_dataset, "PassLength", NULL, NULL, "Pass length", NULL, SDDS_SHORT,
                             ts2)<0 ||
        SDDS_DefineParameter(&SDDS_dataset, "PassCount", NULL, NULL, "Pass count", NULL, SDDS_LONG,
                             ts3)<0 ||
        SDDS_DefineParameter(&SDDS_dataset, "PassCountPreset", NULL, NULL, "Pass count preset", NULL, SDDS_LONG,
                             ts4)<0)
        SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);

    if (dwell_flag == 0) {
        if (dwell_units==0)
            dwell *= 1e-6;
        else if (dwell_units==1) 
            dwell *= 1e-3;
        else if (dwell_units==3) 
            dwell *= 1e-9;
        } 
    else 
        dwell = -1;
    sprintf(ts1, "%15.8e", dwell);
    sprintf(ts2, "%8s %8s", acq_time,acq_date);
    if (SDDS_DefineParameter(&SDDS_dataset, "DwellTime", NULL, "s", "Dwell time", NULL, SDDS_DOUBLE, 
                             ts1)<0 ||
        SDDS_DefineParameter(&SDDS_dataset, "TriggerMode", NULL, NULL, "Trigger mode", NULL, SDDS_STRING,
                             trigger?"external":"internal")<0 ||
        SDDS_DefineParameter(&SDDS_dataset, "AcquisitionMode", NULL, NULL, "Acquisition mode", NULL, SDDS_STRING,
                             acq_mode?"sum":"replace")<0 ||
        SDDS_DefineParameter(&SDDS_dataset, "TimeStamp", NULL, NULL, "Time at which data collection started", NULL, SDDS_STRING,
                             ts2)<0)
        SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
        
    sprintf(ts1, "%15.8e", cal_slope);
    sprintf(ts2, "%15.8e", cal_zero);
    if (cal_flag && 
        (SDDS_DefineParameter(&SDDS_dataset, "CalibrationSlope", NULL, cal_units, "Spectrum calibration slope", NULL, SDDS_DOUBLE, ts1)<0 ||
         SDDS_DefineParameter(&SDDS_dataset, "CalibrationOffset", NULL, cal_units, "Spectrum calibration slope", NULL, SDDS_DOUBLE, ts2)<0))
        SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);

    if (detector_len) {
        detector[(unsigned)detector_len] = 0;
        if (SDDS_DefineParameter(&SDDS_dataset, "HardwareDescription", NULL, NULL, 
                                  NULL, NULL, SDDS_DOUBLE, detector)<0)
            SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
        }
    
    if (sample_len) {
        sample[(unsigned)sample_len] = 0;
        if (SDDS_DefineParameter(&SDDS_dataset, "DataDescription", NULL, NULL, 
                                 NULL, NULL, SDDS_STRING, sample)<0 ||
            SDDS_DefineParameter(&SDDS_dataset, "mplTitle", NULL, NULL, 
                                 NULL, NULL, SDDS_STRING, sample)<0)
            SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
        }
    
    if (disc_sel == 0) {
        sprintf(ts1, "%15.8e", sca_lld);
        sprintf(ts2, "%15.8e", sca_uld);
        if (SDDS_DefineParameter(&SDDS_dataset, "SCA-LLD", NULL, "V", "SCA Lower-Level Discriminator Setting",
                                  NULL, SDDS_DOUBLE, ts1)<0 ||
            SDDS_DefineParameter(&SDDS_dataset, "SCA-ULD", NULL, "V", "SCA Upper-Level Discriminator Setting",
                                 NULL, SDDS_DOUBLE, ts2)<0)
            SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
        } 
    else {
        sprintf(ts1, "%15.8e", disc);
        if (SDDS_DefineParameter(&SDDS_dataset, "DiscrimLevel", NULL, "V", "Discriminator Level",
				 NULL, SDDS_DOUBLE, ts1)<0 ||
            SDDS_DefineParameter(&SDDS_dataset, "DiscrimSlope", NULL, NULL, "Discriminator Slope",
                                 NULL, SDDS_LONG, disc_edge?"+1":"-1")<0)
            SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
        }

    if (consistent==0) {
        if (SDDS_DefineParameter(&SDDS_dataset, "Inconsistent", NULL, NULL, 
                                  "Flag indicating whether data and settings are inconsistent",
                                  NULL, SDDS_LONG, "1")<0)
            SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
        fprintf(stderr, "WARNING: Settings are not consistent with data\n");
        }
    
    if (SDDS_DefineColumn(&SDDS_dataset, "ChannelNumber", NULL, NULL, "Channel number", NULL, SDDS_LONG, 0)<0 ||
        SDDS_DefineColumn(&SDDS_dataset, "EventCount", NULL, NULL, "Number of events", NULL, SDDS_LONG, 0)<0 ||
        !SDDS_WriteLayout(&SDDS_dataset) || !SDDS_StartPage(&SDDS_dataset, (long)pass_length))
        SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
        
    /***************************************************************************/
    /*    Channel Data     */
    /* Output channel data from MCS file */
    /***************************************************************************/
    channel = tmalloc(sizeof(*channel)*pass_length);
    count   = tmalloc(sizeof(*count)*pass_length);
    ucount   = tmalloc(sizeof(*ucount)*pass_length);
    if (fread(ucount, sizeof(*ucount), pass_length, fpi)!=pass_length)
        SDDS_Bomb("unable to read channel data");
    for (i=0; i<(long)pass_length; i++) {
        swapulong(ucount+i);
        count[i] = (long)ucount[i];
        channel[i] = i;
        }
    if (!SDDS_SetColumn(&SDDS_dataset, SDDS_SET_BY_NAME, channel, (long)pass_length, "ChannelNumber") ||
        !SDDS_SetColumn(&SDDS_dataset, SDDS_SET_BY_NAME, count, (long)pass_length, "EventCount") ||
        !SDDS_WritePage(&SDDS_dataset) || !SDDS_Terminate(&SDDS_dataset))
        SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
    fclose(fpi);
    return(0);
}
Ejemplo n.º 8
0
int main(int argc, char **argv)
{
    SDDS_TABLE SDDS_table;
    SCANNED_ARG *scanned;
    long i, i_arg, index, points, lsb_first, bytes_per_number;
    char *input, *output, buffer[BUFSIZE];
    char *signal_name, *ptr, *parameter_name;
    char *mpl_title, *mpl_topline, *descrip_text, *descrip_contents;
    FILE *fpi;
    long code, binary;
    double xIncrement, xZero, yMultiplier, yZero;
    char *xUnits, *yUnits;
    double *time, *data;
    short columnMajorOrder=0;
    unsigned long majorOrderFlag;
    
    xUnits = yUnits = NULL;

    argc = scanargs(&scanned, argc, argv);
    if (argc<3)
        bomb(NULL, USAGE);

    input = output = signal_name = NULL;
    mpl_title = mpl_topline = descrip_text = descrip_contents = NULL;
    binary = 0;

    for (i_arg=1; i_arg<argc; i_arg++) {
        if (scanned[i_arg].arg_type==OPTION) {
            delete_chars(scanned[i_arg].list[0], "_");
            /* process options here */
            switch (match_string(scanned[i_arg].list[0], option, N_OPTIONS, 0)) {
            case SET_MAJOR_ORDER:
              majorOrderFlag=0;
              scanned[i_arg].n_items--;
              if (scanned[i_arg].n_items>0 &&
                  (!scanItemList(&majorOrderFlag, scanned[i_arg].list+1, &scanned[i_arg].n_items, 0,
                                 "row", -1, NULL, 0, SDDS_ROW_MAJOR_ORDER,
                                 "column", -1, NULL, 0, SDDS_COLUMN_MAJOR_ORDER,
                                 NULL)))
                SDDS_Bomb("invalid -majorOrder syntax/values");
              if (majorOrderFlag&SDDS_COLUMN_MAJOR_ORDER)
                columnMajorOrder=1;
              else if (majorOrderFlag&SDDS_ROW_MAJOR_ORDER)
                columnMajorOrder=0;
              break;
            case SET_SIGNAL_NAME:
              if (scanned[i_arg].n_items!=2)
                bomb("invalid -signal_name syntax", USAGE);
              signal_name = scanned[i_arg].list[1];
                break;
            case SET_DESCRIPTION:
              if (scanned[i_arg].n_items!=3)
                bomb("invalid -description syntax", USAGE);
              descrip_text = scanned[i_arg].list[1];
              descrip_contents = scanned[i_arg].list[2];
              break;
            case SET_MPL_LABELS:
              if (scanned[i_arg].n_items!=3)
                bomb("invalid -mpl_labels syntax", USAGE);
              mpl_title = scanned[i_arg].list[1];
              mpl_topline = scanned[i_arg].list[2];
              break;
            default:
              bomb("invalid option seen", USAGE);
              break;
            }
        }
        else {
          if (!input)
            input = scanned[i_arg].list[0];
          else if (!output)
            output = scanned[i_arg].list[0];
          else
            bomb("too many filenames", USAGE);
            }
    }
    if (!input)
      SDDS_Bomb("input file not seen");
    if (!output)
      SDDS_Bomb("output file not seen");
    if (!signal_name)
      signal_name = "V";
    
    fpi = fopen_e(input, "r", 0);
    if (fread(buffer, 1, strlen(TEK_PreambleString), fpi)!=strlen(TEK_PreambleString) ||
        strncmp(TEK_PreambleString, buffer, strlen(TEK_PreambleString))!=0)
        SDDS_Bomb("file does not appear to be in Tektronix format");

    parameter_name = buffer;
    while ((code=GetNextItem(buffer, BUFSIZE, fpi))<3) {
        if (!(ptr=strchr(buffer, ':')))
            SDDS_Bomb("error parsing input file--missing colon on parameter tag");
        *ptr++ = 0;
        if (strcmp(TEK_DataMarker, parameter_name)==0)
            break;
        index = 0;
        while (TEK_parameter[index].TEK_name) {
            if (strcmp(TEK_parameter[index].TEK_name, parameter_name)==0)
                break;
            index++;
            }
        if (!TEK_parameter[index].TEK_name) {
            fprintf(stderr, "warning: parameter %s is not recognized\n",
                    parameter_name);
            continue;
            }
        if (TEK_parameter[index].value_string) {
            fprintf(stderr, "error: duplicate entries for parameter %s\n",
                    parameter_name);
            exit(1);
            }
        SDDS_RemovePadding(ptr);
        SDDS_CopyString(&TEK_parameter[index].value_string, ptr);
        if (code==2 || code==3)
            break;
        }
    if (code!=2)
        SDDS_Bomb("unexpected end of file");

    if (fread(buffer, 1, strlen(TEK_DataMarker), fpi)!=strlen(TEK_DataMarker) ||
        strncmp(TEK_DataMarker, buffer, strlen(TEK_DataMarker))!=0)
        SDDS_Bomb("CURVE item missing or not in right place");

    if (!SDDS_InitializeOutput(&SDDS_table, SDDS_BINARY, 0, descrip_text, descrip_contents,
                               output))
        SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
    SDDS_table.layout.data_mode.column_major = columnMajorOrder;
    
    index = 0;
    while (TEK_parameter[index].TEK_name) {
        if (!TEK_parameter[index].value_string) {
            index++;
            continue;
            }
        if (strcmp(TEK_parameter[index].TEK_name, TEK_XIncrementName)==0) {
            if (sscanf(TEK_parameter[index].value_string, "%lf", &xIncrement)!=1)
                SDDS_Bomb("unable to scan value for x increment");
            }
        else if (strcmp(TEK_parameter[index].TEK_name, TEK_XZeroName)==0) {
            if (sscanf(TEK_parameter[index].value_string, "%lf", &xZero)!=1)
                SDDS_Bomb("unable to scan value for x zero");
            }
        else if (strcmp(TEK_parameter[index].TEK_name, TEK_YZeroName)==0) {
            if (sscanf(TEK_parameter[index].value_string, "%lf", &yZero)!=1)
                SDDS_Bomb("unable to scan value for y zero");
            }
        else if (strcmp(TEK_parameter[index].TEK_name, TEK_YMultiplierName)==0) {
            if (sscanf(TEK_parameter[index].value_string, "%lf", &yMultiplier)!=1)
                SDDS_Bomb("unable to scan value for y multiplier");
            }
        else if (strcmp(TEK_parameter[index].TEK_name, TEK_XUnitsName)==0) {
            xUnits = TEK_parameter[index].value_string;
            str_tolower(xUnits);
            }
        else if (strcmp(TEK_parameter[index].TEK_name, TEK_YUnitsName)==0) {
            yUnits = TEK_parameter[index].value_string;
            str_tolower(yUnits);
            }
        else if (strcmp(TEK_parameter[index].TEK_name, TEK_PointsName)==0) {
            if (sscanf(TEK_parameter[index].value_string, "%ld", &points)!=1)
                SDDS_Bomb("unable to scan value for number of points");
            }
        else if (strcmp(TEK_parameter[index].TEK_name, TEK_EncodingName)==0) {
            if (strcmp(TEK_parameter[index].value_string, "ASCII")==0) 
                binary = 0;
            else if (strcmp(TEK_parameter[index].value_string, "BINARY")==0)
                binary = 1;
            else
                SDDS_Bomb("data encoding is neither ASCII nor BINARY");
            }
        else if (strcmp(TEK_parameter[index].TEK_name, TEK_BytesPerNumberName)==0) {
            if (sscanf(TEK_parameter[index].value_string, "%ld", &bytes_per_number)!=1)
                SDDS_Bomb("unable to scan value bytes per number");
            }
        else if (strcmp(TEK_parameter[index].TEK_name, TEK_ByteOrderName)==0) {
            lsb_first = 1;
            if (strcmp(TEK_parameter[index].value_string, "LSB")!=0)
                lsb_first = 0;
            }
        if (SDDS_DefineParameter(&SDDS_table, TEK_parameter[index].SDDS_name,
                                  NULL, NULL, TEK_parameter[index].TEK_name,
                                  NULL, TEK_parameter[index].type, 
                                  TEK_parameter[index].value_string)<0)
            SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
        index++;
        }

    if (mpl_title &&
        (SDDS_DefineParameter(&SDDS_table, "mplTitle", NULL, NULL, NULL, NULL, SDDS_STRING, mpl_title)<0 ||
         SDDS_DefineParameter(&SDDS_table, "mplTopline", NULL, NULL, NULL, NULL, SDDS_STRING, mpl_topline)<0))
        SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);

    if (SDDS_DefineColumn(&SDDS_table, "t", NULL, xUnits, NULL, NULL, SDDS_DOUBLE, 0)<0 ||
        SDDS_DefineColumn(&SDDS_table, signal_name, NULL, yUnits, NULL, NULL, SDDS_DOUBLE, 0)<0 ||
        !SDDS_WriteLayout(&SDDS_table) || !SDDS_StartTable(&SDDS_table, points))
        SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);

    data = tmalloc(sizeof(*data)*points);
    time = tmalloc(sizeof(*time)*points);
    if (!binary) {
        for (i=0; i<points; i++) {

            if (!(code=GetNextItem(buffer, BUFSIZE, fpi)))
                SDDS_Bomb("insufficient data in input file");
            if (code==4) {
                points = i;
                break;
                }
            time[i] = xZero + i*xIncrement;
            if (sscanf(buffer, "%lf", data+i)!=1)
                SDDS_Bomb("invalid data in input file");
            data[i] = yZero + data[i]*yMultiplier;
            }
        }
    else {
        short sdata;
        fread(buffer, sizeof(char), 4, fpi);
        for (i=0; i<points; i++) {
            if (fread(&sdata, sizeof(sdata), 1, fpi)!=1) {
                fprintf(stderr, "file ends unexpectedly\n");
                points = i;
                break;
                }
            time[i] = xZero + i*xIncrement;
            data[i] = sdata;
            data[i] = yZero + data[i]*yMultiplier;
            }
        }

    if (!SDDS_SetColumn(&SDDS_table, SDDS_SET_BY_NAME, time, points, "t") ||
        !SDDS_SetColumn(&SDDS_table, SDDS_SET_BY_NAME, data, points, signal_name) ||
        !SDDS_WriteTable(&SDDS_table) || !SDDS_Terminate(&SDDS_table))
        SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
    return(0);
}