Exemplo n.º 1
0
char *exp_notation(double x, long n1, long n2)
{
    char t[100], s[100], format[100];
    char *ptr;

    sprintf(format, "%%%ld.%ldle", n1, n2);
    sprintf(s, format, x);
    if ((ptr = strchr(s, 'e'))) {
        *ptr++ = 0;
        if (*ptr=='+') {
            ptr++;
            while (*ptr=='0')
                ptr++;
            }
        else {
            while (*(ptr+1)=='0')
                strcpy_ss(ptr+1, ptr+2);
            }
        sprintf(t, "%sx10$a%s$b", s, ptr);
        cp_str(&ptr, t);
        return(ptr);
        }
    else {
        cp_str(&ptr, s);
        return(ptr);
        }
    }
Exemplo n.º 2
0
long rpn_create_mem(char *name, short is_string)
{
  long i_mem;
  int32_t duplicate;
  MEMORY *newMem;
  
  if (is_func(name)!=-1 || find_udf(name)!=-1) {
    fprintf(stderr, "error: attempt to create rpn memory with reserved name \"%s\"\n", name);
    return -1;
  }
  
  if (Memory==NULL || n_memories>=max_n_memories) {
    Memory = trealloc(Memory, sizeof(*Memory)*(max_n_memories+=10));
    memoryData = trealloc(memoryData, sizeof(*memoryData)*max_n_memories);
    str_memoryData = trealloc(str_memoryData, sizeof(*str_memoryData)*max_n_memories);
  }
  
  newMem = tmalloc(sizeof(*newMem));
  newMem->name = name; /* temporary copy */
  
  i_mem = binaryInsert((void**)Memory, n_memories, (void*)newMem, compare_mem, &duplicate);
  if (duplicate) {
    free(newMem);
    return Memory[i_mem]->index;
  }
  
  cp_str(&newMem->name, name);
  newMem->index = n_memories;
  newMem->is_string = is_string;
  memoryData[n_memories] = 0;
  str_memoryData[n_memories] = NULL;
  n_memories++;
  memory_added = 1;
  return Memory[i_mem]->index;
}
Exemplo n.º 3
0
double rpn_internal(char *expression)
{
  double value;
  long cycle_counter_stop0;
  char *expressionCopy;

  /* this is necessary to prevent UDF processing problems
   */
  cycle_counter_stop0 = cycle_counter_stop;
  cycle_counter_stop = cycle_counter;

  cp_str(&expressionCopy, expression);
#ifdef DEBUG
  fprintf(stderr, "rpn_internal: executing %s\n", expression);
#endif

  push_code(expressionCopy, STATIC);
  execute_code();
  free(expressionCopy);

#ifdef DEBUG
  fprintf(stderr, "done\n");
#endif

  value = pop_num();

#ifdef DEBUG
  fprintf(stderr, "value = %e\n", value);
#endif

  cycle_counter_stop = cycle_counter_stop0;
  return value;
}
Exemplo n.º 4
0
void cat_to_str(char *target, char *source){
   while(*target)
   {
      target++;
   }
   cp_str(target, source);
}
Exemplo n.º 5
0
void load_config(god_t* god){
	check_dirs();

	char *home_dir = getenv("HOME");
	char *conf_file = "/.local/share/crunchball/crunchball.cfg";
	char tmp_path[500] = {0};
	
	cp_str(tmp_path, home_dir);	
	cat_to_str(tmp_path, conf_file);

	long int video_mode;
	long int audio_level;
	long int fullscreen;
	long int high_score;

	cfg_opt_t opts[] = {
		CFG_SIMPLE_INT("video_mode", &video_mode),
		CFG_SIMPLE_INT("audio_level", &audio_level),
		CFG_SIMPLE_INT("fullscreen", &fullscreen),
		CFG_SIMPLE_INT("high_score", &high_score),
		CFG_END()
	};
	cfg_t *cfg;

	cfg = cfg_init(opts, 0);
	int rc = cfg_parse(cfg, tmp_path);

	if ( rc != 0 ){
		video_mode = 2;
		audio_level = 5;
		fullscreen = 0;
		high_score = 0;
	}
	
	if (video_mode == 0)
		video_mode = 2;

	god->scalar.scale = video_mode;
	god->state.settings_volume = audio_level;
	god->state.high_score = high_score;
	god->scalar.fs = fullscreen;
	
	FILE *fp = fopen(tmp_path, "w");
	cfg_print(cfg, fp);

	fclose(fp);

	cfg_free(cfg);

}
Exemplo n.º 6
0
char *process_column_definition(char **argv, long argc)
{
    char buffer[SDDS_MAXLINE], *ptr;
    long i;

    if (argc<1)
        return(NULL);
    sprintf(buffer, "&column name=%s, ", argv[0]);
    for (i=1; i<argc; i++) {
        if (!strchr(argv[i], '='))
            return(NULL);
        strcat(buffer, argv[i]);
        strcat(buffer, ", ");
        }
    if (!strstr(buffer, "type="))
        strcat(buffer, "type=character ");
    strcat(buffer, "&end");
    cp_str(&ptr, buffer);
    return(ptr);
    }
Exemplo n.º 7
0
void get_name_unit_descrip_format(char **name, char **unit, char **descrip, char **format, char *buf)
{
    char *ptr, *ptrn, *ptru, *ptrd, *ptrf;
    char *blank_string;

    cp_str(&blank_string, " ");

    ptr = ptrn = buf;
    ptru = ptrd = ptrf = NULL;
    while ((ptr=strchr(ptr, '\\'))) {
        if (ptr[1]=='\\')
            ptr += 2;
        else {
            if (!ptru) {
                *ptr = 0;
                ptru = ++ptr;
                }
            else if (!ptrd) {
                *ptr = 0;
                ptrd = ++ptr;
                }
            else {
                *ptr = 0;
                ptrf = ++ptr;
                break;
                }
            }
        }
    cp_str(name, ptrn);
    trim_spaces(*name);
    if (ptru) {
        cp_str(unit, ptru);
        trim_spaces(*unit);
        }
    else 
        *unit = blank_string;
    if (ptrd && !is_blank(ptrd)) {
        cp_str(descrip, ptrd);
        trim_spaces(*descrip);
        }
    else 
        cp_str(descrip, *name);
    if (ptrf) {
        cp_str(format, ptrf);
        trim_spaces(*format);
        }
    else
        *format = NULL;
    }
Exemplo n.º 8
0
int main(int argc, char **argv)
{
    SDDS_TABLE SDDS_table;
    SCANNED_ARG *scanned;
    long i, i_arg, points;
    char *input, *output, *name, *indep_var, *var_list_format;
    char *mpl_title, *mpl_topline, *descrip_text, *descrip_contents;
    FILE *fpi;
    char buffer[BUFSIZE], buffer0[BUFSIZE], buffer1[BUFSIZE];
    char *ptr, *ptr1, *ptr2;
    char **data_name, *package_name, *data_format;
    long data_names, data_sets_seen, data_sets_expected, realIndex, imagIndex;
    double **real_data, **imag_data, *var_list;

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

    input = output = package_name = data_format = indep_var = var_list_format = ptr = NULL;
    mpl_title = mpl_topline = descrip_text = descrip_contents = NULL;
    data_names = realIndex = imagIndex = 0;
    data_name = NULL;
    real_data = imag_data = NULL;
    var_list = NULL;
    data_sets_expected = data_sets_seen = 0;
    points = 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_DESCRIPTION:
                if (scanned[i_arg].n_items!=3)
                    SDDS_Bomb("invalid -description syntax");
                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)
                    SDDS_Bomb("invalid -mpllabels syntax");
                mpl_title = scanned[i_arg].list[1];
                mpl_topline = scanned[i_arg].list[2];
                break;
              default:
                SDDS_Bomb("invalid option seen");
                break;
                }
            }
        else {
            if (!input)
                input = scanned[i_arg].list[0];
            else if (!output)
                output = scanned[i_arg].list[0];
            else
                SDDS_Bomb("too many filenames");
            }
        }
    if (!input)
        SDDS_Bomb("input file not seen");
    if (!output)
        SDDS_Bomb("output file not seen");

    fpi = fopen_e(input, "r", 0);
    if (!fgets(buffer, BUFSIZE, fpi) || strncmp(buffer, CITIFILE_TAG, strlen(CITIFILE_TAG))!=0 ||
        !(ptr=strchr(buffer, ' ')))
        SDDS_Bomb("valid CITIFILE version line not found");
    *ptr++ = 0;
    ptr[strlen(ptr)-1] = 0;
    if (strncmp(ptr, CITIFILE_VERSION, strlen(CITIFILE_VERSION))!=0)
        fprintf(stderr, "warning: the CITIFILE version is %s--this program is only designed for version %s\n",
                ptr, CITIFILE_VERSION);
    
    
    if (!SDDS_InitializeOutput(&SDDS_table, SDDS_BINARY, 0, descrip_text, descrip_contents,
                               output))
        SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);

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

    while (fgets(buffer, BUFSIZE, fpi)) {
#if DEBUG
        fputs(buffer, stderr);
#endif
        buffer[strlen(buffer)-1] = 0;
        strcpy(buffer0, buffer);
        ptr1 = NULL;
        if ((ptr1=strchr(buffer, ' '))) 
            *ptr1++ = 0;
        switch (match_string(buffer, citi_keyword, N_CITI_KEYWORDS, EXACT_MATCH)) {
          case CITI_NA_KEYWORD:
            name = buffer+1;
            if (!*ptr1 || !(ptr2=strchr(ptr1, ' '))) {
                fprintf(stderr, "The following line contains an apparently invalid #NA keyword:\n%s\n",
                        buffer0);
                exit(1);
                }
            *(ptr1-1) = '_';
            *ptr2++ = 0;
            if (SDDS_DefineParameter(&SDDS_table, name, NULL, NULL, NULL, NULL, SDDS_STRING, ptr2)<0) {
                SDDS_SetError(buffer0);
                SDDS_SetError("Problem creating parameter for #NA keyword in the following line:");
                SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
                }
            break;
          case CITI_NAME_KEYWORD:
            if (!ptr1 || SDDS_StringIsBlank(ptr1)) {
                fprintf(stderr, "The following line contains erroneous input:\n%s\n", buffer0);
                exit(1);
                }
#if DEBUG
            fprintf(stderr, "NAME: %s\n", ptr1);
#endif
            cp_str(&package_name, ptr1);
            if (SDDS_DefineParameter(&SDDS_table, "CITIPackageName", NULL, NULL, NULL, NULL, SDDS_STRING,
                                      package_name)<0) {
                SDDS_SetError(buffer0);
                SDDS_SetError("Problem creating parameter for NAME keyword in the following line:");
                SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
                }
            break;
          case CITI_VAR_KEYWORD:
            if (!ptr1 || SDDS_StringIsBlank(ptr1)) {
                fprintf(stderr, "The following line contains erroneous input:\n%s\n", buffer0);
                exit(1);
                }
#if DEBUG
            fprintf(stderr, "VAR: %s\n", ptr1);
#endif
            if (!(indep_var=get_token(ptr1)) || !(var_list_format=get_token(ptr1)) || !get_long(&points, ptr1) ||
                points<=0) {
                fprintf(stderr, "The following line contains erroneous input:\n%s\n", buffer0);
                exit(1);
                }
            if (SDDS_DefineColumn(&SDDS_table, indep_var, NULL, NULL, NULL, NULL, SDDS_DOUBLE, 0)<0) {
                SDDS_SetError(buffer0);
                SDDS_SetError("Problem creating column for data element in the following line:");
                SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
                }
            break;
          case CITI_CONSTANT_KEYWORD:
            if (!ptr1 || !(ptr2=strchr(ptr1, ' '))) {
                fprintf(stderr, "The following line contains erroneous input:\n%s\n", buffer0);
                exit(1);
                }
#if DEBUG
            fprintf(stderr, "CONSTANT: %s\n", ptr1);
#endif
            *ptr2++ = 0;
            if (SDDS_DefineParameter(&SDDS_table, ptr1, NULL, NULL, NULL, NULL, SDDS_STRING, ptr2)<0) {
                SDDS_SetError(buffer0);
                SDDS_SetError("Problem creating parameter for CONSTANT keyword in the following line:");
                SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
                }
            break;
          case CITI_COMMENT_KEYWORD:
            if (!ptr1 || SDDS_StringIsBlank(ptr1)) {
                fprintf(stderr, "The following line contains erroneous input:\n%s\n", buffer0);
                exit(1);
                }
#if DEBUG
            fprintf(stderr, "COMMENT: %s\n", ptr1);
#endif
            break;
          case CITI_DATA_KEYWORD:
            if (!ptr1 || !(ptr2 = strchr(ptr1, ' '))) {
                fprintf(stderr, "The following line contains erroneous input:\n%s\n", buffer0);
                exit(1);
                }
#if DEBUG
            fprintf(stderr, "DATA: %s\n", ptr1);
#endif
            *ptr2++ = 0;
            cp_str(&data_format, ptr2);
            data_name = trealloc(data_name, sizeof(*data_name)*(data_names+1));
            cp_str(data_name+data_names, ptr1);
            alter_data_name(data_name[data_names]);
            real_data = trealloc(real_data, sizeof(*real_data)*(data_names+1));
            imag_data = trealloc(imag_data, sizeof(*imag_data)*(data_names+1));
	    sprintf(buffer, "%sReal", data_name[data_names]);
	    sprintf(buffer1, "%sImag", data_name[data_names]);
            if ((realIndex=SDDS_DefineColumn(&SDDS_table, buffer, 
                                  NULL, NULL, NULL, NULL, SDDS_DOUBLE, 0))<0 ||
                (imagIndex=SDDS_DefineColumn(&SDDS_table, buffer1, 
                                  NULL, NULL, NULL, NULL, SDDS_DOUBLE, 0))<0 ) {
                SDDS_SetError(buffer0);
                SDDS_SetError("Problem creating column for data element in the following line:");
                SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
                }
            data_names++;
            break;
          case CITI_VAR_LIST_KEYWORD:
            if (ptr1 && !SDDS_StringIsBlank(ptr1))
                fprintf(stderr, "The following line contains erroneous input:\n%s\n", buffer0);
#if DEBUG
            fprintf(stderr, "VAR_LIST_BEGIN seen\n");
#endif
            if (points==0)
                SDDS_Bomb("VAR_LIST_BEGIN statement seen without prior VAR statement");
            var_list = tmalloc(sizeof(*var_list)*points);
            if (!read_CITI_var_list(fpi, var_list, points))
                SDDS_Bomb("unable to read VAR_LIST");
            break;
          case CITI_BEGIN_KEYWORD:
            if (ptr1 && !SDDS_StringIsBlank(ptr1))
                fprintf(stderr, "The following line contains erroneous input:\n%s\n", buffer0);
#if DEBUG
            fprintf(stderr, "BEGIN seen\n");
#endif
            if (points==0)
                SDDS_Bomb("BEGIN statement seen without prior VAR statement");
            real_data[data_sets_seen] = tmalloc(sizeof(**real_data)*points);
            imag_data[data_sets_seen] = tmalloc(sizeof(**imag_data)*points);
            if (!read_CITI_data(fpi, real_data[data_sets_seen], imag_data[data_sets_seen], points))
                SDDS_Bomb("problem reading data section");
            data_sets_seen++;
            break;
          case CITI_SEG_LIST_BEGIN:
            if (ptr1 && !SDDS_StringIsBlank(ptr1))
                fprintf(stderr, "The following line contains erroneous input:\n%s\n", buffer0);
#if DEBUG
            fprintf(stderr, "SEG_LIST_BEGIN seen\n");
#endif
            if (points==0)
                SDDS_Bomb("SEG_LIST_BEGIN statement seen without prior SEG statement");
            var_list = tmalloc(sizeof(*var_list)*points);
            if (!read_CITI_seg_list(fpi, var_list, points))
                SDDS_Bomb("unable to read SEG_LIST");
            break;
          default:
            fprintf(stderr, "unidentifiable line in file--not CITI format:\n\"%s\"\n",
                    buffer0);
            exit(1);
            break;
            }
        }
    if (!points)
        SDDS_Bomb("no data in file");
    if (data_sets_seen!=(data_sets_expected=data_names))
        SDDS_Bomb("fewer data sets than expected were actually present");
    if (!var_list) {
        fprintf(stderr, "warning: no independent variable data---supplying index\n");
        var_list = tmalloc(sizeof(*var_list)*points);
        for (i=0; i<points; i++)
            var_list[i] = i;
        }
    if (!SDDS_WriteLayout(&SDDS_table) || !SDDS_StartTable(&SDDS_table, points))
        SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
    if (!SDDS_SetColumn(&SDDS_table, SDDS_SET_BY_NAME, (void*)var_list, points, indep_var))
        SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
    for (i=0; i<data_sets_expected; i++) {
         if (!SDDS_SetColumn(&SDDS_table, SDDS_SET_BY_INDEX, (void*)real_data[i], points, 
                             realIndex) ||
             !SDDS_SetColumn(&SDDS_table, SDDS_SET_BY_INDEX, (void*)imag_data[i], points, 
                             imagIndex)) {
             fprintf(stderr, "problem setting data for column(s) %s\n", data_name[i]);
             SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
             }
         }
    if (!SDDS_WriteTable(&SDDS_table) || !SDDS_Terminate(&SDDS_table))
        SDDS_PrintErrors(stderr, SDDS_EXIT_PrintErrors|SDDS_VERBOSE_PrintErrors);
    return(0);
}
Exemplo n.º 9
0
long setupOutputFile(SDDS_DATASET *SDDSout, SDDS_DATASET *SDDSin, char *output,
                     char ***yOutputName, char ***yOutputErrorName, char ***yOutputUnits,
                     char *xName, char *xErrorName,
                     char **yName, char **yErrorName, long yNames,
                     char **mainTemplate0, char **errorTemplate0, int32_t interval,
                     long order)
{
    long i;
    char *xSymbol, *ySymbol;
    char *mainTemplate[3] = {"%yNameDeriv", "Derivative w.r.t. %xSymbol of %ySymbol", "d[%ySymbol]/d[%xSymbol]"};
    char *errorTemplate[3] = {"%yNameDerivSigma", "Sigma of derivative w.r.t. %xSymbol of %ySymbol", 
                                  "Sigma[d[%ySymbol]/d[%xSymbol]]"};
    char buffer[1024];

    for (i=0; i<3; i++) {
      if (!mainTemplate0[i]) {
        if (order!=1) {
          switch (i) {
          case 0:
            /* name */
            sprintf(buffer, "%%yNameDeriv%ld", order);
            break;
          case 1:
            /* description */
            sprintf(buffer, "Derivative %ld w.r.t. %%xSymbol of %%ySymbol", order);
            break;
          case 2:
            /* symbol */
            sprintf(buffer, "d$a%ld$n[%%ySymbol]/d[%%xSymbol]$a%ld$n", order, order);
            break;
          }
          cp_str(&mainTemplate[i], buffer);
        }
      } else
        mainTemplate[i] = mainTemplate0[i];
      if (errorTemplate0[i])
        errorTemplate[i] = errorTemplate0[i];
    }
    
    *yOutputName = tmalloc(sizeof(*yOutputName)*yNames);
    *yOutputErrorName = tmalloc(sizeof(*yOutputErrorName)*yNames);
    *yOutputUnits = tmalloc(sizeof(*yOutputUnits)*yNames);
    if (!SDDS_InitializeOutput(SDDSout, SDDS_BINARY, 0, NULL, "sddsderiv output", output) ||
        SDDS_DefineParameter1(SDDSout, "derivInterval", NULL, NULL, NULL, NULL, SDDS_LONG, &interval)<0)
        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    if (!SDDS_TransferColumnDefinition(SDDSout, SDDSin, xName, NULL) ||
        (xErrorName && !SDDS_TransferColumnDefinition(SDDSout, SDDSin, xErrorName, NULL)))
        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    if (SDDS_GetColumnInformation(SDDSout, "symbol", &xSymbol, SDDS_GET_BY_NAME, xName)!=SDDS_STRING) {
        fprintf(stderr, "error: problem getting symbol for column %s\n", xName);
        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
        }
    if (!xSymbol)
        SDDS_CopyString(&xSymbol, xName);
    for (i=0; i<yNames; i++) {
        if (!SDDS_TransferColumnDefinition(SDDSout, SDDSin, yName[i], NULL)) {
            fprintf(stderr, "error: problem transferring definition for column %s\n", yName[i]);
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
            }
        if (SDDS_GetColumnInformation(SDDSout, "symbol", &ySymbol, SDDS_GET_BY_NAME, yName[i])!=SDDS_STRING) {
            fprintf(stderr, "error: problem getting symbol for column %s\n", yName[i]);
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
            }
        if (!ySymbol || SDDS_StringIsBlank(ySymbol))
            SDDS_CopyString(&ySymbol, yName[i]);
        (*yOutputUnits)[i] = divideColumnUnits(SDDSout, yName[i], xName);
        (*yOutputName)[i] = changeInformation(SDDSout, yName[i], yName[i], ySymbol, xName, xSymbol, mainTemplate,
                                              (*yOutputUnits)[i]);
        if (yErrorName || xErrorName) {
            if (yErrorName && yErrorName[i]) {
                if (!SDDS_TransferColumnDefinition(SDDSout, SDDSin, yErrorName[i], NULL)) { 
                    fprintf(stderr, "error: problem transferring definition for column %s\n", yErrorName[i]);
                    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
                    }
                (*yOutputErrorName)[i] = changeInformation(SDDSout, yErrorName[i], yName[i], ySymbol, xName, xSymbol,
                                                           errorTemplate, (*yOutputUnits)[i]);
                }
            else {
                if (!SDDS_TransferColumnDefinition(SDDSout, SDDSin, yName[i], NULL)) { 
                    fprintf(stderr, "error: problem transferring error definition for column %s\n", yName[i]);
                    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
                    }
                (*yOutputErrorName)[i] = changeInformation(SDDSout, yName[i], yName[i], ySymbol, xName, xSymbol,
                                                           errorTemplate, (*yOutputUnits)[i]);
                }
            }
        else
            (*yOutputErrorName)[i] = NULL;
        }
    if (!SDDS_TransferAllParameterDefinitions(SDDSout, SDDSin, SDDS_TRANSFER_KEEPOLD) ||
        !SDDS_WriteLayout(SDDSout))
      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    return(1);
  }
Exemplo n.º 10
0
void add_element_links(ELEMENT_LINKS *links, NAMELIST_TEXT *nltext, LINE_LIST *beamline)
{
    long n_links, src_position_code=0, n_targets, n_sources, mode_code=0;
    long targets, iTarget, j;
    char **targetList;
    ELEMENT_LIST *t_context, *s_context, **eptr, *eptr1;
    double dz_min, dz;
#if DEBUG
    long i;
#endif

    log_entry("add_element_links");

    /* set namelist variables to defaults */
    target = item = source = equation = exclude = NULL;
    /* must initialize these hear rather than in the .nl file
     * to avoid problems with str_tolower() and other operations
     */
    cp_str(&source_position, "before");
    cp_str(&mode, "dynamic");

    /* process namelist text */
    if (processNamelist(&link_elements, nltext)==NAMELIST_ERROR)
      bombElegant(NULL, NULL);
    if (target)          str_toupper(target);
    if (exclude)         str_toupper(exclude);
    if (item)            str_toupper(item);
    if (source)          str_toupper(source);
    if (source_position) 
      str_tolower(source_position);
    else
      cp_str(&source_position, "nearest");
    if (mode) 
      str_tolower(mode);
    else
      cp_str(&mode, "dynamic");
    if (echoNamelists) print_namelist(stdout, &link_elements);

    /* check for valid input */
    if (!target)
        bombElegant("link target not named", NULL);
    if (!item)
        bombElegant("link item not named", NULL);
    if (!source)
        bombElegant("link source not named", NULL);
    if (!equation)
        bombElegant("link equation not given", NULL);
    if (!source_position || (src_position_code=match_string(source_position, src_position_name, N_SRC_POSITIONS, 0))<0)
        bombElegant("source_position not given/unknown", NULL);
    if (!mode || (mode_code=match_string(mode, link_mode, N_LINK_MODES, 0))<0)
        bombElegant("link mode not known", NULL);
    if (minimum>maximum)
      bombElegant("minimum>maximum", NULL);
    
    t_context = s_context = NULL;

    if (has_wildcards(target) && strchr(target, '-'))
      target = expand_ranges(target);
    if (exclude && strlen(exclude) && has_wildcards(exclude) && strchr(exclude, '-'))
      exclude = expand_ranges(exclude);
    
    if (!(t_context=wfind_element(target, &t_context, &(beamline->elem)))) {
      fprintf(stdout, "error: cannot make link with target element %s--not in beamline\n", target);
      fflush(stdout);
      exitElegant(1);
    }
    if (!(s_context=find_element(source, &s_context, &(beamline->elem)))) {
      fprintf(stdout, "error: cannot make link with source element %s--not in beamline\n", source);
      fflush(stdout);
      exitElegant(1);
    }

    targets = 0;
    targetList = NULL;
    /* make a list of all the unique element names that match this (possibly wildcard) target */
    do {
      int32_t duplic;
      if (!exclude || !strlen(exclude) || !wild_match(t_context->name, exclude)) {
        targetList = SDDS_Realloc(targetList, sizeof(*targetList)*(targets+1));
        binaryInsert((void**)targetList, targets, t_context->name, strcmp, &duplic);
        if (!duplic)
          targets++;
      }
    } while ((t_context=wfind_element(target, &t_context, &(beamline->elem))));
    if (!targets)
      bombElegant("cannot make link--no targets found\n", NULL);
      
    /* note that targets==1 if all the targets have the same name ! */
    for (iTarget=0; iTarget<targets; iTarget++) {
      n_links = links->n_links;
      target = targetList[iTarget];
      t_context = NULL;
      t_context = find_element(target, &t_context, &(beamline->elem));

      /* expand the arrays */
      links->target_name     = trealloc(links->target_name, sizeof(*links->target_name)*(n_links+1));
      links->target_elem     = trealloc(links->target_elem, sizeof(*links->target_elem)*(n_links+1));
      links->item            = trealloc(links->item, sizeof(*links->item)*(n_links+1));
      links->target_param    = trealloc(links->target_param, sizeof(*links->target_param)*(n_links+1));
      links->source_name     = trealloc(links->source_name, sizeof(*links->source_name)*(n_links+1));
      links->source_position = trealloc(links->source_position, sizeof(*links->source_position)*(n_links+1));
      links->flags           = trealloc(links->flags, sizeof(*links->flags)*(n_links+1));
      links->source_elem     = trealloc(links->source_elem, sizeof(*links->source_elem)*(n_links+1));
      links->equation        = trealloc(links->equation, sizeof(*links->equation)*(n_links+1));
      links->n_targets       = trealloc(links->n_targets, sizeof(*links->n_targets)*(n_links+1));
      links->initial_value   = trealloc(links->initial_value, sizeof(*links->initial_value)*(n_links+1));
      links->baseline_value  = trealloc(links->baseline_value, sizeof(*links->baseline_value)*(n_links+1));
      links->minimum   = trealloc(links->minimum, sizeof(*links->minimum)*(n_links+1));
      links->maximum   = trealloc(links->maximum, sizeof(*links->maximum)*(n_links+1));

      /* copy the basic data */
      cp_str(links->target_name+n_links, target);
      cp_str(links->item+n_links, item);
      cp_str(links->source_name+n_links, source);
      cp_str(links->equation+n_links, equation);
      links->source_position[n_links] = src_position_code;
      links->flags[n_links] = link_mode_flag[mode_code];
      links->minimum[n_links] = minimum;
      links->maximum[n_links] = maximum;
      
      /* make the list of pointers to targets */
      eptr = tmalloc(sizeof(*eptr));
      eptr[0] = t_context;
      if ((links->target_param[n_links] = confirm_parameter(item, t_context->type))<0) {
        fprintf(stdout, "error: element %s does not have a parameter %s\n", target, item);
        fflush(stdout);
        exitElegant(1);
      }
      n_targets = 1;
      while ((t_context=find_element(target, &t_context, &(beamline->elem)))) {
        eptr = trealloc(eptr, sizeof(*eptr)*(n_targets+1));
        eptr[n_targets] = t_context;
        n_targets++;
      }
      links->baseline_value[n_links] = tmalloc(sizeof(*links->baseline_value[n_links])*n_targets);
      links->n_targets[n_links] = n_targets;
      links->target_elem[n_links] = eptr;
      t_context = links->target_elem[n_links][0];
      switch (entity_description[eptr[0]->type].parameter[links->target_param[n_links]].type) {
      case IS_DOUBLE:
        links->initial_value[n_links] = 
          *((double*)(eptr[0]->p_elem+entity_description[eptr[0]->type].parameter[links->target_param[n_links]].offset));
        break;
      case IS_LONG:
        links->initial_value[n_links] = 
          *((long*)(eptr[0]->p_elem+entity_description[eptr[0]->type].parameter[links->target_param[n_links]].offset));
        break;
      default:
        bombElegant("invalid type of item for target of link", NULL);
        break;
      }
      for (j=0; j<n_targets; j++)
        links->baseline_value[n_links][j] = links->initial_value[n_links];

      /* make the list of pointers to sources */
      if (iTarget) {
        s_context = NULL;
        if (!(s_context=find_element(source, &s_context, &(beamline->elem)))) {
          fprintf(stdout, "error: cannot make link with source element %s--not in beamline\n", source);
          fflush(stdout);
          exitElegant(1);
        }
      }
      eptr = tmalloc(sizeof(*eptr)*(n_targets));
      if (src_position_code==SRC_POSITION_SAME_OCCURENCE) {
        n_sources = 0;
        while (n_sources<n_targets) {
          eptr1 = NULL;
          s_context = NULL;
          while (find_element(source, &s_context, &(beamline->elem))) {
            if (s_context->occurence==links->target_elem[n_links][n_sources]->occurence) {
              eptr1 = s_context;
              break;
            }
          }
          if (!eptr1) {
            fprintf(stdout, "error: no %s element is found with the same occurence number as the %ld-th %s element--can't link as requested\n",
                    source, n_sources, target);
            fflush(stdout);
            exitElegant(1);
          }
          eptr[n_sources++] = eptr1;
        }
      }
      else if (src_position_code==SRC_POSITION_NEAREST) {
        n_sources = 0;
        while (n_sources<n_targets) {
          dz_min = DBL_MAX;
          eptr1 = NULL;
          s_context = NULL;
          while (find_element(source, &s_context, &(beamline->elem))) {
            if ((dz = fabs(s_context->end_pos-links->target_elem[n_links][n_sources]->end_pos))<dz_min) {
              eptr1 = s_context;
              dz_min = dz;
            }
          }
          if (!eptr1) {
            fprintf(stdout, "error: no %s element is found near the %ld-th %s element--can't link as requested\n",
                    source, n_sources, target);
            fflush(stdout);
            exitElegant(1);
          }
          eptr[n_sources++] = eptr1;
        }
      }
      else if (src_position_code==SRC_POSITION_ADJACENT) {
        n_sources = 0;
        while (n_sources<n_targets) {
          eptr1 = NULL;
          if ((eptr1=links->target_elem[n_links][n_sources]->pred)) {
            if (strcmp(eptr1->name, source)!=0)
              eptr1 = NULL;
          }
          if (!eptr1 && (eptr1=links->target_elem[n_links][n_sources]->succ)) {
            if (strcmp(eptr1->name, source)!=0)
              eptr1 = NULL;
          }
          if (!eptr1) {
            fprintf(stdout, "error: no %s element is found adjacent to the %ld-th %s element--can't link as requested\n",
                    source, n_sources, target);
            fflush(stdout);
            exitElegant(1);
          }
          eptr[n_sources++] = eptr1;
        }
      }
      else if (src_position_code==SRC_POSITION_BEFORE) {
        if (links->target_elem[n_links][0]->end_pos<s_context->end_pos) {
          fprintf(stdout, "error: there is no %s element before the first %s element--can't link as requested\n",
                  source, target);
          fflush(stdout);
          exitElegant(1);
        }
        eptr[0] = s_context;
        n_sources = 0;
        while (n_sources<n_targets) {
          eptr1 = NULL;
          do {
            if (s_context->end_pos<links->target_elem[n_links][n_sources]->end_pos)
              eptr1 = s_context;
            else if (s_context->end_pos==links->target_elem[n_links][n_sources]->end_pos) {
              eptr1 = s_context;
              break;
            }
            else
              break;
          } while (find_element(source, &s_context, &(beamline->elem)));
          if (!eptr1) {
            fprintf(stdout, "error: no %s element is found before the %ld-th %s element--can't link as requested\n",
                    source, n_sources, target);
            fflush(stdout);
            exitElegant(1);
          }
          eptr[n_sources++] = eptr1;
          s_context = eptr[n_sources-1];
        }
      }
      else if (src_position_code==SRC_POSITION_AFTER) {
        if (links->target_elem[n_links][0]->end_pos>=s_context->end_pos) {
          /* search for first source element after first target element */
          while (find_element(source, &s_context, &(beamline->elem))) {
            if (links->target_elem[n_links][0]->end_pos<s_context->end_pos)
              break;
          }
          if (!s_context) {
            fprintf(stdout, "error: no %s element after the first %s element--can't link as requested\n",
                    source, target);
            fflush(stdout);
            exitElegant(1);
          }
        }
        eptr[0] = s_context;
        n_sources = 1;
        while (n_sources<n_targets) {
          s_context = links->target_elem[n_links][n_sources-1];
          while (find_element(source, &s_context, &(beamline->elem))) {
            if (s_context->end_pos>links->target_elem[n_links][n_sources]->end_pos)
              break;
          }
          if (!s_context) {
            fprintf(stdout, "error: no %s element is found after the %ld-th %s element--can't link as requested\n",
                    source, n_sources, target);
            fflush(stdout);
            exitElegant(1);
          }
          eptr[n_sources++] = s_context;
        }
      }

      links->source_elem[n_links] = eptr;

#if DEBUG
      fprintf(stdout, "list of targets and sources:\n");
      fflush(stdout);
      for (i=0; i<n_targets; i++)
        fprintf(stdout, "%s at z=%em linked to %s at z=%em\n", 
                links->target_elem[n_links][i]->name, links->target_elem[n_links][i]->end_pos,
                links->source_elem[n_links][i]->name, links->source_elem[n_links][i]->end_pos);
      fflush(stdout);
#endif

      links->n_links += 1;
    }
    
    log_exit("add_element_links");
    }
Exemplo n.º 11
0
/* Set twiss parameter arrays etc. */
void init_IBS(ELEMENT_LIST *element)
{
  long count, nElements, i, j, isRing = 0, init=1;
  double startRingPos, finalPos;
  double s0, s1, dt, delta_s, p0, gamma;
  ELEMENT_LIST *element0, *elementStartRing, *eptr=NULL;
  IBSCATTER *IBS=NULL;
  TWISS *tp;
  
  if (!element->twiss) 
    bombElegant("Twiss parameters must be calculated befor IBS tracking.", NULL);

  /* Find out start point of ring */
  element0 = elementStartRing = element;
  startRingPos = 0;

  count = 0;
  while (element) {
    if (element->type==T_RECIRC) {
      startRingPos = element->end_pos;
      elementStartRing = element->succ;
      count++;
      break;
    }
    count++;
    element = element->succ;
  }

  if (elementStartRing!=element0) {
    element = elementStartRing;
  } else {
    element = element0;
    count = 0;
  }

  nElements =0;
  s1 = startRingPos;
  dt = delta_s = 0.;
  while (element) {
    s0 = s1;
    s1 = element->end_pos;
    if (s1 > s0) {
      if (element->pred)
        p0 = (element->Pref_output + element->pred->Pref_output)/2.;
      else
        p0 = element->Pref_output;
      gamma = sqrt(p0*p0+1);
      dt += (s1-s0)*gamma/p0/c_mks;
      delta_s += (s1-s0);
    }

    if (element->type==T_IBSCATTER) {
      IBS = (IBSCATTER*)element->p_elem; 
      IBS->revolutionLength = delta_s;
      if (nElements<2) 
        bombElegant("you need at least 2 other elements between IBSCATTERS, check twiss file for clue", NULL);
      IBS->dT = dt;
      dt = delta_s = 0.;
      IBS->elements = nElements;
      IBS->offset = count;
      IBS->output = 1;
      count = count + nElements +1;
      isRing = IBS->isRing;
      if (!(IBS->name = SDDS_Calloc(nElements,  sizeof(*(IBS->name)))) ||
          !(IBS->s = SDDS_Calloc(nElements, sizeof(*(IBS->s)))) ||
          !(IBS->pCentral = SDDS_Calloc(nElements, sizeof(*(IBS->pCentral)))))
        bombElegant("memory allocation failure in init_IBS", NULL);
      if (!(IBS->etax = SDDS_Realloc(IBS->etax, sizeof(*(IBS->etax))*nElements)) ||
          !(IBS->etaxp = SDDS_Realloc(IBS->etaxp, sizeof(*(IBS->etaxp))*nElements)) ||
          !(IBS->etay = SDDS_Realloc(IBS->etay, sizeof(*(IBS->etay))*nElements)) ||
          !(IBS->etayp = SDDS_Realloc(IBS->etayp, sizeof(*(IBS->etayp))*nElements)))
        bombElegant("memory allocation failure in init_IBS", NULL);
      if (!(IBS->icharge = SDDS_Realloc(IBS->icharge, sizeof(*(IBS->icharge))*IBS->nslice)) ||
          !(IBS->emitx0 = SDDS_Realloc(IBS->emitx0, sizeof(*(IBS->emitx0))*IBS->nslice)) ||
          !(IBS->emity0 = SDDS_Realloc(IBS->emity0, sizeof(*(IBS->emity0))*IBS->nslice)) ||
          !(IBS->emitl0 = SDDS_Realloc(IBS->emitl0, sizeof(*(IBS->emitl0))*IBS->nslice)) ||
          !(IBS->sigmaz0 = SDDS_Realloc(IBS->sigmaz0, sizeof(*(IBS->sigmaz0))*IBS->nslice)) ||
          !(IBS->sigmaDelta0 = SDDS_Realloc(IBS->sigmaDelta0, sizeof(*(IBS->sigmaDelta0))*IBS->nslice)) ||
          !(IBS->emitx = SDDS_Realloc(IBS->emitx, sizeof(*(IBS->emitx))*IBS->nslice)) ||
          !(IBS->emity = SDDS_Realloc(IBS->emity, sizeof(*(IBS->emity))*IBS->nslice)) ||
          !(IBS->emitl = SDDS_Realloc(IBS->emitl, sizeof(*(IBS->emitl))*IBS->nslice)) ||
          !(IBS->sigmaz = SDDS_Realloc(IBS->sigmaz, sizeof(*(IBS->sigmaz))*IBS->nslice)) ||
          !(IBS->sigmaDelta = SDDS_Realloc(IBS->sigmaDelta, sizeof(*(IBS->sigmaDelta))*IBS->nslice)) ||
          !(IBS->xGrowthRate = SDDS_Realloc(IBS->xGrowthRate, sizeof(*(IBS->xGrowthRate))*IBS->nslice)) ||
          !(IBS->yGrowthRate = SDDS_Realloc(IBS->yGrowthRate, sizeof(*(IBS->yGrowthRate))*IBS->nslice)) ||
          !(IBS->zGrowthRate = SDDS_Realloc(IBS->zGrowthRate, sizeof(*(IBS->zGrowthRate))*IBS->nslice)))
        bombElegant("memory allocation failure in init_IBS", NULL);
      if (!(IBS->betax = (double**)czarray_2d(sizeof(double), IBS->nslice, nElements)) ||
          !(IBS->alphax = (double**)czarray_2d(sizeof(double), IBS->nslice, nElements)) ||
          !(IBS->betay = (double**)czarray_2d(sizeof(double), IBS->nslice, nElements)) ||
          !(IBS->alphay = (double**)czarray_2d(sizeof(double), IBS->nslice, nElements)) ||
          !(IBS->xRateVsS = (double**)czarray_2d(sizeof(double), IBS->nslice, nElements)) ||
          !(IBS->yRateVsS = (double**)czarray_2d(sizeof(double), IBS->nslice, nElements)) ||
          !(IBS->zRateVsS = (double**)czarray_2d(sizeof(double), IBS->nslice, nElements)))
        bombElegant("memory allocation failure in init_IBS", NULL);

      for (i=0; i<IBS->elements; i++) {
        cp_str(&IBS->name[i], elementStartRing->name);
        IBS->s[i] = elementStartRing->end_pos;
        IBS->pCentral[i] = elementStartRing->Pref_output;
        IBS->etax[i] = elementStartRing->twiss->etax;
        IBS->etaxp[i] = elementStartRing->twiss->etapx;
        IBS->etay[i] = elementStartRing->twiss->etay;
        IBS->etayp[i] = elementStartRing->twiss->etapy;
        if (init)
          twiss0 = tmalloc(sizeof(*twiss0)*IBS->nslice);
        /*
          twiss0 = SDDS_Realloc(twiss0, sizeof(*twiss0)*IBS->nslice);
        */
        for (j=0; j<IBS->nslice; j++) {
          if (init) {
            tp = &(twiss0[j]);
            copy_twiss(tp, elementStartRing->twiss);
          }
          IBS->betax[j][i] = elementStartRing->twiss->betax;
          IBS->alphax[j][i] = elementStartRing->twiss->alphax;   
          IBS->betay[j][i] = elementStartRing->twiss->betay;   
          IBS->alphay[j][i] = elementStartRing->twiss->alphay;   
        }
        init = 0;
        elementStartRing = elementStartRing->succ;
      }
      IBS->elem = tmalloc(sizeof(*(IBS->elem)));
      IBS->elem->pred = IBS->elem->succ = NULL;
      elementStartRing = elementStartRing->pred;
      for (i=IBS->elements; i>0; i--) {
        add_element(IBS->elem, elementStartRing);
        eptr = IBS->elem->succ;
        /* copy input energy to newly added element. Necessary if beamline contains RF cavity */
        eptr->Pref_input = elementStartRing->Pref_input;
        eptr->Pref_output = elementStartRing->Pref_output;
        elementStartRing = elementStartRing->pred;
      }
      IBS->elem = eptr;
      eptr->pred = eptr->pred->succ = NULL;
      nElements = -1;
      elementStartRing = element->succ;
    }
    nElements ++;
    finalPos = element->end_pos;
    element = element->succ;
  }
  
  if (isRing)
    if (finalPos != IBS->s[IBS->elements-1])
      bombElegant("You must have IBSCATTER at the end of the RING", NULL);
  element = element0;
  return;
}
Exemplo n.º 12
0
long scan_namelist(NAMELIST_TEXT *nl, char *line)
{
    register char *ptr, *ptr_e;
    char *ptr_p, *ptr_to_free ;
    long n_entities, i, j, length_values, length;
    char *values;
    static char *buffer = NULL;
    static long bufsize = 0;
#define BIGBUFSIZE 16384
#define INDEX_LIMIT 16380
#if !defined(vxWorks)
    long k, m, n, len, insideCommand;
    char psBuffer[16384], tempptr[16384], command[16384];
    FILE *fID;
#ifdef CONDOR_COMPILE
    char tmpName[1024];
#endif
#endif

    values = NULL;
    length_values = 0;
    if (!buffer)
        buffer = tmalloc(sizeof(*buffer)*(bufsize = 128));

    nl->n_entities = 0;
    nl->group_name = NULL;
    nl->entity   = NULL;
    nl->value    = NULL;
    nl->n_values = nl->n_subscripts = NULL;
    nl->subscript = nl->repeat = NULL;

#ifdef DEBUG
    printf("scan_namelist: line = <%s>\n", line);
#endif
    cp_str(&ptr_to_free, line);
    ptr = ptr_to_free;

    /* Find group name--it's a token starting with '$' or '&'. */
#if DOLLARSIGN_TOO
    if (!(ptr_p=next_unquoted_char(ptr, '$', '"')) &&
        !(ptr_p=next_unquoted_char(ptr, '&', '"')) ) {
        free(ptr_to_free);
        fprintf(stderr, "error: namelist scanning problem---missing group name:\n%s\n", ptr);
        return(-1);
        }
#else
    if (!(ptr_p=next_unquoted_char(ptr, '&', '"'))) {
        free(ptr_to_free);
        fprintf(stderr, "error: namelist scanning problem---missing group name:\n%s\n", ptr);
        return(-1);
        }
#endif
    ptr_p++;
    if ((nl->group_name=get_token(ptr_p))==NULL) {
        free(ptr_to_free);
        fprintf(stderr, "error: namelist scanning problem---missing group name:\n%s\n", ptr);
        return(-1);
        }
#ifdef DEBUG
    printf("scan_namelist: nl->group_name = <%s>\n", nl->group_name);
#endif

    /* Count entities--each entity is associated with an equals sign,
     * since these are all assignments. */
#if DOLLARSIGN_TOO
    n_entities = count_occurences(ptr_p, '=', "$&");
#else
    n_entities = count_occurences(ptr_p, '=', "&");
#endif
    if (n_entities==0) {
        free(ptr_to_free);
        return(nl->n_entities=0);
        }
#ifdef DEBUG
    printf("scan_namelist: n_entities = %ld\n", n_entities);
#endif

    /* allocate memory for parallel arrays representing the namelist:
     *   nl->entity is an array of entity names
     *   nl->value is an array of arrays of values assigned
     *   nl->repeat is an array of arrays of repeat factors applied to values
     *   nl->n_values is an array of numbers of values
     *   nl->n_subscripts is an array of numbers of subscripts
     *   nl->subscript is an array of arrays of subscripts
     */
    nl->entity   = tmalloc(sizeof(*(nl->entity  ))*n_entities);
    nl->value    = tmalloc(sizeof(*(nl->value   ))*n_entities);
    nl->repeat   = tmalloc(sizeof(*(nl->repeat  ))*n_entities);
    nl->n_values = tmalloc(sizeof(*(nl->n_values))*n_entities);
    nl->n_subscripts = tmalloc(sizeof(*(nl->n_subscripts))*n_entities);
    nl->subscript    = tmalloc(sizeof(*(nl->subscript))*n_entities);

#ifdef DEBUG
    printf("scan_namelist: allocation successful\n");
#endif

    /* scan individual items--look for entity names and successively extract
     * strings containing assignments for single entities.  For each string,
     * extract a list of values and repeat factors.
     */
    for (i=0; i<n_entities; i++) {
        /* Find next entity name, which terminates with '='.  ptr_p
         * points to the section of the string being parsed.  I.e., everything
         * before ptr_p has been parsed already. */
        if (!(ptr_e = next_unquoted_char(ptr_p, '=', '"'))) {
            fprintf(stderr, "scan_namelist: no '=' in string >%s<\n", ptr_p);
            exit(1);
            }

        ptr = ptr_e;
        while (isspace(*(ptr-1)))
            ptr--;
        *ptr = 0;                /* end entity name string at '=' or space */

        while (isspace(*ptr_p))    /* advance to start of name      */
            ptr_p++;
        cp_str(nl->entity+i, ptr_p);   /* copy the entity name */
        nl->n_subscripts[i] = extract_subscripts(nl->entity[i], nl->subscript+i);

#ifdef DEBUG
        printf("scan_namelist: nl->entity[%ld] = <%s>\n", i, nl->entity[i]);
        printf("remainder: <%s>\n", ptr_e+1);
#endif

        /* Set ptr to point to start of values list, which follows the '='
         * that was just found and deleted. */
        ptr = ptr_e + 1;

        /* Find next entity name, if there is one, and insert a 0 before it
         * to mark end of current values list. */
        if ((ptr_e = next_unquoted_char(ptr, '=', '"'))) {
            /* set ptr_e to point to end of values list for current entity,
             * which is at the comma or space preceeding the next entity name
             */
#ifdef DEBUG
            printf("scan_namelist: next list is <%s>\n", ptr_e);
#endif
            /* Skip whitespace and get to the entity name. */
            ptr_e--;
            while (isspace(*ptr_e) && ptr_e!=ptr)
                ptr_e--;
            /* Skip over the entity name. */
            while (*ptr_e==')' || *ptr_e=='}') {
                ptr_e--;
                while (*ptr_e!='(' && *ptr_e!='{' && ptr_e!=ptr)
                    ptr_e--;
                }
            while (!(isspace(*ptr_e) || *ptr_e==',') && ptr_e!=ptr)
                ptr_e--;
            ptr_p = ptr_e+1;      /* Save start of next entity. */
            /* Skip trailing whitespace and commas in the values list. */
            while ((isspace(*ptr_e) || *ptr_e==',') && ptr_e!=ptr)
                ptr_e--;
            /* If there's nothing left, there was no value given. */
            if (++ptr_e==ptr)
                bomb("missing value in namelist", NULL);
            /* Mark end of values with a NUL, and set ptr_p to the point
             * where processing begins for the next entity. */
            *ptr_e = 0;
            }
        else {
            /* There is no following entity, so there should be a '$end'
             * '&end', or just '$' or '&'.   */
            /* set ptr_e to $end of string, check for error */
#ifdef DEBUG
            printf("scan_namelist: last item is <%s>\n", ptr);
#endif
#if DOLLARSIGN_TOO
            if (!(ptr_e=next_unquoted_char(ptr, '&', '"')) && !(ptr_e=next_unquoted_char(ptr, '$', '"')) ) {
                fprintf(stderr, "error: namelist improperly terminated\n");
                return(-1);
                }
#else
            if (!(ptr_e=next_unquoted_char(ptr, '&', '"'))) {
                fprintf(stderr, "error: namelist improperly terminated\n");
                return(-1);
                }
#endif
            *ptr_e = 0;           /* Delete the symbol. */

            /* If the number of entities doesn't match what was counted before,
             * something is really goofy. */
            if (i!=n_entities-1) {
#ifdef DEBUG
                printf("scan_namelist: fatal error: n_entites=%ld, i=%ld\n", n_entities,
                      i);
#endif
                return(-1);
                }

            /* Scan backwards to the first token. Make sure there are some
             * values listed. */
            ptr_e--;
            while ((isspace(*ptr_e) || *ptr_e==',') && ptr_e!=ptr)
                ptr_e--;
            if (++ptr_e==ptr) {
#ifdef DEBUG
            printf("scan_namelist: fatal error: ptr_e = ptr\n");
            printf("scan_namelist: ptr = <%s>\n", ptr);
#endif
                fprintf(stderr, "error: no values listed for namelist field %s\n",
                        nl->entity[i]);
                return(-1);     /* No values listed. */
                }
            *ptr_e = 0;
            ptr_p = ptr_e;
            }
        /* ptr now points to the beginning of the values list, which is
         * NUL terminated.  ptr_p points to the beginning of the rest of
         * what remains to be parsed. */
#ifdef DEBUG
        printf("scan_namelist: values list = <%s>\n", ptr);
        printf("scan_namelist: remainder = <%s>\n", ptr_p);
#endif
#if !defined(vxWorks)
	length = strlen(ptr);
	if (length == 0) {
            fprintf(stderr, "error: missing values for namelist field %s\n",
                    nl->entity[i]);
            return -1;
	}
	n = 0;
	j = 0;
	k = 0;
	insideCommand = 0;
	while (n<length) {
	  if (j>INDEX_LIMIT) {
	      fprintf(stderr, "error: values for namelist field %s is too long\n",
		      nl->entity[i]);
	      return -1;
	  }
	  if (ptr[n]=='\\') {
            if (ptr[n+1]!='}' && ptr[n+1]!='{')
              tempptr[j++] = ptr[n++];
            else
              n++;
	    if (n<length) {
	      if (insideCommand) {
		command[k] = ptr[n];
		k++;
		n++;		
	      } else {
		tempptr[j] = ptr[n];
		j++;
		n++;
	      }
	    }
	  } else if (ptr[n]=='{') {
	    if (insideCommand) {
	      fprintf(stderr, "error: values for namelist field %s has invalid command brackets\n",
		      nl->entity[i]);
	      return -1;
	    }
	    insideCommand = 1;
	    k = 0;
	    n++;
	  } else if (ptr[n]=='}') {
	    if (!insideCommand) {
	      fprintf(stderr, "error: values for namelist field %s has invalid command brackets\n",
		      nl->entity[i]);
	      return -1;
	    }
	    insideCommand = 0;
	    command[k] = 0;
	    n++;
#ifndef CONDOR_COMPILE
	    if ((fID = popen(command, "r")) == NULL) {
	      fprintf(stderr, "error: invalid command for namelist field %s\n",
		      nl->entity[i]);
              fprintf(stderr, "command was %s\n", command);
	      return -1;
	    }
	    if (feof(fID)) {
	      fprintf(stderr, "error: command for namelist field %s returns EOF\n",
		      nl->entity[i]);
              fprintf(stderr, "command was %s\n", command);
	      return -1;
	    }
	    if (fgets(psBuffer, 128, fID) == NULL) {
	      fprintf(stderr, "error: command for namelist field %s returns NULL\n",
		      nl->entity[i]);
              fprintf(stderr, "command was %s\n", command);
	      return -1;
	    }
            pclose(fID);
#else
            tmpnam(tmpName);
            sprintf(psBuffer, "%s > %s", command, tmpName);
            system(psBuffer);
            if (!(fID = fopen(tmpName, "r"))) {
	      fprintf(stderr, "error: command for namelist field %s failed\n",
		      nl->entity[i]);
              fprintf(stderr, "command was %s\n", command);
	      return -1;
            }
            if (fgets(psBuffer, 128, fID) == NULL) {
	      fprintf(stderr, "error: command for namelist field %s returns NULL\n",
		      nl->entity[i]);
              fprintf(stderr, "command was %s\n", command);
	      return -1;
            }
            fclose(fID);
            remove(tmpName);
 #endif
	    len = strlen(psBuffer)-1;
	    if ((len > 0) && (psBuffer[len] == '\n')) {
	      psBuffer[len] = 0;
	    }
	    m = 0;
	    len = strlen(psBuffer);
	    if (j+len>INDEX_LIMIT) {
	      fprintf(stderr, "error: values for namelist field %s is too long\n",
		      nl->entity[i]);
	      return -1;
	    }
	    while (m < len) {
	      tempptr[j] = psBuffer[m];
	      j++;
	      m++;
	    } 
	  } else {
	    if (insideCommand) {
	      command[k] = ptr[n];
	      n++;
	      k++;
	    } else {
	      tempptr[j] = ptr[n];
	      n++;
	      j++;
	    }
	  }
	}
	tempptr[j] = 0;
	
	ptr = tempptr;
#endif
        /* Process string of values.  Values must be separated by commas. */
        length = strlen(ptr)+1;
        if (length==1) {
            fprintf(stderr, "error: missing values for namelist field %s\n",
                    nl->entity[i]);
            return -1;
            }
        if (values==NULL) {
            values = tmalloc(length*sizeof(*values));
            length_values = length;
            }
        else if (length>length_values) {
            tfree(values);
            values = tmalloc(length*sizeof(*values));
            }
        strcpy_ss(values, ptr);
        nl->n_values[i] = count_occurences(values, ',', "")+1;
        nl->value[i]    = tmalloc(sizeof(*(nl->value[i]))*nl->n_values[i]);
        nl->repeat[i]   = tmalloc(sizeof(*(nl->repeat[i]))*nl->n_values[i]);
#ifdef DEBUG
        printf("scan_namelist: allocation successful--nl->n_values[%ld]=%ld\n",
            i, nl->n_values[i]);
#endif

        for (j=0; j<nl->n_values[i]; j++) {
#ifdef DEBUG
          printf("scan_namelist: scanning tokens from >%s<\n",
                 values);
#endif
            ptr = nl->value[i][j] =
                    get_token_tq(values, ", ", ", ", "\"'", "\"'");
#ifdef DEBUG
            printf("scan_namelist: looping over values--j=%ld\n", j);
            printf("scan_namelist: token is <%s>\n", ptr);
#endif 
            if (!ptr) {
                fprintf(stderr, "error: missing values for namelist field %s\n",
                        nl->entity[i]);
                return -1;
                }
            if (!isdigit(*ptr)) {
                nl->repeat[i][j] = 1;
                un_quote(ptr);
                }
            else {
                ptr_e = ptr;
                while (isdigit(*ptr))
                    ptr++;
                if (*ptr!='*') {
                    nl->repeat[i][j] = 1;
                    continue;
                    }
                *ptr = 0;
                if ((length=strlen(ptr_e))-1>bufsize)
                    buffer = trealloc(buffer, sizeof(*buffer)*(bufsize=length+1024));
                strcpy_ss(buffer, ptr_e);
                strcpy_ss(nl->value[i][j], ptr+1);
                un_quote(nl->value[i][j]);
#ifdef DEBUG
                printf("doing repeat scan: ptr_e = <%s>  ptr+1 = <%s>\nbuffer = <%s>\n",
                    ptr_e, ptr+1, buffer);
#endif
                if (sscanf(buffer, "%ld", nl->repeat[i]+j)!=1)
                    bomb("bad repeat specifier in namelist", NULL);
                }
#ifdef DEBUG
            printf("scan_namelist: nl->value[%ld][%ld] = %ld*<%s>\n",
                i, j, nl->repeat[i][j], nl->value[i][j]);
            printf("remainder: <%s>\n\n", values);
#endif
            }
        }

    free(values);
    free(ptr_to_free);
#ifdef DEBUG
    nl->n_entities = n_entities;
    show_namelist(stdout, nl);
#endif
    return(nl->n_entities=n_entities);
    }
Exemplo n.º 13
0
int main(int argc, char **argv)
{
    SDDS_DATASET SDDS_1, SDDS_2, SDDS_output;
    long i, j, i_arg, rows1, rows2, reuse, reusePage, i1, i2;
    SCANNED_ARG *s_arg;
    char s[200], *ptr;
    char **match_column, **equate_column;
    long match_columns, equate_columns;
    char *input1, *input2, *output;
    long tmpfile_used, retval1, retval2;
    long warnings, invert;
    unsigned long pipeFlags;
    KEYED_EQUIVALENT **keyGroup=NULL;
    long keyGroups=0;
    
    SDDS_RegisterProgramName(argv[0]);
    argc = scanargs(&s_arg, argc, argv);
    if (argc<3) 
        bomb(NULL, USAGE);

    input1 = input2 = output = NULL;
    match_column  = equate_column  = NULL;
    match_columns = equate_columns = reuse = reusePage = 0;
    tmpfile_used = invert = 0;
    warnings = 1;
    pipeFlags = 0;

    for (i_arg=1; i_arg<argc; i_arg++) {
        if (s_arg[i_arg].arg_type==OPTION) {
            delete_chars(s_arg[i_arg].list[0], "_");
            switch (match_string(s_arg[i_arg].list[0], option, N_OPTIONS, 0)) {
              case SET_MATCH_COLUMN:
                if (s_arg[i_arg].n_items!=2)
                    SDDS_Bomb("invalid -match syntax");
                if (match_columns!=0)
                    SDDS_Bomb("only one -match option may be given");
		match_column = tmalloc(sizeof(*match_column)*2);
                if ((ptr=strchr(s_arg[i_arg].list[1], '=')))
                    *ptr++ = 0;
                else 
                    ptr = s_arg[i_arg].list[1];
                match_column[0] = s_arg[i_arg].list[1];
                match_column[1] = ptr;
		match_columns = 1;
                break;
              case SET_EQUATE_COLUMN:
                if (s_arg[i_arg].n_items!=2)
                    SDDS_Bomb("invalid -equate syntax");
                if (equate_columns!=0)
                    SDDS_Bomb("only one -equate option may be given");
		equate_column = tmalloc(sizeof(*equate_column)*2);
                if ((ptr=strchr(s_arg[i_arg].list[1], '=')))
                    *ptr++ = 0;
                else 
                    ptr = s_arg[i_arg].list[1];
                equate_column[0] = s_arg[i_arg].list[1];
                equate_column[1] = ptr;
		equate_columns = 1;
                break;
              case SET_REUSE:
                if (s_arg[i_arg].n_items==1)
                    reuse = 1;
                else {
                    char *reuseOptions[2] = {"rows", "page"};
                    for (i=1; i<s_arg[i_arg].n_items; i++) {
                        switch (match_string(s_arg[i_arg].list[i], reuseOptions, 2, 0)) {
                          case 0:
                            reuse = 1;
                            break;
                          case 1:
                            reusePage = 1;
                            break;
                          default:
                            SDDS_Bomb("unknown reuse keyword");
                            break;
                            }
                        }
                    }
                break;
              case SET_INVERT:
                invert = 1;
                break;
              case SET_NOWARNINGS:
                warnings = 0;
                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;
              default:
                fprintf(stderr, "error: unknown switch: %s\n", s_arg[i_arg].list[0]);
                SDDS_Bomb(NULL);
                break;
                }
            }
        else {
            if (input1==NULL)
                input1 = s_arg[i_arg].list[0];
            else if (input2==NULL)
                input2 = s_arg[i_arg].list[0];
            else if (output==NULL)
                output = s_arg[i_arg].list[0];
            else
                SDDS_Bomb("too many filenames");
            }
        }

    if (pipeFlags&USE_STDIN && input1) {
        if (output)
            SDDS_Bomb("too many filenames (sddsxref)");
        output = input2;
        input2 = input1;
        input1 = NULL;
        }
    processFilenames("sddsselect", &input1, &output, pipeFlags, !warnings, &tmpfile_used);
    if (!input2)
        SDDS_Bomb("second input file not specified (sddsxref)");

    if (equate_columns && match_columns)
        SDDS_Bomb("only one of -equate or -match may be given");
    if (!equate_columns && !match_columns)
        SDDS_Bomb("one of -equate or -match must be given");

    if (!SDDS_InitializeInput(&SDDS_1, input1)) {
        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
        exit(1);
        }
    if (!SDDS_InitializeInput(&SDDS_2, input2)) {
        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
        exit(1);
        }

    if (match_columns) {
        if ((j=SDDS_GetColumnIndex(&SDDS_1, match_column[0]))<0 || SDDS_GetColumnType(&SDDS_1, j)!=SDDS_STRING) {
            sprintf(s, "error: column %s not found or not string type in file %s", match_column[0], input1?input1:"stdin");
            SDDS_SetError(s);
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
            }
        if ((j=SDDS_GetColumnIndex(&SDDS_2, match_column[1]))<0 || SDDS_GetColumnType(&SDDS_2, j)!=SDDS_STRING) {
            sprintf(s, "error: column %s not found or not string type in file %s", match_column[1], input2);
            SDDS_SetError(s);
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
            }
        }
    if (equate_columns) {
        if ((j=SDDS_GetColumnIndex(&SDDS_1, equate_column[0]))<0 || !SDDS_NUMERIC_TYPE(SDDS_GetColumnType(&SDDS_1, j))) {
            sprintf(s, "error: column %s not found or not numeric type in file %s", equate_column[0], input1?input1:"stdin");
            SDDS_SetError(s);
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
            }
        if ((j=SDDS_GetColumnIndex(&SDDS_2, equate_column[1]))<0 || !SDDS_NUMERIC_TYPE(SDDS_GetColumnType(&SDDS_2, j))) {
            sprintf(s, "error: column %s not found or not numeric type in file %s", equate_column[1], input2);
            SDDS_SetError(s);
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
            }
        }

    if (output && pipeFlags&USE_STDOUT)
        SDDS_Bomb("too many filenames with -pipe option");
    if (!output && !(pipeFlags&USE_STDOUT)) {
        if (warnings)
            fprintf(stderr, "warning: existing file %s will be replaced (sddsselect)\n", input1?input1:"stdin");
        tmpfile_used = 1;
        cp_str(&output, tmpname(NULL));
        }
    if (!SDDS_InitializeCopy(&SDDS_output, &SDDS_1, output, "w")) {
        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
        exit(1);
        }

    if (!SDDS_WriteLayout(&SDDS_output)) 
        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
   
    while ((retval1=SDDS_ReadPage(&SDDS_1))>0) {
        if (!reusePage) {
            if ((retval2=SDDS_ReadPage(&SDDS_2))<=0) {
                if (warnings)
                    fprintf(stderr, "warning: <input2> ends before <input1>\n");
                if (invert) {
                    /* nothing to match, so everything would normally be thrown out */
                    if (!SDDS_CopyPage(&SDDS_output, &SDDS_1) || !SDDS_WritePage(&SDDS_output))
                        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
                    continue;
                    }
                else 
                    /* nothing to match, so everything thrown out */
                    break;
                }
            }
        else {
            if (retval1==1 && (retval2=SDDS_ReadPage(&SDDS_2))<=0)
                SDDS_Bomb("<input2> has no data");
            SDDS_SetRowFlags(&SDDS_2, 1);
            }
        rows1 = SDDS_CountRowsOfInterest(&SDDS_1);
        rows2 = SDDS_CountRowsOfInterest(&SDDS_2);
        
        if (!SDDS_StartPage(&SDDS_output, rows1)) {
            SDDS_SetError("Problem starting output page");
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
            }
        if (!SDDS_CopyParameters(&SDDS_output, &SDDS_2) || !SDDS_CopyArrays(&SDDS_output, &SDDS_2)) {
            SDDS_SetError("Problem copying parameter or array data from second input file");
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
            }
        if (!SDDS_CopyParameters(&SDDS_output, &SDDS_1) || !SDDS_CopyArrays(&SDDS_output, &SDDS_1)) {
            SDDS_SetError("Problem copying parameter or array data from first input file");
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
            }
        if (match_columns) {
          char **string1, **string2;
          long matched;
          string2 = NULL;
          if (!(string1 = SDDS_GetColumn(&SDDS_1, match_column[0]))) {
            fprintf(stderr, "Error: problem getting column %s from file %s\n", 
                    match_column[0], input1?input1:"stdin");
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
          }
          if (rows2 && !(string2 = SDDS_GetColumn(&SDDS_2, match_column[1]))) {
            fprintf(stderr, "Error: problem getting column %s from file %s\n", 
                    match_column[1], input2);
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
          }
          if (rows2)
            keyGroup = MakeSortedKeyGroups(&keyGroups, SDDS_STRING, string2, rows2);
          for (i1=0; i1<rows1; i1++) {
            if (!SDDS_CopyRowDirect(&SDDS_output, i1, &SDDS_1, i1)) {
              sprintf(s, "Problem copying row %ld of first data set", i1);
              SDDS_SetError(s);
                    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
            }
            matched = 0;
            if (rows2 &&(i2 = FindMatchingKeyGroup(keyGroup, keyGroups, SDDS_STRING, string1+i1, reuse))>=0) {
              matched = 1;
            }
            if ((!matched && !invert) || (matched && invert)) {
              if (!SDDS_AssertRowFlags(&SDDS_output, SDDS_INDEX_LIMITS, i1, i1, 0)) 
                SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
            }
          }
          if (string1) {
            for (i=0;i<rows1;i++) 
              free(string1[i]);
            free(string1);
            string1 = NULL;
          }
          if (string2) {
            for (i=0;i<rows2;i++) 
              free(string2[i]);
            free(string2);
            string2 = NULL;
          }
          for (i=0;i<keyGroups;i++) {
	    if (keyGroup[i]) {
	      if (keyGroup[i]->equivalent)
		free(keyGroup[i]->equivalent);
	      free(keyGroup[i]);
	      keyGroup[i] = NULL;
	    }
          }
          if (keyGroups) {
            free(keyGroup);
	    keyGroup = NULL;
	    keyGroups = 0;
	  }
        }
        else if (equate_columns) {
          double *value1, *value2;
          long equated;
          value2 = NULL;
          if (!(value1 = SDDS_GetColumnInDoubles(&SDDS_1, equate_column[0]))) {
            fprintf(stderr, "Error: problem getting column %s from file %s\n", 
                    equate_column[0], input1?input1:"stdin");
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
          }
          if (rows2 && !(value2 = SDDS_GetColumnInDoubles(&SDDS_2, equate_column[1]))) {
            fprintf(stderr, "Error: problem getting column %s from file %s\n", 
                    equate_column[1], input2);
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
          }
          if (rows2)
            keyGroup = MakeSortedKeyGroups(&keyGroups, SDDS_DOUBLE, value2, rows2);
          for (i1=0; i1<rows1; i1++) {
            if (!SDDS_CopyRowDirect(&SDDS_output, i1, &SDDS_1, i1)) {
              sprintf(s, "Problem copying row %ld of first data set", i1);
              SDDS_SetError(s);
              SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
            }
            equated = 0;
            if (rows2 && (i2 = FindMatchingKeyGroup(keyGroup, keyGroups, SDDS_DOUBLE, value1+i1, reuse))>=0) {
              equated = 1;
            }
            if ((!equated && !invert) || (equated && invert)) {
              if (!SDDS_AssertRowFlags(&SDDS_output, SDDS_INDEX_LIMITS, i1, i1, 0)) 
                SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
            }
          }
          if (value1)
            free(value1);
          value1 = NULL;
          if (rows2 && value2)
            free(value2);
          value2 = NULL;
          for (i=0;i<keyGroups;i++) {
	    if (keyGroup[i]) {
	      if (keyGroup[i]->equivalent)
		free(keyGroup[i]->equivalent);
	      free(keyGroup[i]);
	      keyGroup[i] = NULL;
	    }
          }
          if (keyGroups) {
            free(keyGroup);
	    keyGroup = NULL;
	    keyGroups = 0;
	  }
        }
        if (!SDDS_WritePage(&SDDS_output)) {
          SDDS_SetError("Problem writing data to output file");
          SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
        }
      }

    if (!SDDS_Terminate(&SDDS_1) || !SDDS_Terminate(&SDDS_2) || !SDDS_Terminate(&SDDS_output)) {
      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
      exit(1);
    }
    if (tmpfile_used && !replaceFileAndBackUp(input1, output))
        exit(1);
    free_scanargs(&s_arg,argc);
    if (match_columns) 
      free(match_column);
    return(0);
}
Exemplo n.º 14
0
double rpn(char *expression)
{
    static long i, return_code;
    static char *ptr;
    static char *input, *rpn_defns;
    static long initial_call = 1;
#if defined(LINUX)
    struct stat sts;
#endif

    if (initial_call) {
        initial_call = 0;

#ifdef VAX_VMS
        /* initialize collection of computer usage statistics--required by
         * user-callable function 'rs'
         */
        init_stats();
#endif

        /* sort the command table for faster access */
        qsort(funcRPN, NFUNCS, sizeof(struct FUNCTION), func_compare);

        /* initialize stack pointers--empty stacks */
        stackptr = 0;
        dstackptr = 0;
        sstackptr = 0;
        lstackptr = 0;
        astackptr = 0;
	udf_stackptr = 0;
	max_udf_stackptr = 0;
        astack = NULL;
	udf_stack = NULL;
	udf_id = NULL;
	udf_unknown = NULL;

        /* The first item on the command input stack is the standard input.
         * Input from this source is echoed to the screen. */
        istackptr = 1;
        input_stack[0].fp = stdin;
        input_stack[0].filemode = ECHO;


       /* Initialize variables use in keeping track of what 'code' is being
         * executed.  code_ptr is a global pointer to the currently used
         * code structure.  The code is kept track of in a linked list of
         * code structures.
         */
        code_ptr = &code;
        input = code_ptr->text = tmalloc(sizeof(*(code_ptr->text))*CODE_LEN);
        code_ptr->position = 0;
        code_ptr->token = NULL;
        code_ptr->storage_mode = STATIC;
        code_ptr->buffer = tmalloc(sizeof(*(code_ptr->buffer))*LBUFFER);
        code_ptr->pred = code_ptr->succ = NULL;
        code_lev = 1;

        /* Initialize array of IO file structures.  Element 0 is for terminal
         * input, while element 1 is for terminal output.
         */
        for (i=0; i<FILESTACKSIZE; i++)
            io_file[i].fp = NULL;
        io_file[0].fp = stdin;
        cp_str(&(io_file[0].name), "stdin");
        io_file[0].mode = INPUT;
        io_file[1].fp = stdout;
        cp_str(&(io_file[1].name), "stdout");
        io_file[1].mode = OUTPUT;

        /* initialize variables for UDF storage */
        udf_changed = num_udfs = max_udfs = 0;
        udf_list = NULL;

        /* Initialize flags for user memories */
        n_memories = memory_added = 0;

        /* If there was an argument (filename), push it onto the input stack
         * so that it will be run to set up the program.
         */
        if (expression) {
          if ((input_stack[istackptr].fp = fopen_e(expression, "r", 1))==NULL) {
            fprintf(stderr, "ensure the RPN_DEFNS environment variable is set\n");
            exit(1);
          }
          input_stack[istackptr++].filemode = NO_ECHO;
        }
        else { /*add default setting for a linux system, G. Shen, Dec 31, 2009 */
	    rpn_defns=getenv("RPN_DEFNS");
	    if(!rpn_defns) {
#if defined(LINUX)
		if (!(stat(rpn_default, &sts) == -1 && errno == ENOENT)) { /* check whether default file exists */
		    rpn_defns = rpn_default;
		}
#endif
	    }
	    if (rpn_defns) {
            /* check environment variable RPN_DEFNS for setup file */
		/*cp_str(&rpn_defns, getenv("RPN_DEFNS"));*/
		if (strlen(rpn_defns)) {
		    input_stack[istackptr].fp = fopen_e(rpn_defns, "r", 0);
		    input_stack[istackptr++].filemode = NO_ECHO;
                }
            }
	}
        expression = NULL;

        /* end of initialization section */
        }
    else
        istackptr = 1;

    /* check the stacks for overflows */

    if (stackptr>=STACKSIZE-1) {
        fprintf(stderr, "error: numeric stack size overflow (rpn).\n");
        abort();
        }
/*
    if (astackptr>=STACKSIZE-1) {
        fprintf(stderr, "error: array stack size overflow (rpn).\n");
        abort();
        }
*/
    if (sstackptr>=STACKSIZE-1) {
        fprintf(stderr, "error: string stack size overflow (rpn).\n");
        abort();
        }
    if (lstackptr>=LOGICSTACKSIZE-1) {
        fprintf(stderr, "error: logic stack size overflow (rpn).\n");
        abort();
        }


    /* This is the main loop. Code is read in and executed here. */
    while (istackptr!=0) {
        /* istackptr-1 gives index of most recently pushed input file. */
        /* This loop implements the command input file stacking. */
        while (istackptr>0 &&
               (ptr=((istackptr-1)?fgets((code_ptr->text=input), CODE_LEN,
                                     input_stack[istackptr-1].fp)
                                 :(expression?strcpy(code_ptr->text,expression):NULL) )) ) {
            /* Loop while there's still data in the (istackptr-1)th file. *
             * istackptr=1 corresponds to the expression passed.          *
             * The data is put in the code list.                          */

            /* If we are at the terminal input level and a UDF has been changed
             * or a memory added, relink the udfs to get any references to the
             * new udf or memory translated into 'pcode'.
             */
            if ((istackptr==1 && udf_changed) || memory_added) {
                link_udfs();
                udf_changed = memory_added = 0;
                }
            code_ptr->position = 0;

            /* Get rid of new-lines in data from files */
            if (istackptr!=1 && ptr!=NULL) {
                chop_nl(ptr);
                }

            /* Check for and ignore comment lines. */
            if (strncmp(ptr, "/*", 2)==0)
                continue;

            /* Finally, push input line onto the code stack & execute it.   */
            return_code = execute_code();
            if (code_lev!=1) {
                fputs("error: code level on return from execute_code is not 1\n\n", stderr);
                exit(1);
                }
            /* Reset pointers in the current code structure to indicate that the
             * stuff has been executed.
             */
            *(code_ptr->text) = 0;
            code_ptr->position = 0;

            expression = NULL;
            }

        /* Close the current input file and go to the one below it on the *
         * stack.  This constitutes popping the command input stack.      *
         */
        if (istackptr>1)
            fclose(input_stack[--istackptr].fp);
        else
            istackptr--;
        }

    /* check the stacks for overflows */
    if (stackptr>=STACKSIZE-1) {
        fprintf(stderr, "error: numeric stack size overflow (rpn).\n");
        abort();
        }
/*
    if (astackptr>=STACKSIZE-1) {
        fprintf(stderr, "error: array stack size overflow (rpn).\n");
        abort();
        }
*/
    if (sstackptr>=STACKSIZE-1) {
        fprintf(stderr, "error: string stack size overflow (rpn).\n");
        abort();
        }
    if (lstackptr>=LOGICSTACKSIZE-1) {
        fprintf(stderr, "error: logic stack size overflow (rpn).\n");
        abort();
        }

    if (stackptr>0)
        return(stack[stackptr-1]);
    return(0.0);
    }
Exemplo n.º 15
0
int main(int argc, char **argv)
{
  SDDS_DATASET SDDS_dataset;
  long i, j, k, i_arg, rows, retval, description;
  SCANNED_ARG *s_arg;
  char **input;
  char **column_name, **parameter_name, **array_name;
  char **parameterFormat, **columnFormat, **arrayFormat;
  long column_names, parameter_names, array_names, page_number, *type, inputs;
  char *delimiter;
  void **data;
  char *buffer;
  long filenames, print_rows, print_pages, noQuotes, pipe, ignoreFormats;
  static char printBuffer[SDDS_MAXLINE*16];
  long n_rows, n_rows_bare, n_rows_total, n_pages, n_pages_bare;

  SDDS_RegisterProgramName(argv[0]);
  argc = scanargs(&s_arg, argc, argv);
  if (argc<3) 
    bomb(NULL, USAGE);

  type = NULL;
  data = NULL;
  buffer = tmalloc(sizeof(char)*16);  /* large enough for any data type */
  delimiter = NULL;
  input = parameter_name = column_name = array_name = NULL;
  parameterFormat = columnFormat = arrayFormat = NULL;
  inputs = parameter_names = column_names = array_names = 0;
  page_number = filenames = ignoreFormats = 0;
  n_rows = n_rows_bare = n_rows_total = n_pages = n_pages_bare = 0;
  print_rows = print_pages = noQuotes = pipe = description = 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_COLUMNS:
        if (s_arg[i_arg].n_items<2)
          SDDS_Bomb("invalid -columns syntax");
        if (column_names)
          SDDS_Bomb("invalid syntax: specify -columns once only");
        column_name = tmalloc(sizeof(*column_name)*(s_arg[i_arg].n_items-1));
        for (i=1; i<s_arg[i_arg].n_items; i++)
          column_name[i-1] = s_arg[i_arg].list[i];
        column_names = s_arg[i_arg].n_items-1;
        break;
      case SET_PARAMETERS:
        if (s_arg[i_arg].n_items<2)
          SDDS_Bomb("invalid -parameters syntax");
        if (parameter_names)
          SDDS_Bomb("invalid syntax: specify -parameters once only");
        parameter_name = tmalloc(sizeof(*parameter_name)*(s_arg[i_arg].n_items-1));
        for (i=1; i<s_arg[i_arg].n_items; i++)
          parameter_name[i-1] = s_arg[i_arg].list[i];
        parameter_names = s_arg[i_arg].n_items-1;
        break;
      case SET_ARRAYS:
        if (s_arg[i_arg].n_items<2)
          SDDS_Bomb("invalid -arrays syntax");
        if (array_names)
          SDDS_Bomb("invalid syntax: specify -arrays once only");
        array_name = tmalloc(sizeof(*array_name)*(s_arg[i_arg].n_items-1));
        for (i=1; i<s_arg[i_arg].n_items; i++)
          array_name[i-1] = s_arg[i_arg].list[i];
        array_names = s_arg[i_arg].n_items-1;
        break;
      case SET_TABLE:
      case SET_PAGE:
        if (s_arg[i_arg].n_items<2 || s_arg[i_arg].n_items>2)
          SDDS_Bomb("invalid -page syntax");
        if (page_number!=0)
          SDDS_Bomb("invalid syntax: specify -page once only");
        if (sscanf(s_arg[i_arg].list[1], "%ld", &page_number)!=1 || page_number<=0)
          SDDS_Bomb("invalid -page syntax or value");
        break;
      case SET_DELIMITER:
        if (s_arg[i_arg].n_items<2)
          SDDS_Bomb("invalid -delimiter syntax");
        delimiter = s_arg[i_arg].list[1];
        break;
      case SET_FILENAMES:
        filenames = 1;
        break;
      case SET_ROWS:
        if (s_arg[i_arg].n_items>3)
          SDDS_Bomb("invalid -rows syntax");
        else {
          char *rowsOutputMode[2] = {"bare", "total"};
          for (i=1; i<s_arg[i_arg].n_items; i++) {
            switch (match_string(s_arg[i_arg].list[i], rowsOutputMode, 2, 0)) {
            case 0:
              n_rows_bare = 1;
              break;
            case 1:
              n_rows_total = 1;
              break;
            default:
              SDDS_Bomb("unknown output mode for -rows option");
              break;
            }
          }
        }
        print_rows = 1;
        break;
      case SET_SHOW_PAGES:
        if (s_arg[i_arg].n_items>2)
          SDDS_Bomb("invalid -pages syntax");
        else {
          char *pagesOutputMode[1] = {"bare"};
          for (i=1; i<s_arg[i_arg].n_items; i++) {
            if (strcmp(s_arg[i_arg].list[i],"")!=0) {
              if (match_string(s_arg[i_arg].list[i], pagesOutputMode, 1, 0)==0) 
                n_pages_bare = 1;
              else 
                SDDS_Bomb("unknown output mode for -npages option");
            }
            else 
              SDDS_Bomb("unknown output mode for -npages option");
          }
        }
        print_pages = 1;
        break;
      case SET_NOQUOTES:
        noQuotes = 1;
        break;
      case SET_PIPE:
        pipe = 1;
        break;
      case SET_IGNOREFORMATS:
        ignoreFormats = 1;
        break;
      case SET_DESCRIPTION:
        description = 1;
        break;
      default:
        fprintf(stderr, "error: unknown switch: %s\n", s_arg[i_arg].list[0]);
        exit(1);
        break;
      }
    }
    else {
      input = trealloc(input, sizeof(*input)*(inputs+1));
      input[inputs++] = s_arg[i_arg].list[0];
    }
  }

  if (!inputs) {
    if (!pipe)
      SDDS_Bomb("too few filenames");
    inputs = 1;
    input = trealloc(input, sizeof(*input)*(inputs+1));
    input[0] = NULL;
  }

  if (!column_names && !parameter_names && !array_names && !print_rows && !description && !print_pages)
    SDDS_Bomb("you must specify one of -columns, -parameters, -arrays, -rows or -description");
  if (!delimiter) {
    if (column_names || array_names)
      cp_str(&delimiter, " ");
    else
      cp_str(&delimiter, "\n");
  }

  SDDS_SetTerminateMode(TERMINATE_DONT_FREE_TABLE_STRINGS+
                        TERMINATE_DONT_FREE_ARRAY_STRINGS);
  for (k=0; k<inputs; k++) {
    if (!SDDS_InitializeInput(&SDDS_dataset, input[k])) {
      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
      exit(1);
    }
    n_pages = 0;
    
    if (column_names) {
      if (k==0) {
        type = tmalloc(sizeof(*type)*column_names);
        data = tmalloc(sizeof(*data)*column_names);
        columnFormat = tmalloc(sizeof(*columnFormat)*column_names);
      }
      for (i=0; i<column_names; i++) {
        if ((j=SDDS_GetColumnIndex(&SDDS_dataset, column_name[i]))<0) {
          fprintf(stderr, "error: column %s does not exist\n", column_name[i]);
          exit(1);
        }
        if ((type[i]=SDDS_GetColumnType(&SDDS_dataset, j))<=0 || 
            !SDDS_GetColumnInformation(&SDDS_dataset, "format_string", columnFormat+i, SDDS_GET_BY_INDEX, j)) {
          SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
          exit(1);
        }
      }
    }
    else if (array_names) {
      if (k==0) {
        type = tmalloc(sizeof(*type)*array_names);
        data = tmalloc(sizeof(*data)*array_names);
        arrayFormat = tmalloc(sizeof(*arrayFormat)*array_names);
      }

      for (i=0; i<array_names; i++) {
        if ((j=SDDS_GetArrayIndex(&SDDS_dataset, array_name[i]))<0) {
          fprintf(stderr, "error: array %s does not exist\n", array_name[i]);
          exit(1);
        }
        if ((type[i]=SDDS_GetArrayType(&SDDS_dataset, j))<=0 ||
            !SDDS_GetArrayInformation(&SDDS_dataset, "format_string", arrayFormat+i, SDDS_BY_INDEX, j)) {
          SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
          exit(1);
        }
      }
    }
    else if (parameter_names) {
      if (k==0) {
        type = tmalloc(sizeof(*type)*parameter_names);
        parameterFormat = tmalloc(sizeof(*parameterFormat)*parameter_names);
      }
      for (i=0; i<parameter_names; i++) {
        if ((j=SDDS_GetParameterIndex(&SDDS_dataset, parameter_name[i]))<0) {
          fprintf(stderr, "error: parameter %s does not exist\n", parameter_name[i]);
          exit(1);
        }
        if ((type[i]=SDDS_GetParameterType(&SDDS_dataset, j))<=0 ||
            !SDDS_GetParameterInformation(&SDDS_dataset, "format_string", parameterFormat+i, SDDS_BY_INDEX, j)) {
          SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
          exit(1);
        }
      }
    }
    
    if (description) {
      if (!SDDS_SprintTypedValue2(SDDS_dataset.layout.description, NULL, 
                                  printBuffer,noQuotes?SDDS_PRINT_NOQUOTES:0)) {
        
        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
        exit(1);
      }
      
      fputs(printBuffer, stdout);
      fprintf(stdout, delimiter);

      if (!SDDS_SprintTypedValue2(SDDS_dataset.layout.contents, NULL, 
                                  printBuffer,noQuotes?SDDS_PRINT_NOQUOTES:0)) {
        SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
        exit(1);
      }
      fputs(printBuffer, stdout);
      fprintf(stdout, delimiter);

      if (!strchr(delimiter, '\n'))
        fputc('\n', stdout);
    }

    retval = -1;
    while (retval!=page_number && (retval=SDDS_ReadPage(&SDDS_dataset))>0) {
      if (page_number && retval!=page_number)
        continue;
      
      if (print_rows) {
        if (n_rows_total && !(page_number))
          n_rows += SDDS_CountRowsOfInterest(&SDDS_dataset);
        else {
          if (n_rows_bare)
            fprintf(stdout, "%" PRId32 "\n", SDDS_CountRowsOfInterest(&SDDS_dataset));
          else
            fprintf(stdout, "%" PRId32 " rows\n", SDDS_CountRowsOfInterest(&SDDS_dataset));
        }
      }

      if (column_names) {
        if ((rows=SDDS_CountRowsOfInterest(&SDDS_dataset))<0) {
          SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
          exit(1);
        }
        if (rows) {
          if (filenames) {
            fprintf(stdout, "%s%s", input[k], delimiter);
            if (!strchr(delimiter, '\n'))
              fputc('\n', stdout);
          }
          for (i=0; i<column_names; i++)
            if (!(data[i]=SDDS_GetInternalColumn(&SDDS_dataset, column_name[i]))) {
              SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
              exit(1);
            }
          for (j=0; j<rows; j++) {
            for (i=0; i<column_names; i++) {
              if (!SDDS_SprintTypedValue(data[i], j, type[i], 
                                         ignoreFormats?NULL:columnFormat[i], 
                                         printBuffer, 
                                         noQuotes?SDDS_PRINT_NOQUOTES:0)) {
                SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
                exit(1);
              }
              fputs(printBuffer, stdout);
              if (i!=column_names-1)
                /* must use print here: */
                fprintf(stdout, delimiter);
            }
            fputc('\n', stdout);
          }
        }
      }
      else if (array_names) {
        SDDS_ARRAY *array;
        if (filenames) {
          fprintf(stdout, "%s%s", input[k], delimiter);
          if (!strchr(delimiter, '\n'))
            fputc('\n', stdout);
        }
        for (i=0; i<array_names; i++) {
          if (!(array=SDDS_GetArray(&SDDS_dataset, array_name[i], NULL))) {
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
            exit(1);
          }
          for (j=0; j<array->elements; j++) {
            if (!SDDS_SprintTypedValue(array->data, j, type[i], 
                                       ignoreFormats?NULL:arrayFormat[i], 
                                       printBuffer,
                                       noQuotes?SDDS_PRINT_NOQUOTES:0)) {
              SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
              exit(1);
            }
            fputs(printBuffer, stdout);
            fprintf(stdout, delimiter);
          }
        }
        if (!strchr(delimiter, '\n'))
          fputc('\n', stdout);
      }
      else {
        if (filenames)
          fprintf(stdout, "%s%s", input[k], delimiter);
        for (i=0; i<parameter_names; i++) {
          if (!SDDS_GetParameter(&SDDS_dataset, parameter_name[i], buffer)) {
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
            exit(1);
          }
          if (!SDDS_SprintTypedValue(buffer, 0, type[i], 
                                     ignoreFormats?NULL:parameterFormat[i], 
                                     printBuffer,
                                     noQuotes?SDDS_PRINT_NOQUOTES:0)) {
            SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
            exit(1);
          }
          fputs(printBuffer, stdout);
          /* must use print here: */
          fprintf(stdout, delimiter);
        }
        if (!strchr(delimiter, '\n'))
          fputc('\n', stdout);
      }
      n_pages++;
    }
    if (retval==0) {
      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
      exit(1);
    }
    else {
      if (print_rows && (n_rows_total || (retval==-1 && n_pages==0)) && !(page_number)) {
        if (n_rows_bare)
          fprintf(stdout, "%ld\n", n_rows);
        else
          fprintf(stdout, "%ld rows\n", n_rows);
      }
      if (print_pages) {
        if (n_pages_bare)
          fprintf(stdout, "%ld\n", n_pages);
        else
          fprintf(stdout, "%ld pages\n", n_pages);
      }
    }
    if (!SDDS_Terminate(&SDDS_dataset)) {
      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors);
      exit(1);
    }
  }
  return(0);
}
Exemplo n.º 16
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);
}
Exemplo n.º 17
0
void check_dirs(){

	struct stat st = {0};
	
	char *home_dir = getenv("HOME");
	char *local_dir = "/.local";
	char *share_dir = "/share";
	char *crunchball_dir = "/crunchball";
	char *conf_file = "/crunchball.cfg";
	char tmp_path[500] = {0};
	
	cp_str(tmp_path, home_dir);	
	cat_to_str(tmp_path, local_dir);
	if (stat(tmp_path, &st) == -1) {
#ifdef _WIN32
		mkdir(tmp_path);
#else
		mkdir(tmp_path, 0755);
#endif
	}
	
	cat_to_str(tmp_path, share_dir);
	if (stat(tmp_path, &st) == -1) {
#ifdef _WIN32
		mkdir(tmp_path);
#else
		mkdir(tmp_path, 0755);
#endif
	}
	
	cat_to_str(tmp_path, crunchball_dir);
	if (stat(tmp_path, &st) == -1) {
#ifdef _WIN32
		mkdir(tmp_path);
#else
		mkdir(tmp_path, 0755);
#endif
	}

	cat_to_str(tmp_path, conf_file);
	
	if (stat(tmp_path, &st) == -1) {
		
		long int video_mode = 2;
		long int audio_level = 5;
		long int fullscreen = 0;
		long int high_score = 0;

		cfg_opt_t opts[] = {
			CFG_SIMPLE_INT("video_mode", &video_mode),
			CFG_SIMPLE_INT("audio_level", &audio_level),
			CFG_SIMPLE_INT("fullscreen", &fullscreen),
			CFG_SIMPLE_INT("high_score", &high_score),
			CFG_END()
		};
		cfg_t *cfg;

		cfg = cfg_init(opts, 0);


		FILE *fp = fopen(tmp_path, "w");
		cfg_print(cfg, fp);

		fclose(fp);
		
		cfg_free(cfg);
	}
}
Exemplo n.º 18
0
long get_mc_table(MC_TABLE *table, char *file, long flags)
{
    FILE *fpi;
    long i, j, i_col;
    char *ptr;

    if (!(fpi = fopen_e(file, "r", 1)))
        return(0);

    if (!fgets_mc_skip(buffer, 1024, fpi, '!'))
        bomb("unable to read first line of table file", NULL);
    if (!(get_long(&table->n_cols, buffer)))
        bomb("unable to scan number of columns in table file", NULL);
    if (table->n_cols<=0)
        bomb("number of columns is invalid in table file", NULL);
    table->n_lines_per_row = 1;
    table->n_auxiliaries = 0;
    if (get_long(&table->n_lines_per_row, buffer)) {
        if (table->n_lines_per_row<=0)
            bomb("number of lines per row is invalid in table file", NULL);
        if (get_long(&table->n_auxiliaries, buffer) &&
                table->n_auxiliaries<0)
            bomb("number of auxiliary quantities is invalid in table file", NULL);
        }

#if DEBUG
    printf("file %s\nn_cols = %ld  n_lines_per_row = %ld  n_auxiliaries = %ld\n",
        file, table->n_cols, table->n_lines_per_row, table->n_auxiliaries);
#endif

    table->name = tmalloc(sizeof(char*)*table->n_cols);
    table->unit = tmalloc(sizeof(char*)*table->n_cols);
    table->description
                = tmalloc(sizeof(char*)*table->n_cols);
    table->format
                = tmalloc(sizeof(char*)*table->n_cols);
    
    for (i=0; i<table->n_cols; i++) {
        if (!fgets_mc_skip(buffer, 1024, fpi, '!'))
            bomb("missing quantity name and units line in table file", NULL);
        get_name_unit_descrip_format(table->name+i, table->unit+i,
                table->description+i, table->format+i, buffer);
        if (table->format[i] && !strchr(table->format[i], '%'))
            table->format[i] = NULL;
        }

#if DEBUG
    for (i=0; i<table->n_cols; i++)
        printf("column %ld:  %s in %s--%s in format %s\n", 
                i, table->name[i], table->unit[i], table->description[i], 
                (table->format[i]?table->format[i]:"{null}") );
#endif

    if (!fgets_mc_skip(buffer, 1024, fpi, '!'))
        bomb("missing title string in table file", NULL);
    cp_str(&table->title, buffer);

    if (!fgets_mc_skip(buffer, 1024, fpi, '!'))
        bomb("missing label string in table file", NULL);
    cp_str(&table->label, buffer);

#if DEBUG
    printf("title: %s\nlabel: %s\n", table->title, table->label);
#endif

    if (table->n_auxiliaries) {
#if DEBUG
        printf("%ld auxuliary quantities are expected\n", table->n_auxiliaries);
#endif
        /* get auxiliary quantity names\units... */
        table->aux_name        = tmalloc(sizeof(char*)*table->n_auxiliaries);
        table->aux_unit        = tmalloc(sizeof(char*)*table->n_auxiliaries);
        table->aux_description = tmalloc(sizeof(char*)*table->n_auxiliaries);
        table->aux_value       = tmalloc(sizeof(*(table->aux_value))*table->n_auxiliaries);
        for (i=0; i<table->n_auxiliaries; i++) {
            if (!fgets_mc_skip(buffer, 1024, fpi, '!'))
                bomb("missing quantity name and units line in table file", NULL);
            get_name_unit_descrip_format(table->aux_name+i, table->aux_unit+i,
                    table->aux_description+i, &ptr, buffer);
            if ((!ptr || 1!=sscanf(ptr, "%lf", table->aux_value+i)) && flags&GMCT_WARN_MISSING_AUXVAL)
                printf("warning: missing value for auxiliary quantity %s---zero assumed\n", table->aux_name[i]);
            }
        }
        
#if DEBUG
    for (i=0; i<table->n_auxiliaries; i++) {
        printf("auxiliary %ld:  %s = %le %s---%s\n", 
            i, table->aux_name[i], table->aux_value[i], table->aux_unit[i],
            table->aux_description[i]);
        }
#endif

    if (!fgets_mc_skip(buffer, 1024, fpi, '!'))
        bomb("missing number of data rows in table file", NULL);
    if (!get_long(&table->n_rows, buffer) || table->n_rows<0)
        bomb("invalid number of data rows specified in table file", NULL);
    if (table->n_rows==0)
        return(1);    

#if DEBUG
    printf("n_rows = %ld\n", table->n_rows);
#endif
    
    table->value = (double**)zarray_2d(sizeof(double), table->n_cols, table->n_rows);
    table->row_label = (char**)tmalloc(sizeof(char*)*table->n_rows);

    for (i=0; i<table->n_rows; i++) {
        i_col = 0;
        table->row_label[i] = NULL;
        for (j=0; j<table->n_lines_per_row && i_col<table->n_cols; j++) {
            if (!fgets_mc_skip(buffer, 1024, fpi, '!'))
                break;
            strcpy(buffer1, buffer);
#if DEBUG
            printf("row %ld, line %ld:\n%s\n", i, j, buffer);
#endif
            while (i_col<table->n_cols && get_double(table->value[i_col]+i, buffer))
                i_col++;
            }

        if (!is_blank(buffer)) {
            cp_str(table->row_label+i, buffer);
            while (isspace(*table->row_label[i]))
                table->row_label[i]++;
            }
        else
            cp_str(table->row_label+i, "");

        if (i_col==0) {
            if (flags&GMCT_WARN_WRONG_COUNT)
                printf("warning: fewer data rows than expected in file %s\n", file);
            break;
            }
        else if (i_col!=table->n_cols) {
            if (flags&GMCT_WARN_INCOMPLETE_ROW) {
                printf("warning: incomplete data row in file %s\n", file);
                printf("line in question is:\n%s\n", buffer1);
                printf("skipping to next line\n");
                }
            i--;
            continue;
            }
#if DEBUG
        printf("%ld: ", i);
        for (i_col=0; i_col<table->n_cols; i_col++)
            printf("%.4le  ", table->value[i_col][i]);
        putchar('\n');
#endif
        }
    if (i==table->n_rows && fgets_mc_skip(buffer, 1024, fpi, '!') && flags&GMCT_WARN_EXTRA_ROWS)
        printf("warning: file %s contains extra rows, which are ignored\n",
                file);
    table->n_rows = i;
    return(1);
    }
Exemplo n.º 19
0
void setup_chromaticity_correction(NAMELIST_TEXT *nltext, RUN *run, LINE_LIST *beamline, CHROM_CORRECTION *chrom)
{
    VMATRIX *M;
    ELEMENT_LIST *eptr, *elast;
#include "chrom.h"
    unsigned long unstable;
    
    log_entry("setup_chromaticity_correction");

    cp_str(&sextupoles, "sf sd");

    /* process namelist input */
    set_namelist_processing_flags(STICKY_NAMELIST_DEFAULTS);
    set_print_namelist_flags(0);
    if (processNamelist(&chromaticity, nltext)==NAMELIST_ERROR)
      bombElegant(NULL, NULL);
    str_toupper(sextupoles);
    if (echoNamelists) print_namelist(stdout, &chromaticity);

    if (run->default_order<2)
        bombElegant("default order must be >= 2 for chromaticity correction", NULL);

    if (chrom->name)
        tfree(chrom->name);
    chrom->name = tmalloc(sizeof(*chrom->name)*(chrom->n_families=1));
    while ((chrom->name[chrom->n_families-1]=get_token(sextupoles)))
        chrom->name = trealloc(chrom->name, sizeof(*chrom->name)*(chrom->n_families+=1));
    if ((--chrom->n_families)<1)
        bombElegant("too few sextupoles given for chromaticity correction", NULL);
    chrom->chromx = dnux_dp;
    chrom->chromy = dnuy_dp;
    chrom->n_iterations = n_iterations;
    chrom->correction_fraction = correction_fraction;
    alter_defined_values = change_defined_values;
    chrom->strengthLimit = strength_limit;
    chrom->use_perturbed_matrix = use_perturbed_matrix;
    chrom->sextupole_tweek = sextupole_tweek;
    chrom->tolerance = tolerance;
    verbosityLevel = verbosity;
    chrom->exit_on_failure = exit_on_failure;
    
    if (!use_perturbed_matrix) {
      if (!beamline->twiss0 || !beamline->matrix) {
        double beta_x, alpha_x, eta_x, etap_x;
        double beta_y, alpha_y, eta_y, etap_y;

        fprintf(stdout, "Computing periodic Twiss parameters.\n");
        fflush(stdout);

        if (!beamline->twiss0)
          beamline->twiss0 = tmalloc(sizeof(*beamline->twiss0));

        eptr = beamline->elem_twiss = &(beamline->elem);
        elast = eptr;
        while (eptr) {
          if (eptr->type==T_RECIRC)
            beamline->elem_twiss = beamline->elem_recirc = eptr;
          elast = eptr;
          eptr = eptr->succ;
        }
        if (beamline->links) {
          /* rebaseline_element_links(beamline->links, run, beamline); */
          if (assert_element_links(beamline->links, run, beamline, STATIC_LINK+DYNAMIC_LINK)) {
            beamline->flags &= ~BEAMLINE_CONCAT_CURRENT;
            beamline->flags &= ~BEAMLINE_TWISS_CURRENT;
            beamline->flags &= ~BEAMLINE_RADINT_CURRENT;
          }
        }
        
        M = beamline->matrix = compute_periodic_twiss(&beta_x, &alpha_x, &eta_x, &etap_x, beamline->tune,
                                                      &beta_y, &alpha_y, &eta_y, &etap_y, beamline->tune+1, 
                                                      beamline->elem_twiss, NULL, run, 
                                                      &unstable, NULL, NULL);
        beamline->twiss0->betax  = beta_x;
        beamline->twiss0->alphax = alpha_x;
        beamline->twiss0->phix   = 0;
        beamline->twiss0->etax   = eta_x;
        beamline->twiss0->etapx  = etap_x;
        beamline->twiss0->betay  = beta_y;
        beamline->twiss0->alphay = alpha_y;
        beamline->twiss0->phiy   = 0;
        beamline->twiss0->etay   = eta_y;
        beamline->twiss0->etapy  = etap_y;
        
        propagate_twiss_parameters(beamline->twiss0, beamline->tune, beamline->waists,
                                   NULL, beamline->elem_twiss, run, NULL,
				   beamline->couplingFactor);
      }

      if (!(M=beamline->matrix) || !M->C || !M->R || !M->T)
        bombElegant("something wrong with transfer map for beamline (setup_chromaticity_correction)", NULL);

      computeChromCorrectionMatrix(run, beamline, chrom);
    }
    
#if USE_MPI
    if (!writePermitted)
       strength_log = NULL;
#endif
    if (strength_log) {
        strength_log = compose_filename(strength_log, run->rootname);
        fp_sl = fopen_e(strength_log, "w", 0);
        fprintf(fp_sl, "SDDS1\n&column name=Step, type=long, description=\"Simulation step\" &end\n");
        fprintf(fp_sl, "&column name=K2, type=double, units=\"1/m$a2$n\" &end\n");
        fprintf(fp_sl, "&column name=SextupoleName, type=string  &end\n");
        fprintf(fp_sl, "&data mode=ascii, no_row_counts=1 &end\n");
        fflush(fp_sl);
        }

    log_exit("setup_chromaticity_correction");
    
}
Exemplo n.º 20
0
void add_error_element(ERRORVAL *errcon, NAMELIST_TEXT *nltext, LINE_LIST *beamline)
{
    long n_items, n_added, i_start, firstIndexInGroup;
    ELEMENT_LIST *context;
    double sMin = -DBL_MAX, sMax = DBL_MAX;
    
    log_entry("add_error_element");

    if ((n_items = errcon->n_items)==0) {
        if (errcon->new_data_read)
            bombElegant("improper sequencing of error specifications and tracking", NULL);
        errcon->new_data_read = 1;
        }

    /* process namelist text */
    set_namelist_processing_flags(STICKY_NAMELIST_DEFAULTS);
    set_print_namelist_flags(0);
    if (processNamelist(&error, nltext)==NAMELIST_ERROR)
      bombElegant(NULL, NULL);
    if (name==NULL) {
      if (!element_type)
        bombElegant("element name missing in error namelist", NULL);
      SDDS_CopyString(&name, "*");
    }
    if (echoNamelists) print_namelist(stdout, &error);

    /* check for valid input and copy to errcon arrays */
    if (item==NULL)
        bombElegant("item name missing in error namelist", NULL);
    if (match_string(type, known_error_type, N_ERROR_TYPES, 0)<0)
        bombElegant("unknown error type specified", NULL);
    if (bind_number<0)
        bombElegant("bind_number < 0", NULL);
    if (!additive && fractional)
        bombElegant("fractional errors must be additive", NULL);

    context = NULL;
    n_added = 0;
    i_start = n_items;

    context = NULL;
    if (after && strlen(after)) {
      if (!(context=find_element(after, &context, &(beamline->elem)))) {
        fprintf(stdout, "Element %s not found in beamline.\n", after);
        exitElegant(1);
      }
      sMin = context->end_pos;
      if (find_element(after, &context, &(beamline->elem))) {
        fprintf(stdout, "Element %s found in beamline more than once.\n", after);
        exitElegant(1);
      }
      fprintf(stdout, "%s found at s = %le m\n", after, sMin);
      fflush(stdout);
    }
    context = NULL;
    if (before && strlen(before)) {
      if (!(context=find_element(before, &context, &(beamline->elem)))) {
        fprintf(stdout, "Element %s not found in beamline.\n", before);
        exitElegant(1);
      }
      sMax = context->end_pos;
      if (find_element(before, &context, &(beamline->elem))) {
        fprintf(stdout, "Element %s found in beamline more than once.\n", after);
        exitElegant(1);
      }
      fprintf(stdout, "%s found at s = %le m\n", before, sMax);
      fflush(stdout);
    }
    if (after && before && sMin>sMax) {
      fprintf(stdout, "Element %s is not upstream of %s!\n",
              before, after);
      exitElegant(1);
    }
    if (element_type && has_wildcards(element_type) && strchr(element_type, '-'))
      element_type = expand_ranges(element_type);
    if (has_wildcards(name)) {
        if (strchr(name, '-'))
            name = expand_ranges(name);
        str_toupper(name);
        firstIndexInGroup = -1;
        while ((context=wfind_element(name, &context, &(beamline->elem)))) {
            if (element_type && 
                !wild_match(entity_name[context->type], element_type))
              continue;
            if (exclude &&
                wild_match(context->name, exclude))
              continue;
            if (i_start!=n_items && duplicate_name(errcon->name+i_start, n_items-i_start, context->name))
                continue;
            if ((sMin>=0 && context->end_pos<sMin) ||
                (sMax>=0 && context->end_pos>sMax)) 
              continue;
            errcon->name              = trealloc(errcon->name, sizeof(*errcon->name)*(n_items+1));
            errcon->item              = trealloc(errcon->item, sizeof(*errcon->item)*(n_items+1));
            errcon->quan_name         = trealloc(errcon->quan_name, sizeof(*errcon->quan_name)*(n_items+1));
            errcon->quan_final_index  
              = trealloc(errcon->quan_final_index, sizeof(*errcon->quan_final_index)*(n_items+1));
            errcon->quan_unit         = trealloc(errcon->quan_unit, sizeof(*errcon->quan_unit)*(n_items+1));
            errcon->error_level       = trealloc(errcon->error_level, sizeof(*errcon->error_level)*(n_items+1));
            errcon->error_cutoff      = trealloc(errcon->error_cutoff, sizeof(*errcon->error_cutoff)*(n_items+1));
            errcon->error_type        = trealloc(errcon->error_type, sizeof(*errcon->error_type)*(n_items+1));
            errcon->elem_type         = trealloc(errcon->elem_type, sizeof(*errcon->elem_type)*(n_items+1));
            errcon->error_value       = trealloc(errcon->error_value, sizeof(*errcon->error_value)*(n_items+1));
            errcon->unperturbed_value = trealloc(errcon->unperturbed_value, sizeof(*errcon->unperturbed_value)*(n_items+1));
            errcon->param_number      = trealloc(errcon->param_number, sizeof(*errcon->param_number)*(n_items+1));
            errcon->bind_number       = trealloc(errcon->bind_number, sizeof(*errcon->bind_number)*(n_items+1));
            errcon->flags             = trealloc(errcon->flags, sizeof(*errcon->flags)*(n_items+1));
            errcon->sMin             = trealloc(errcon->sMin, sizeof(*errcon->sMin)*(n_items+1));
            errcon->sMax             = trealloc(errcon->sMax, sizeof(*errcon->sMax)*(n_items+1));
            errcon->boundTo          = trealloc(errcon->boundTo, sizeof(*errcon->boundTo)*(n_items+1));

            cp_str(errcon->item+n_items, str_toupper(item));
            cp_str(errcon->name+n_items, context->name);
            errcon->error_level[n_items] = amplitude*error_factor;
            errcon->error_cutoff[n_items] = cutoff;
            errcon->error_type[n_items] = match_string(type, known_error_type, N_ERROR_TYPES, 0);
            errcon->quan_name[n_items] = tmalloc(sizeof(char*)*(strlen(context->name)+strlen(item)+4));
            errcon->quan_final_index[n_items] = -1;
            sprintf(errcon->quan_name[n_items], "d%s.%s", context->name, item);
            errcon->flags[n_items]  = (fractional?FRACTIONAL_ERRORS:0);
            errcon->flags[n_items] += (bind==0?0:(bind==-1?ANTIBIND_ERRORS:BIND_ERRORS));
            errcon->flags[n_items] += (post_correction?POST_CORRECTION:PRE_CORRECTION);
            errcon->flags[n_items] += (additive?0:NONADDITIVE_ERRORS);
            errcon->bind_number[n_items] = bind_number;
            /* boundTo must be -1 when there is no cross-name binding or when this element is the
             * first of a series 
             */
            errcon->boundTo[n_items] = bind_across_names?firstIndexInGroup:-1;
/*
            if (errcon->boundTo[n_items]!=-1)
              fprintf(stdout, "%s bound to %s\n", 
                      errcon->name[n_items], errcon->name[errcon->boundTo[n_items]]);
*/
            errcon->sMin[n_items] = sMin;
            errcon->sMax[n_items] = sMax;
            errcon->elem_type[n_items] = context->type;

            if ((errcon->param_number[n_items] = confirm_parameter(item, context->type))<0) {
                fprintf(stdout, "error: cannot vary %s--no such parameter for %s (wildcard name: %s)\n",item, context->name, name);
                fflush(stdout);
                exitElegant(1);
                }
            cp_str(&errcon->quan_unit[n_items], 
                errcon->flags[n_items]&FRACTIONAL_ERRORS?"fr":
                entity_description[errcon->elem_type[n_items]].parameter[errcon->param_number[n_items]].unit
                );
            errcon->unperturbed_value[n_items] 
                = parameter_value(errcon->name[n_items], errcon->elem_type[n_items], errcon->param_number[n_items],
                            beamline);
            if (errcon->unperturbed_value[n_items]==0 && errcon->flags[n_items]&FRACTIONAL_ERRORS)
                fprintf(stdout, "***\7\7\7 warning: you've specified fractional errors for %s.%s, but the unperturbed value is zero.\nThis may be an error.\n", 
                    errcon->name[n_items], errcon->item[n_items]);
                fflush(stdout);
            if (duplicate_name(errcon->quan_name, n_items, errcon->quan_name[n_items]))
                fprintf(stdout, "***\7\7\7 warning: you've specified errors for %s.%s more than once!\n",
                    errcon->name[n_items], errcon->item[n_items]);
                fflush(stdout);
            errcon->n_items = ++n_items;
            n_added++;
            if (firstIndexInGroup==-1)
              firstIndexInGroup = n_items-1;
            }
        }
    else {
        str_toupper(name);
        if (!(context=find_element(name, &context, &(beamline->elem)))) {
            fprintf(stdout, "error: cannot add errors to element %s--not in beamline\n", name);
            fflush(stdout);
            exitElegant(1);
            }
        errcon->name              = trealloc(errcon->name, sizeof(*errcon->name)*(n_items+1));
        errcon->item              = trealloc(errcon->item, sizeof(*errcon->item)*(n_items+1));
        errcon->quan_name         = trealloc(errcon->quan_name, sizeof(*errcon->quan_name)*(n_items+1));
        errcon->quan_final_index  
          = trealloc(errcon->quan_final_index, sizeof(*errcon->quan_final_index)*(n_items+1));
        errcon->quan_unit         = trealloc(errcon->quan_unit, sizeof(*errcon->quan_unit)*(n_items+1));
        errcon->error_level       = trealloc(errcon->error_level, sizeof(*errcon->error_level)*(n_items+1));
        errcon->error_cutoff      = trealloc(errcon->error_cutoff, sizeof(*errcon->error_cutoff)*(n_items+1));
        errcon->error_type        = trealloc(errcon->error_type, sizeof(*errcon->error_type)*(n_items+1));
        errcon->elem_type         = trealloc(errcon->elem_type, sizeof(*errcon->elem_type)*(n_items+1));
        errcon->error_value       = trealloc(errcon->error_value, sizeof(*errcon->error_value)*(n_items+1));
        errcon->unperturbed_value = trealloc(errcon->unperturbed_value, sizeof(*errcon->unperturbed_value)*(n_items+1));
        errcon->param_number      = trealloc(errcon->param_number, sizeof(*errcon->param_number)*(n_items+1));
        errcon->bind_number       = trealloc(errcon->bind_number, sizeof(*errcon->bind_number)*(n_items+1));
        errcon->flags             = trealloc(errcon->flags, sizeof(*errcon->flags)*(n_items+1));
        errcon->sMin             = trealloc(errcon->sMin, sizeof(*errcon->sMin)*(n_items+1));
        errcon->sMax             = trealloc(errcon->sMax, sizeof(*errcon->sMax)*(n_items+1));
        errcon->boundTo          = trealloc(errcon->boundTo, sizeof(*errcon->boundTo)*(n_items+1));

        cp_str(errcon->item+n_items, str_toupper(item));
        cp_str(errcon->name+n_items, context->name);
        errcon->error_level[n_items] = amplitude;
        errcon->error_cutoff[n_items] = cutoff;
        errcon->error_type[n_items] = match_string(type, known_error_type, N_ERROR_TYPES, 0);
        errcon->quan_name[n_items] = tmalloc(sizeof(char*)*(strlen(context->name)+strlen(item)+4));
        sprintf(errcon->quan_name[n_items], "d%s.%s", context->name, item);
        errcon->flags[n_items]  = (fractional?FRACTIONAL_ERRORS:0);
        errcon->flags[n_items] += (bind==0?0:(bind==-1?ANTIBIND_ERRORS:BIND_ERRORS));
        errcon->flags[n_items] += (post_correction?POST_CORRECTION:PRE_CORRECTION);
        errcon->flags[n_items] += (additive?0:NONADDITIVE_ERRORS);
        errcon->bind_number[n_items] = bind_number;
        errcon->sMin[n_items] = sMin;
        errcon->sMax[n_items] = sMax;
        errcon->boundTo[n_items] = -1;  /* not used when there are no wildcards */

        errcon->elem_type[n_items] = context->type;
        if ((errcon->param_number[n_items] = confirm_parameter(item, context->type))<0) {
            fprintf(stdout, "error: cannot vary %s--no such parameter for %s\n",item, name);
            fflush(stdout);
            exitElegant(1);
            }
        cp_str(&errcon->quan_unit[n_items], 
            errcon->flags[n_items]&FRACTIONAL_ERRORS?"fr":
            entity_description[errcon->elem_type[n_items]].parameter[errcon->param_number[n_items]].unit
            );
        errcon->unperturbed_value[n_items] 
            = parameter_value(errcon->name[n_items], errcon->elem_type[n_items], errcon->param_number[n_items],
                        beamline);
        if (errcon->unperturbed_value[n_items]==0 && errcon->flags[n_items]&FRACTIONAL_ERRORS)
            fprintf(stdout, "***\7\7\7 warning: you've specified fractional errors for %s.%s, but the unperturbed value is zero.\nThis may be an error.\n", 
                errcon->name[n_items], errcon->item[n_items]);
            fflush(stdout);

        if (duplicate_name(errcon->quan_name, n_items, errcon->quan_name[n_items]))
            fprintf(stdout, "***\7\7\7 warning: you've specified errors for %s.%s more than once!\n",
                errcon->name[n_items], errcon->item[n_items]);
            fflush(stdout);
        errcon->n_items = ++n_items;
        n_added++;
        }

    if (!n_added && !allow_missing_elements) {
        fprintf(stdout, "error: no match for name %s\n", name);
        fflush(stdout);
        exitElegant(1);
        }
    log_exit("add_error_element");
    }
Exemplo n.º 21
0
int main(int argc, char **argv)
{
  FILE *fileID;
  COLUMN_DATA_STRUCTURES *columnValues;
  PARAMETER_DATA_STRUCTURES *parameterValues;

  SDDS_DATASET SDDS_dataset;
  SCANNED_ARG *s_arg;
  long i, j, k, n, i_arg;
  int32_t rows;
  int32_t maxRows=10000, initRows=10000, row;
  long par, col, page, size, readline=1, fillin=0;
  int32_t ptrSize=0;
  char *input, *output, s[1024], *ptr, *ptr2, data[10240],temp[10240];
  unsigned long pipeFlags=0,majorOrderFlag;
  long noWarnings=0, tmpfile_used=0, columnOrder=0, whitespace=1;
  short shortValue;
  int32_t longValue;
  float floatValue;
  double doubleValue;
  char stringValue[SDDS_MAXLINE];
  char characterValue;
  char buffer[124], buffer2[124];
  long *parameterIndex, *columnIndex;

  long binary=0, noRowCount=0, inputBinary=0, count=0;
  char separator;
  char commentCharacters[20];
  short checkComment=0;
  short commentFound;
  long parameters=0, columns=0;
  long skiplines=0;
  short abort=0, recover=1, columnMajorOrder=0;

  input = output = NULL;
  separator = ' ';
  columnValues = NULL;
  parameterValues = NULL;

  parameterIndex = columnIndex = NULL;

  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_MAJOR_ORDER:
        majorOrderFlag=0;
        s_arg[i_arg].n_items -=1;
        if (s_arg[i_arg].n_items>0 &&
            (!scanItemList(&majorOrderFlag, s_arg[i_arg].list+1, &s_arg[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_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_INPUTMODE:
	if (s_arg[i_arg].n_items!=2)
	  SDDS_Bomb("invalid -inputMode syntax");
	switch (match_string(s_arg[i_arg].list[1], mode_name, MODES, 0)) {
	case ASCII_MODE:
	  inputBinary = 0;
	  break;
	case BINARY_MODE:
	  inputBinary = 1;
	  break;
	default:
	  SDDS_Bomb("invalid -inputMode 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][0];
        whitespace = 0;
	break;
      case SET_COMMENT:
	if (s_arg[i_arg].n_items!=2)
	  SDDS_Bomb("invalid -commentCharacters syntax");
	sprintf(commentCharacters, "%s", s_arg[i_arg].list[1]);
        checkComment=1;
	break;
      case SET_FILLIN:
        fillin=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<3)
	  SDDS_Bomb("invalid -parameter syntax");
        count=1;
	parameters++;
	parameterValues = trealloc(parameterValues, sizeof(*parameterValues)*(parameters));
        SDDS_CopyString(&parameterValues[parameters-1].name, s_arg[i_arg].list[1]);
	parameterValues[parameters-1].units = NULL;
	parameterValues[parameters-1].description = NULL;
	parameterValues[parameters-1].symbol = NULL;
	switch (match_string(s_arg[i_arg].list[2], type_name, DATATYPES, 0)) {
	case TYPE_SHORT:
	  parameterValues[parameters-1].type = SDDS_SHORT;
	  break;
	case TYPE_LONG:
	  parameterValues[parameters-1].type = SDDS_LONG;
	  break;
	case TYPE_FLOAT:
	  parameterValues[parameters-1].type = SDDS_FLOAT;
	  break;
	case TYPE_DOUBLE:
	  parameterValues[parameters-1].type = SDDS_DOUBLE;
	  break;
	case TYPE_STRING:
	  parameterValues[parameters-1].type = SDDS_STRING;
	  break;
	case TYPE_CHARACTER:
	  parameterValues[parameters-1].type = SDDS_CHARACTER;
	  break;
	default:
	  SDDS_Bomb("invalid -parameter type");
	  break;
	}
	for (i=3;i<s_arg[i_arg].n_items;i++) {
	  if (!(ptr=strchr(s_arg[i_arg].list[i], '=')))
	    SDDS_Bomb("invalid -parameter syntax");
	  *ptr++ = 0;	
	  switch (match_string(s_arg[i_arg].list[i], header_elements, HEADERELEMENTS, 0)) {
	  case HEADER_UNITS:
            SDDS_CopyString(&parameterValues[parameters-1].units, ptr);
	    break;
	  case HEADER_DESCRIPTION:
            SDDS_CopyString(&parameterValues[parameters-1].description, ptr);
	    break;
	  case HEADER_SYMBOL:
            SDDS_CopyString(&parameterValues[parameters-1].symbol, ptr);
	    break;
	  case HEADER_COUNT:
	    if (sscanf(ptr, "%ld", &count)!=1 ||
                count<=0)
              SDDS_Bomb("invalid parameter count value");
            sprintf(buffer, "%s", parameterValues[parameters-1].name);
            sprintf(buffer2, "%s1", buffer);
            free(parameterValues[parameters-1].name);
            SDDS_CopyString(&parameterValues[parameters-1].name, buffer2);
	    break;
	  default:
	    SDDS_Bomb("invalid -parameter syntax");
	    break;
	  } 
	}
        
        for (i=2;i<=count;i++) {
          parameters++;
          parameterValues = trealloc(parameterValues, sizeof(*parameterValues)*(parameters));
          sprintf(buffer2, "%s%ld", buffer, i);
          SDDS_CopyString(&parameterValues[parameters-1].name, buffer2);
          parameterValues[parameters-1].units = NULL;
          parameterValues[parameters-1].description = NULL;
          parameterValues[parameters-1].symbol = NULL;
          parameterValues[parameters-1].type = parameterValues[parameters-2].type;
          if (parameterValues[parameters-2].units)
            SDDS_CopyString(&parameterValues[parameters-1].units, parameterValues[parameters-2].units);
          if (parameterValues[parameters-2].description)
            SDDS_CopyString(&parameterValues[parameters-1].description, parameterValues[parameters-2].description);
          if (parameterValues[parameters-2].symbol)
            SDDS_CopyString(&parameterValues[parameters-1].symbol, parameterValues[parameters-2].symbol);
        }
        
	break;
      case SET_COLUMN:
	if (s_arg[i_arg].n_items<3)
	  SDDS_Bomb("invalid -column syntax");
        count=1;
	columns++;
	columnValues = trealloc(columnValues, sizeof(*columnValues)*(columns));
        SDDS_CopyString(&columnValues[columns-1].name, s_arg[i_arg].list[1]);
	columnValues[columns-1].elements = 0;
	columnValues[columns-1].values = NULL;
	columnValues[columns-1].stringValues = NULL;
	columnValues[columns-1].units = NULL;
	columnValues[columns-1].description = NULL;
	columnValues[columns-1].symbol = NULL;
	columnValues[columns-1].skip = 0;

	switch (match_string(s_arg[i_arg].list[2], type_name, DATATYPES, 0)) {
	case TYPE_SHORT:
	  columnValues[columns-1].type = SDDS_SHORT;
	  break;
	case TYPE_LONG:
	  columnValues[columns-1].type = SDDS_LONG;
	  break;
	case TYPE_FLOAT:
	  columnValues[columns-1].type = SDDS_FLOAT;
	  break;
	case TYPE_DOUBLE:
	  columnValues[columns-1].type = SDDS_DOUBLE;
	  break;
	case TYPE_STRING:
	  columnValues[columns-1].type = SDDS_STRING;
	  break;
	case TYPE_CHARACTER:
	  columnValues[columns-1].type = SDDS_CHARACTER;
	  break;
	default:
	  SDDS_Bomb("invalid -column type");
	  break;
	}
	for (i=3;i<s_arg[i_arg].n_items;i++) {
	  if (!(ptr=strchr(s_arg[i_arg].list[i], '=')))
	    SDDS_Bomb("invalid -column syntax");
	  *ptr++ = 0;	
	  switch (match_string(s_arg[i_arg].list[i], header_elements, HEADERELEMENTS, 0)) {
	  case HEADER_UNITS:
            SDDS_CopyString(&columnValues[columns-1].units, ptr);
	    break;
	  case HEADER_DESCRIPTION:
            SDDS_CopyString(&columnValues[columns-1].description, ptr);
	    break;
	  case HEADER_SYMBOL:
            SDDS_CopyString(&columnValues[columns-1].symbol, ptr);
	    break;
	  case HEADER_COUNT:
	    if (sscanf(ptr, "%ld", &count)!=1 ||
                count<=0)
              SDDS_Bomb("invalid column count value");
            sprintf(buffer, "%s", columnValues[columns-1].name);
            sprintf(buffer2, "%s1", buffer);
            free(columnValues[columns-1].name);
            SDDS_CopyString(&columnValues[columns-1].name, buffer2);
	    break;
	  default:
	    SDDS_Bomb("invalid -column syntax");
	    break;
	  }
	}
        
        for (i=2;i<=count;i++) {
          columns++;
          columnValues = trealloc(columnValues, sizeof(*columnValues)*(columns));
          sprintf(buffer2, "%s%ld", buffer, i);
          SDDS_CopyString(&columnValues[columns-1].name, buffer2);
          columnValues[columns-1].elements = 0;
          columnValues[columns-1].values = NULL;
          columnValues[columns-1].stringValues = NULL;
          columnValues[columns-1].units = NULL;
          columnValues[columns-1].description = NULL;
          columnValues[columns-1].symbol = NULL;
          columnValues[columns-1].type = columnValues[columns-2].type;
          if (columnValues[columns-2].units)
            SDDS_CopyString(&columnValues[columns-1].units, columnValues[columns-2].units);
          if (columnValues[columns-2].description)
            SDDS_CopyString(&columnValues[columns-1].description, columnValues[columns-2].description);
          if (columnValues[columns-2].symbol)
            SDDS_CopyString(&columnValues[columns-1].symbol, columnValues[columns-2].symbol);
        }
        
	break;
      case SET_SKIPCOLUMN:
	if (s_arg[i_arg].n_items!=2)
	  SDDS_Bomb("invalid -skipcolumn syntax");
        count=1;
	columns++;
	columnValues = trealloc(columnValues, sizeof(*columnValues)*(columns));
        columnValues[columns-1].name = NULL;
	columnValues[columns-1].elements = 0;
	columnValues[columns-1].values = NULL;
	columnValues[columns-1].stringValues = NULL;
	columnValues[columns-1].units = NULL;
	columnValues[columns-1].description = NULL;
	columnValues[columns-1].symbol = NULL;
	columnValues[columns-1].skip = 1;

	switch (match_string(s_arg[i_arg].list[1], type_name, DATATYPES, 0)) {
	case TYPE_SHORT:
	  columnValues[columns-1].type = SDDS_SHORT;
	  break;
	case TYPE_LONG:
	  columnValues[columns-1].type = SDDS_LONG;
	  break;
	case TYPE_FLOAT:
	  columnValues[columns-1].type = SDDS_FLOAT;
	  break;
	case TYPE_DOUBLE:
	  columnValues[columns-1].type = SDDS_DOUBLE;
	  break;
	case TYPE_STRING:
	  columnValues[columns-1].type = SDDS_STRING;
	  break;
	case TYPE_CHARACTER:
	  columnValues[columns-1].type = SDDS_CHARACTER;
	  break;
	default:
	  SDDS_Bomb("invalid -skipcolumn type");
	  break;
	}        
	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_SKIPLINES:
	if (s_arg[i_arg].n_items!=2 ||
	    sscanf(s_arg[i_arg].list[1], "%ld", &skiplines)!=1 ||
	    skiplines<=0)
	  SDDS_Bomb("invalid -skiplines syntax");
	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("plaindata2sdds", &input, &output, pipeFlags, noWarnings, &tmpfile_used);

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

  if (skiplines && inputBinary)
    SDDS_Bomb("-skiplines does not work with binary input files");
  
  if (!input) {
    if (inputBinary) {
#if defined(_WIN32)
      if (_setmode(_fileno(stdin), _O_BINARY) == -1) {
	fprintf(stderr, "error: unable to set stdin to binary mode\n");
	exit(1);
      }      
#endif
    }
    fileID = stdin;
  } else {
    if (!fexists(input)) {
      fprintf(stderr, "input file not found\n");
      exit(1);
    }
    if (inputBinary) {
      fileID = fopen(input, "rb");
    } else {
      fileID = fopen(input, "r");
    }
  }
  if (fileID == NULL) {
    fprintf(stderr, "unable to open input file for reading\n");
    exit(1);
  }
  
  if (!SDDS_InitializeOutput(&SDDS_dataset, binary?SDDS_BINARY:SDDS_ASCII,
                             1, NULL, NULL, output))
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    
  SDDS_dataset.layout.data_mode.column_major = columnMajorOrder;
  
  if (parameters) {
    parameterIndex = tmalloc(sizeof(*parameterIndex)*parameters);
  }
  if (columns) {
    columnIndex = tmalloc(sizeof(*columnIndex)*columns);
  }

  for (i=0; i<parameters; i++) {
    if ((parameterIndex[i] = 
         SDDS_DefineParameter(&SDDS_dataset, parameterValues[i].name, parameterValues[i].symbol,
			      parameterValues[i].units, parameterValues[i].description, NULL, 
                           parameterValues[i].type, 0))<0) {
      sprintf(s, "Problem defining parameter %s.", parameterValues[i].name);
      SDDS_SetError(s);
      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    }
  }
  for (i=0; i<columns; i++) {
    if (columnValues[i].skip)
      continue;
    if ((columnIndex[i] = 
         SDDS_DefineColumn(&SDDS_dataset, columnValues[i].name, columnValues[i].symbol, \
			   columnValues[i].units, columnValues[i].description, NULL, 
                           columnValues[i].type, 0))<0) {
      sprintf(s, "Problem defining column %s.", columnValues[i].name);
      SDDS_SetError(s);
      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    }
  }

  if (!SDDS_WriteLayout(&SDDS_dataset))
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);

  if (!SDDS_StartPage(&SDDS_dataset, initRows))
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);


  row = par = col = page = 0;
  while (inputBinary) {
    row = par = col = 0;
    
    if (fread(&rows,sizeof(rows),1,fileID) != 1) {
      if (page == 0) {
	SDDS_SetError("Unable to read number of rows");
	SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
      } else {
        if (!SDDS_Terminate(&SDDS_dataset))
          SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
        for (k=0;k<columns;k++) {
          if (columnValues[k].type == SDDS_STRING) {
            SDDS_FreeStringArray(columnValues[k].stringValues,columnValues[k].elements);
          } else {
            free(columnValues[k].values);
          }
        }
	return 0;
      }
    }
    page++;

    for (par=0;par<parameters;par++) {
      
      switch (parameterValues[par].type) {
      case SDDS_SHORT:
	if (fread(&shortValue,2,1,fileID) != 1) {
     	  SDDS_SetError("Unable to read short parameter");
	  SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
	}
	if (!SDDS_SetParameters(&SDDS_dataset,SDDS_SET_BY_INDEX|SDDS_PASS_BY_VALUE,par,shortValue,-1))
	  SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	break;
      case SDDS_LONG:
	if (fread(&longValue,4,1,fileID) != 1) {
     	  SDDS_SetError("Unable to read long parameter");
	  SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
	}
	if (!SDDS_SetParameters(&SDDS_dataset,SDDS_SET_BY_INDEX|SDDS_PASS_BY_VALUE,par,longValue,-1))
	  SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	break;
      case SDDS_FLOAT:
	if (fread(&floatValue,4,1,fileID) != 1) {
     	  SDDS_SetError("Unable to read float parameter");
	  SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
	}
	if (!SDDS_SetParameters(&SDDS_dataset,SDDS_SET_BY_INDEX|SDDS_PASS_BY_VALUE,par,floatValue,-1))
	  SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	break;
      case SDDS_DOUBLE:
	if (fread(&doubleValue,8,1,fileID) != 1) {
     	  SDDS_SetError("Unable to read double parameter");
	  SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
	}
	if (!SDDS_SetParameters(&SDDS_dataset,SDDS_SET_BY_INDEX|SDDS_PASS_BY_VALUE,par,doubleValue,-1))
	  SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	break;
      case SDDS_STRING:
	if (fread(&size,4,1,fileID) != 1) {
     	  SDDS_SetError("Unable to read string parameter");
	  SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
	}
        if (size>SDDS_MAXLINE-1)
          SDDS_Bomb("String is too long");
	if (size > 0) {
	  if (fread(&stringValue,size,1,fileID) != 1) {
	    SDDS_SetError("Unable to read string parameter");
	    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
	  }
          stringValue[size] = 0;
	} else {
	  strcpy(stringValue,"");
	}
	if (!SDDS_SetParameters(&SDDS_dataset,SDDS_SET_BY_INDEX|SDDS_PASS_BY_VALUE,par,stringValue,-1))
	  SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	break;
      case SDDS_CHARACTER:
	if (fread(&characterValue,1,1,fileID) != 1) {
     	  SDDS_SetError("Unable to read character parameter");
	  SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
	}
	if (!SDDS_SetParameters(&SDDS_dataset,SDDS_SET_BY_INDEX|SDDS_PASS_BY_VALUE,par,characterValue,-1))
	  SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	break;
      }
    }
    for (i=0;i<columns;i++) {
	if (rows > columnValues[i].elements) {
	  if (columnValues[i].type == SDDS_STRING) {
	    columnValues[i].stringValues = AllocateColumnStringData(columnValues[i].stringValues, rows, columnValues[i].elements);
	  } else {
	    columnValues[i].values = AllocateColumnData(columnValues[i].type, columnValues[i].values, rows);
          }
	  columnValues[i].elements = rows;
	}
    }
    if (columnOrder) {
      for (col=0;col<columns;col++) {
	switch (columnValues[col].type) {
	case SDDS_SHORT:
	  for (i=0;i<rows;i++) {
	    if (fread((short*)(columnValues[col].values)+i,2,1,fileID) != 1) {
	      SDDS_SetError("Unable to read short column");
	      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
	    }
	  }
	  break;
	case SDDS_LONG:
	  for (i=0;i<rows;i++) {
	    if (fread((int32_t*)(columnValues[col].values)+i,4,1,fileID) != 1) {
	      SDDS_SetError("Unable to read long column");
	      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
	    }
	  }
	  break;
	case SDDS_FLOAT:
	  for (i=0;i<rows;i++) {
	    if (fread((float*)(columnValues[col].values)+i,4,1,fileID) != 1) {
	      SDDS_SetError("Unable to read float column");
	      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
	    }      
	  }
	  break;
	case SDDS_DOUBLE:
	  for (i=0;i<rows;i++) {
	    if (fread((double*)(columnValues[col].values)+i,8,1,fileID) != 1) {
	      SDDS_SetError("Unable to read double double");
	      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
	    }
	  }
	  break;
	case SDDS_STRING:
	  for (i=0;i<rows;i++) {
	    if (fread(&size,4,1,fileID) != 1) {
	      SDDS_SetError("Unable to read string column");
	      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
	    }
            if (size>SDDS_MAXLINE-1)
              SDDS_Bomb("String is too long");
            columnValues[col].stringValues[i] = malloc(size + 1);
	    if (size > 0) {
	      if (fread(columnValues[col].stringValues[i],size,1,fileID) != 1) {
		SDDS_SetError("Unable to read string column");
		SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
	      }
              columnValues[col].stringValues[i][size] = 0;
	    } else {
	      strcpy(columnValues[col].stringValues[i],"");
	    }
	  }
	  break;
	case SDDS_CHARACTER:
	  for (i=0;i<rows;i++) {
	    if (fread((char*)(columnValues[col].values)+i,1,1,fileID) != 1) {
	      SDDS_SetError("Unable to read character column");
	      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
	    }
	  }
	  break;
	}
      }
    } else {
      for (i=0;i<rows;i++) {
	for (col=0;col<columns;col++) {
	  switch (columnValues[col].type) {
	  case SDDS_SHORT:
	    if (fread((short*)(columnValues[col].values)+i,2,1,fileID) != 1) {
	      SDDS_SetError("Unable to read short column");
	      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
	    }
	    break;
	  case SDDS_LONG:
	    if (fread((int32_t*)(columnValues[col].values)+i,4,1,fileID) != 1) {
	      SDDS_SetError("Unable to read long column");
	      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
	    }
	    break;
	  case SDDS_FLOAT:
	    if (fread((float*)(columnValues[col].values)+i,4,1,fileID) != 1) {
	      SDDS_SetError("Unable to read float column");
	      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
	    }      
	    break;
	  case SDDS_DOUBLE:
	    if (fread(((double*)(columnValues[col].values)+i),8,1,fileID) != 1) {
	      SDDS_SetError("Unable to read double column");
	      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
	    }
	    break;
	  case SDDS_STRING:
	    if (fread(&size,4,1,fileID) != 1) {
	      SDDS_SetError("Unable to read string column");
	      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
	    }
            if (size>SDDS_MAXLINE-1)
              SDDS_Bomb("String is too long");
            columnValues[col].stringValues[i] = malloc(size + 1);
	    if (size > 0) {
	      if (fread(columnValues[col].stringValues[i],size,1,fileID) != 1) {
		SDDS_SetError("Unable to read string column");
		SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
	      }
              columnValues[col].stringValues[i][size] = 0;
	    } else {
	      strcpy(columnValues[col].stringValues[i],"");
	    }
	    break;
	  case SDDS_CHARACTER:
	    if (fread(((char*)(columnValues[col].values)+i),1,1,fileID) != 1) {
	      SDDS_SetError("Unable to read character column");
	      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
	    }
	    break;
	  }
	}
      }
    }
    if (rows > maxRows) {
      if (!SDDS_LengthenTable(&SDDS_dataset, rows - maxRows)) {
	SDDS_SetError("Unable to lengthen table");
	SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
      }
      maxRows = rows;
    }
    j=n;
    for (i=0;i<columns;i++) {
      if (columnValues[i].skip)
	continue;
      if (columnValues[i].type == SDDS_STRING) {
	SetColumnData(columnValues[i].type, &SDDS_dataset, columnValues[i].stringValues, rows, n);
      } else {
	SetColumnData(columnValues[i].type, &SDDS_dataset, columnValues[i].values, rows, n);
      }
      n++;
    }
    
    if (!SDDS_WritePage(&SDDS_dataset)) {
      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
    }
    maxRows = 10000;
    if (!SDDS_StartPage(&SDDS_dataset, initRows))
      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
  }
  
  row = par = col = n = 0;
  rows = -1;
  ptr = NULL;
  ptr = SDDS_Malloc(sizeof(*ptr)*(ptrSize=2048));
  /*  ptr2 = NULL;
      ptr2 = SDDS_Malloc(sizeof(*ptr)*(ptrSize=2048));*/
  ptr[0] = 0;
  while (1) {
    if (readline) {
      while (skiplines > 0) {
	fgets(ptr, ptrSize, fileID);
	skiplines--;
      }
      if (!fgetsSkipCommentsResize(&ptr,&ptrSize,fileID, '!'))
	break;
      commentFound=0;
      if (checkComment) {
        for (i=0; i<strlen(commentCharacters); i++) {
          if (ptr[0] == commentCharacters[i]) {
            commentFound=1;
          }
        }
      }
      if (commentFound == 1) {
        continue;
      }
      if (ptr[strlen(ptr)-1] == '\n')
        ptr[strlen(ptr)-1] = 0;
      strcpy(temp,ptr);
      /*skip empty lines*/
      if (getToken(temp,data,10240,separator,whitespace)<0)
        continue;
    } else {
      readline = 1;
    }
    if (par < parameters) {
      switch (parameterValues[par].type) {
      case SDDS_SHORT:
	if (sscanf(ptr,"%hd",&shortValue) != 1) {
	  SDDS_SetError("Invalid short parameter");
	  SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	}
	if (!SDDS_SetParameters(&SDDS_dataset,SDDS_SET_BY_INDEX|SDDS_PASS_BY_VALUE,par,shortValue,-1))
	  SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	break;
      case SDDS_LONG:
	if (sscanf(ptr,"%" SCNd32 ,&longValue) != 1) {
	  SDDS_SetError("Invalid long parameter");
	  SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	}
	if (!SDDS_SetParameters(&SDDS_dataset,SDDS_SET_BY_INDEX|SDDS_PASS_BY_VALUE,par,longValue,-1))
	  SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	break;
      case SDDS_FLOAT:
        ConvertDNotationToENotation(ptr);
	if (sscanf(ptr,"%f",&floatValue) != 1) {
	  SDDS_SetError("Invalid float parameter");
	  SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	}
	if (!SDDS_SetParameters(&SDDS_dataset,SDDS_SET_BY_INDEX|SDDS_PASS_BY_VALUE,par,floatValue,-1))
	  SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	break;
      case SDDS_DOUBLE:
        ConvertDNotationToENotation(ptr);
	if (sscanf(ptr,"%lf",&doubleValue) != 1) {
	  SDDS_SetError("Invalid double parameter");
	  SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	}
	if (!SDDS_SetParameters(&SDDS_dataset,SDDS_SET_BY_INDEX|SDDS_PASS_BY_VALUE,par,doubleValue,-1))
	  SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	break;
      case SDDS_STRING:
	SDDS_GetToken(ptr,stringValue,SDDS_MAXLINE);
	SDDS_InterpretEscapes(stringValue);
	if (!SDDS_SetParameters(&SDDS_dataset,SDDS_SET_BY_INDEX|SDDS_PASS_BY_VALUE,par,stringValue,-1))
	  SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	break;
      case SDDS_CHARACTER:
	SDDS_InterpretEscapes(ptr);
	characterValue = ptr[0];
	if (!SDDS_SetParameters(&SDDS_dataset,SDDS_SET_BY_INDEX|SDDS_PASS_BY_VALUE,par,characterValue,-1))
	  SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	break;
      }
      par++;
    } else if ((rows == -1) && (!noRowCount)) {
      if (sscanf(ptr,"%ld",&rows) != 1) {
	SDDS_SetError("Invalid row count");
	SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
      }
    } else if ((columns > 0) && ((row < rows) || (noRowCount)))  {

      if (columnOrder) {

	if (noRowCount) {
	  cp_str(&ptr2,ptr);
	  rows = 0;
	  while (getToken(ptr2,data,10240,separator,whitespace) >= 0) {
	    rows++;
          }
          free(ptr2);
	}

	if (rows > columnValues[col].elements) {
	  if (columnValues[col].type == SDDS_STRING) {
	    columnValues[col].stringValues = AllocateColumnStringData(columnValues[col].stringValues, rows, columnValues[col].elements);
	  } else {
	    columnValues[col].values = AllocateColumnData(columnValues[col].type, columnValues[col].values, rows);
          }
	  columnValues[col].elements = rows;
	}
	switch (columnValues[col].type) {
	case SDDS_SHORT:
	  for (row=0;row<rows;row++) {
	    if (getToken(ptr,data,10240,separator,whitespace) < 0) {
	      SDDS_SetError("Invalid short column element");
	      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	    }
	    if (sscanf(data,"%hd",((short*)(columnValues[col].values)+row)) != 1) {
	      SDDS_SetError("Invalid short column element");
	      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	    }
	  }
	  break;
	case SDDS_LONG:
	  for (row=0;row<rows;row++) {
	    if (getToken(ptr,data,10240,separator,whitespace) < 0) {
	      SDDS_SetError("Invalid long column element");
	      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	    }
	    if (sscanf(data,"%" SCNd32,((int32_t*)(columnValues[col].values)+row)) != 1) {
	      SDDS_SetError("Invalid long column element");
	      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	    }
	  }
	  break;
	case SDDS_FLOAT:
	  for (row=0;row<rows;row++) {
	    if (getToken(ptr,data,10240,separator,whitespace) < 0) {
	      SDDS_SetError("Invalid float column element");
	      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	    }
            ConvertDNotationToENotation(data);
	    if (sscanf(data,"%f",((float*)(columnValues[col].values)+row)) != 1) {
	      SDDS_SetError("Invalid float column element");
	      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	    }
	  }
	  break;
	case SDDS_DOUBLE:
	  for (row=0;row<rows;row++) {
	    if (getToken(ptr,data,10240,separator,whitespace) < 0) {
	      SDDS_SetError("Invalid double column element");
	      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	    }
            ConvertDNotationToENotation(data);
	    if (sscanf(data,"%lf",((double*)(columnValues[col].values)+row)) != 1) {
	      SDDS_SetError("Invalid double column element");
	      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	    }
	  }
	  break;
	case SDDS_STRING:
	  for (row=0;row<rows;row++) {
	    if (getToken(ptr,data,10240,separator,whitespace) < 0) {
	      SDDS_SetError("Invalid string column element");
	      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	    }
	    SDDS_InterpretEscapes(data);
            columnValues[col].stringValues[row] = malloc(strlen(data) + 1);
	    strcpy(columnValues[col].stringValues[row],data);
	  }
	  break;
	case SDDS_CHARACTER:
	  for (row=0;row<rows;row++) {
	    if (getToken(ptr,data,10240,separator,whitespace) < 0) {
	      SDDS_SetError("Invalid character column element");
	      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	    }
	    SDDS_InterpretEscapes(data);
	    *((char*)(columnValues[col].values)+row) = data[0];
	  }
	  break;
	}
	if (rows > maxRows) {
	  if (!SDDS_LengthenTable(&SDDS_dataset, rows - maxRows)) {
	    SDDS_SetError("Unable to lengthen table");
	    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
	  }
	  maxRows = rows;
	}
	if (columnValues[col].skip == 0) {
	  if (columnValues[col].type == SDDS_STRING) {
	    SetColumnData(columnValues[col].type, &SDDS_dataset, columnValues[col].stringValues, rows, col);
	  } else {
	    SetColumnData(columnValues[col].type, &SDDS_dataset, columnValues[col].values, rows, col);
	  }
	  n++;
	}
	col++;
	row = 0;
      } else {
	if (noRowCount) {
	  if (row == 0) {
	    rows = 3;
	  } else if (row == rows - 1) {
	    rows = rows + 3;
	    for (i=0;i<columns;i++) {
	      if (rows > columnValues[i].elements) {
		if (columnValues[i].type == SDDS_STRING) {
		  columnValues[i].stringValues = AllocateColumnStringData(columnValues[i].stringValues, rows, columnValues[i].elements);
		} else {
		  columnValues[i].values = AllocateColumnData(columnValues[i].type, columnValues[i].values, rows);
                }
	      }
	      columnValues[i].elements = rows;
	    }
	  }
	}
	if (row == 0) 
	  for (i=0;i<columns;i++) {
	    if (rows > columnValues[i].elements) {
	      if (columnValues[i].type == SDDS_STRING) {
		columnValues[i].stringValues = AllocateColumnStringData(columnValues[i].stringValues, rows, columnValues[i].elements);
	      } else {
		columnValues[i].values = AllocateColumnData(columnValues[i].type, columnValues[i].values, rows);
              }
	    }
	    columnValues[i].elements = rows;
	  }

	if (noRowCount) {
	  cp_str(&ptr2,ptr);
	  i = 0;
	  while (getToken(ptr2,data,10240,separator,whitespace) >= 0)
	    i++;
          free(ptr2);
	  if ((i != columns) && (parameters>0 && i==1)) {
	    if (row > 0) {
	      if (row > maxRows) {
		if (!SDDS_LengthenTable(&SDDS_dataset, row - maxRows)) {
		  SDDS_SetError("Unable to lengthen table");
		  SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
		}
		maxRows = row;
	      }
	      n=0;
	      for (j=0;j<columns;j++) {
		if (columnValues[j].skip)
		  continue;
		if (columnValues[j].type == SDDS_STRING) {
		  SetColumnData(columnValues[j].type, &SDDS_dataset, columnValues[j].stringValues, row, n);
		} else {
		  SetColumnData(columnValues[j].type, &SDDS_dataset, columnValues[j].values, row, n);
		}
		n++;
	      }
	      if (!SDDS_WritePage(&SDDS_dataset))
		SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	      maxRows = 10000;
	      if (!SDDS_StartPage(&SDDS_dataset, initRows))
		SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
	      row = par = col = 0;
	      rows = -1;
	    }
	    readline = 0;
	    continue;
	  }
	}

	for (i=0;i<columns;i++) {
	  if (getToken(ptr,data,10240,separator,whitespace) < 0) {
            if (!fillin) {
              SDDS_SetError("Invalid column element");
              SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
            } else {
              switch (columnValues[i].type) {
              case SDDS_SHORT:
              case SDDS_LONG:
              case SDDS_FLOAT:
              case SDDS_DOUBLE:
                data[0]='0';
                data[1]='\0';
                break;
              case SDDS_STRING:  
              case SDDS_CHARACTER:
                data[0]='\0';
                break;
              }
            }
	  }

	  switch (columnValues[i].type) {
	  case SDDS_SHORT:
	    if (sscanf(data,"%hd",((short*)(columnValues[i].values)+row)) != 1) {
              if (recover) {
                abort=1;
                row--;
              } else {
                SDDS_SetError("Invalid short column element");
                SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
              }
            }
	    break;
	  case SDDS_LONG:
	    if (sscanf(data,"%" SCNd32,((int32_t*)(columnValues[i].values)+row)) != 1) {
              if (recover) {
                abort=1;
                row--;
              } else {
                SDDS_SetError("Invalid long column element");
                SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
              }
            }
	    break;
	  case SDDS_FLOAT:
            ConvertDNotationToENotation(data);
	    if (sscanf(data,"%f",((float*)(columnValues[i].values)+row)) != 1) {
              if (recover) {
                abort=1;
                row--;
              } else {
                SDDS_SetError("Invalid float column element");
                SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
              }
            }
	    break;
	  case SDDS_DOUBLE:
            ConvertDNotationToENotation(data);
	    if (sscanf(data,"%lf",((double*)(columnValues[i].values)+row)) != 1) {
              if (recover) {
                abort=1;
                row--;
              } else {
                SDDS_SetError("Invalid double column element");
                SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
              }
	    }
	    break;
	  case SDDS_STRING:
	    SDDS_InterpretEscapes(data);
            columnValues[i].stringValues[row] = malloc(strlen(data) + 1);
	    strcpy(columnValues[i].stringValues[row],data);
	    break;
	  case SDDS_CHARACTER:
	    SDDS_InterpretEscapes(data);
	    *((char*)(columnValues[i].values)+row) = data[0];
	    break;
	  }

          if (recover && abort) {
            break;
          }
        }
	row++;
	if ((row == rows) && (!noRowCount)) {
	  if (rows > maxRows) {
	    if (!SDDS_LengthenTable(&SDDS_dataset, rows - maxRows)) {
	      SDDS_SetError("Unable to lengthen table");
	      SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
	    }
	    maxRows = rows;
	  }
	  n=0;
	  for (i=0;i<columns;i++) {
	    if (columnValues[i].skip)
	      continue;
	    if (columnValues[i].type == SDDS_STRING) {
	      SetColumnData(columnValues[i].type, &SDDS_dataset, columnValues[i].stringValues, rows, n);
	    } else {
	      SetColumnData(columnValues[i].type, &SDDS_dataset, columnValues[i].values, rows, n);
	    }
	    n++;
	  }
	}
      }
    }
    if ((par == parameters) && 
	(((!noRowCount) && (rows != -1)) || (noRowCount)) && 
	(((columnOrder) && (col == columns)) || ((columns > 0) && (row == rows)) || (columns == 0))) {
      if (!SDDS_WritePage(&SDDS_dataset)) {
	SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
      }
      maxRows = 10000;
      if (!SDDS_StartPage(&SDDS_dataset, initRows))
	SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
      
      row = par = col = 0;
      rows = -1;
    }
    ptr[0] = 0;
  }

  if (noRowCount) {
    if (row > 0) {
      if (row > maxRows) {
	if (!SDDS_LengthenTable(&SDDS_dataset, row - maxRows)) {
	  SDDS_SetError("Unable to lengthen table");
	  SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors); 
	}
	maxRows = row;
      }
      n=0;
      for (j=0;j<columns;j++) {
	if (columnValues[j].skip)
	  continue;
	if (columnValues[j].type == SDDS_STRING) {
	  SetColumnData(columnValues[j].type, &SDDS_dataset, columnValues[j].stringValues, row, n);
	} else {
	  SetColumnData(columnValues[j].type, &SDDS_dataset, columnValues[j].values, row, n);
	}
	n++;
      }
      if (!SDDS_WritePage(&SDDS_dataset)) {
	SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
      }
      maxRows = 10000;
    }
  }
  for (i=0;i<columns;i++) {
    if (columnValues[i].type == SDDS_STRING) {
      for (j=0;j<columnValues[i].elements;j++) {
	free(columnValues[i].stringValues[j]);
      }
      free(columnValues[i].stringValues);
    } else {
      free(columnValues[i].values);
    }
    if (columnValues[i].name) free(columnValues[i].name);
    if (columnValues[i].units) free(columnValues[i].units);
    if (columnValues[i].description) free(columnValues[i].description);
    if (columnValues[i].symbol) free(columnValues[i].symbol);

  }
  for (i=0;i<parameters;i++) {
    free(parameterValues[i].name);
    if (parameterValues[i].units) free(parameterValues[i].units);
    if (parameterValues[i].description) free(parameterValues[i].description);
    if (parameterValues[i].symbol) free(parameterValues[i].symbol);
  }
  if (columnValues) free(columnValues);
  if (parameterValues) free(parameterValues);
  if (columnIndex) free(columnIndex);
  if (parameterIndex) free(parameterIndex);
  if (ptr) free(ptr);
  if (!SDDS_Terminate(&SDDS_dataset))
    SDDS_PrintErrors(stderr, SDDS_VERBOSE_PrintErrors|SDDS_EXIT_PrintErrors);
  free_scanargs(&s_arg,argc);
  return 0;
}
Exemplo n.º 22
0
Arquivo: rpn.c Projeto: epicsdeb/sdds
int main(int argc, char **argv)
{
    long i, return_code;
    char *ptr;
    static char *input;
    static char *rpn_defns;
#if defined(LINUX)
    struct stat sts;
#endif

#ifdef VAX_VMS
    /* initialize collection of computer usage statistics--required by
     * user-callable function 'rs'
     */
    init_stats();
#endif

    puts("Welcome to rpn version 6, by Michael Borland and Robert Soliday (June 1999).");

    /* sort the command table for faster access */
    /*qsort(func, NFUNCS, sizeof(struct FUNCTION), func_compare); */
    qsort(funcRPN, sizeof(funcRPN)/sizeof(funcRPN[0]), sizeof(struct FUNCTION), func_compare);
    /* initialize stack pointers--empty stacks */
    stackptr = 0;
    sstackptr = 0;
    lstackptr = 0;
    astackptr = 0;
    dstackptr = 0;
    astack = NULL;
    udf_stackptr = 0;
    max_udf_stackptr = 0;
    udf_stack = NULL;
    udf_cond_stackptr = 0;
    max_udf_cond_stackptr = 0;
    udf_cond_stack = NULL;
    udf_id = NULL;	
    udf_unknown = NULL;

    /* The first item on the command input stack is the standard input.
     * Input from this source is echoed to the screen. */
    istackptr = 1;
    input_stack[0].fp = stdin;
    input_stack[0].filemode = ECHO;

    /* Initialize variables use in keeping track of what 'code' is being
     * executed.  code_ptr is a global pointer to the currently used
     * code structure.  The code is kept track of in a linked list of
     * code structures.
     */
    code_ptr = &code;
    input = code_ptr->text = tmalloc(sizeof(*(code_ptr->text))*CODE_LEN);
    code_ptr->position = 0;
    code_ptr->token = NULL;
    code_ptr->storage_mode = STATIC;
    code_ptr->buffer = tmalloc(sizeof(*(code_ptr->buffer))*LBUFFER);
    code_ptr->pred = code_ptr->succ = NULL;
    code_lev = 1;

    /* Initialize array of IO file structures.  Element 0 is for terminal
     * input, while element 1 is for terminal output.
     */
    for (i=0; i<FILESTACKSIZE; i++)
        io_file[i].fp = NULL;
    io_file[0].fp = stdin;
    cp_str(&(io_file[0].name), "stdin");
    io_file[0].mode = INPUT;
    io_file[1].fp = stdout;
    cp_str(&(io_file[1].name), "stdout");
    io_file[1].mode = OUTPUT;

    /* initialize variables for UDF storage */
    udf_changed = num_udfs = max_udfs = 0;
    udf_list = NULL;

    /* Initialize flags for user memories */
    n_memories = memory_added = 0;

    /* If there are arguments push them onto the input stack
     * so that it will be run to set up the program.
     */
    while (argc-- >= 2) {
        input_stack[istackptr].fp = fopen_e(argv[argc], "r", 0);
        input_stack[istackptr++].filemode = NO_ECHO;
        }

    /*add default setting for a linux system, G. Shen, Dec 31, 2009 */
    rpn_defns=getenv("RPN_DEFNS");
    if(!rpn_defns) {
#if defined(LINUX)
	if (!(stat(rpn_default, &sts) == -1 && errno == ENOENT)) { /* check whether default file exists */
	    rpn_defns = rpn_default;
	}
#endif
    }
    if (rpn_defns && (long)strlen(rpn_defns)>0 ) {
        /* push rpn definitions file onto top of the stack */
        input_stack[istackptr].fp = fopen_e(rpn_defns, "r", 0);
        input_stack[istackptr++].filemode = NO_ECHO;
        }

    /* This is the main loop. Code is read in and executed here. */
    while (istackptr!=0) {
        /* istackptr-1 gives index of most recently pushed input file. */
        /* This loop implements the command input file stacking. */
#ifdef DEBUG
        fprintf(stderr, "istackptr = %ld\n", istackptr);
#endif
        while (prompt("rpn> ", !(istackptr-1)),
                ptr=fgets((code_ptr->text=input), CODE_LEN,
                input_stack[istackptr-1].fp)) {
            /* Loop while there's still data in the (istackptr-1)th file. *
             * The data is put in the code list.                          */
#ifdef DEBUG
            fprintf(stderr, "input string: >%s<\n", ptr);
#endif
            /* If we are at the terminal input level and a UDF has been changed
             * or a memory added, relink the udfs to get any references to the
             * new udf or memory translated into 'pcode'.
             */
            if ((udf_changed) || memory_added) {
#ifdef DEBUG
                fputs("re-linking udfs", stderr);
#endif
                link_udfs();
                udf_changed = memory_added = 0;
                }
            code_ptr->position = 0;

            /* Get rid of new-lines in data from files, and echo data to  *
             * screen if appropriate.                                     */
            if (istackptr!=1 && ptr!=NULL) {
#ifdef DEBUG
                fputs("truncating input line", stderr);
#endif
                chop_nl(ptr);
                if (input_stack[istackptr-1].filemode==ECHO)
                    puts(ptr);
                }

            /* Check for and ignore comment lines. */
#ifdef DEBUG
            fputs("checking for comment line", stderr);
#endif
            if (strncmp(ptr, "/*", 2)==0)
                continue;

            /* Finally, push input line onto the code stack & execute it.   */
#ifdef DEBUG
            fputs("pushing onto stack and executing", stderr);
#endif
            return_code = execute_code();
	    cycle_counter = 0;

            if (code_lev!=1) {
                fputs("error: code level on return from execute_code is not 1\n", stderr);
                exit(1);
                }
            /* Reset pointers in the current code structure to indicate that the
             * stuff has been executed.
             */
#ifdef DEBUG
            fputs("reseting pointers", stderr);
#endif
            *(code_ptr->text) = 0;
            code_ptr->position = 0;

            /* If it's appropriate to print the top of the numeric or logical *
             * stacks, do so here.                                            */
            if (stackptr>=1 && return_code==NUMERIC_FUNC )
                printf(choose_format(format_flag, stack[stackptr-1]),
                                    ' ', stack[stackptr-1], '\n');
            if (lstackptr>=1 && return_code==LOGICAL_FUNC)
                printf("%s\n", (logicstack[lstackptr-1])?"true":"false");
            }

        /* Close the current input file and go to the one below it on the *
         * stack.  This constitutes popping the command input stack.      *
         */
#ifdef DEBUG
        fputs("closing input file", stderr);
#endif
        fclose(input_stack[--istackptr].fp);
        }
    return(0);
    }