Exemple #1
0
static List _create_front_end_info_list(
	front_end_info_msg_t *front_end_info_ptr, int changed)
{
	char *upper = NULL;
	char user[32], time_str[32];
	static List info_list = NULL;
	List last_list = NULL;
	ListIterator last_list_itr = NULL;
	int i = 0;
	sview_front_end_info_t *sview_front_end_info_ptr = NULL;
	front_end_info_t *front_end_ptr = NULL;

	if (!changed && info_list)
		goto update_color;

	if (info_list)
		last_list = info_list;

	info_list = list_create(_front_end_info_list_del);

	if (last_list)
		last_list_itr = list_iterator_create(last_list);
	for (i = 0; i < front_end_info_ptr->record_count; i++) {
		front_end_ptr = &(front_end_info_ptr->front_end_array[i]);

		sview_front_end_info_ptr = NULL;

		if (last_list_itr) {
			while ((sview_front_end_info_ptr =
				list_next(last_list_itr))) {
				if (!xstrcmp(sview_front_end_info_ptr->
					     front_end_name,
					     front_end_ptr->name)) {
					list_remove(last_list_itr);
					_front_end_info_free(
						sview_front_end_info_ptr);
					break;
				}
			}
			list_iterator_reset(last_list_itr);
		}
		if (!sview_front_end_info_ptr)
			sview_front_end_info_ptr =
				xmalloc(sizeof(sview_front_end_info_t));
		sview_front_end_info_ptr->pos = i;
		sview_front_end_info_ptr->front_end_name = front_end_ptr->name;
		sview_front_end_info_ptr->front_end_ptr = front_end_ptr;
		sview_front_end_info_ptr->color_inx = i % sview_colors_cnt;
		if (g_node_info_ptr) {
			sview_front_end_info_ptr->node_inx[0] = 0;
			sview_front_end_info_ptr->node_inx[1] =
				g_node_info_ptr->record_count - 1;
			sview_front_end_info_ptr->node_inx[2] = -1;
		} else
			sview_front_end_info_ptr->node_inx[0] = -1;
		if (front_end_ptr->boot_time) {
			slurm_make_time_str(&front_end_ptr->boot_time,
					    time_str, sizeof(time_str));
			sview_front_end_info_ptr->boot_time =
				xstrdup(time_str);
		}
		if (front_end_ptr->slurmd_start_time) {
			slurm_make_time_str(&front_end_ptr->slurmd_start_time,
					    time_str, sizeof(time_str));
			sview_front_end_info_ptr->slurmd_start_time =
				xstrdup(time_str);
		}
		upper = node_state_string(front_end_ptr->node_state);
		sview_front_end_info_ptr->state = str_tolower(upper);

		if (front_end_ptr->reason && front_end_ptr->reason_time &&
		    (front_end_ptr->reason_uid != NO_VAL)) {
			struct passwd *pw = NULL;

			if ((pw=getpwuid(front_end_ptr->reason_uid)))
				snprintf(user, sizeof(user), "%s", pw->pw_name);
			else
				snprintf(user, sizeof(user), "Unk(%u)",
					 front_end_ptr->reason_uid);
			slurm_make_time_str(&front_end_ptr->reason_time,
					    time_str, sizeof(time_str));
			sview_front_end_info_ptr->reason =
				xstrdup_printf("%s [%s@%s]",
					       front_end_ptr->reason, user,
					       time_str);
		} else {
			sview_front_end_info_ptr->reason =
				xstrdup(front_end_ptr->reason);
		}

		list_append(info_list, sview_front_end_info_ptr);
	}

	if (last_list) {
		list_iterator_destroy(last_list_itr);
		FREE_NULL_LIST(last_list);
	}

update_color:
	return info_list;
}
Exemple #2
0
static void ok_cb(Fl_Widget*, void *d) {
	if(is_empty_input(name) || is_empty_input(execute) || !img->image()) {
		/* do nothing */
		win->hide();
		return;
	}
	
	Desktop *self = (Desktop*)d;
	
	DesktopFile df;
	df.create_new(DESK_FILE_TYPE_APPLICATION);
	df.set_name(name->value());

	if(comment->value())
		df.set_comment(comment->value());

	df.set_icon((img_path.length() > 1) ? img_path.c_str() : DEFAULT_ICON);
	df.set_exec(execute->value());
	
	if(!is_empty_input(workdir))
		df.set_path(workdir->value());
	
	df.set_startup_notify(start_notify->value());
	df.set_terminal(run_in_terminal->value());

	/* determine filename and save it */
	String file = name->value();
	const char *fp = file.c_str();

	str_tolower((unsigned char*)fp);
	file += EDE_DESKTOP_DESKTOP_EXT;

	/* go through the file and replace spaces with '_' */
	for(String::size_type i = 0; i < file.length(); i++)
		if(isspace(file[i])) file[i] = '_';

	String path = build_filename(self->desktop_path(), file.c_str());
	
	int  X = 0, Y = 0;
	if(curr_icon) {
		X = curr_icon->x();
		Y = curr_icon->y();
		/* try to remove icon from filesystem only when we can't overwrite old icon path */
		self->remove_icon(curr_icon, old_desktop_path != path);
	}

	if(df.save(path.c_str())) {
		DesktopIcon *ic = self->read_desktop_file(path.c_str(), file.c_str());
		if(ic) {
			if(X > 0 || Y > 0) ic->position(X, Y);
			self->add(ic);
		}

		self->redraw();
		
		/* 
		 * In case when we rename icon, icon position will not be saved (because they are saved by icon basename). So
		 * with different paths we are assured the name was changed and we proceed further.
		 */
		if(old_desktop_path != path) self->save_icons_positions();
	} else {
		alert(_("Unable to create '%s' file. Received error is: %s\n"), path.c_str(), df.strerror());
	}

	win->hide();
}
static int
parse_domain_list(FPST ** const domain_list_p,
                  FPST ** const domain_rev_list_p,
                  FPST ** const domain_substr_list_p,
                  const char * const file)
{
    char       buf[MAX_QNAME_LENGTH + 1U];
    char      *line;
    FILE      *fp;
    char      *ptr;
    FPST      *domain_list;
    FPST      *domain_list_tmp;
    FPST      *domain_rev_list;
    FPST      *domain_rev_list_tmp;
    FPST      *domain_substr_list;
    FPST      *domain_substr_list_tmp;
    size_t     line_len;
    BlockType  block_type = BLOCKTYPE_UNDEFINED;
    int        ret = -1;

    assert(domain_list_p != NULL);
    assert(domain_rev_list_p != NULL);
    assert(domain_substr_list_p != NULL);
    *domain_list_p = NULL;
    *domain_rev_list_p = NULL;
    *domain_substr_list_p = NULL;
    domain_list = fpst_new();
    domain_rev_list = fpst_new();
    domain_substr_list = fpst_new();
    if ((fp = fopen(file, "r")) == NULL) {
        return -1;
    }
    while (fgets(buf, (int) sizeof buf, fp) != NULL) {
        if ((line = trim_comments(untab(buf))) == NULL || *line == 0) {
            continue;
        }
        line_len = strlen(line);
        if (line[0] == '*' && line[line_len - 1] == '*') {
            line[line_len - 1] = 0;
            line++;
            block_type = BLOCKTYPE_SUBSTRING;
        } else if (line[line_len - 1] == '*') {
            line[line_len - 1] = 0;
            block_type = BLOCKTYPE_PREFIX;
        } else {
            if (line[0] == '*') {
                line++;
            }
            if (line[0] == '.') {
                line++;
            }
            str_reverse(line);
            block_type = BLOCKTYPE_SUFFIX;
        }
        if (*line == 0) {
            continue;
        }
        str_tolower(line);
        if ((line = strdup(line)) == NULL) {
            break;
        }
        if (block_type == BLOCKTYPE_SUFFIX) {
            if ((domain_rev_list_tmp = fpst_insert_str(domain_rev_list, line,
                                                       (uint32_t) block_type)) == NULL) {
                free(line);
                break;
            }
            domain_rev_list = domain_rev_list_tmp;
        } else if (block_type == BLOCKTYPE_PREFIX) {
            if ((domain_list_tmp = fpst_insert_str(domain_list, line,
                                                   (uint32_t) block_type)) == NULL) {
                free(line);
                break;
            }
            domain_list = domain_list_tmp;
        } else if (block_type == BLOCKTYPE_SUBSTRING) {
            if ((domain_substr_list_tmp = fpst_insert_str(domain_substr_list, line,
                                                          (uint32_t) block_type)) == NULL) {
                free(line);
                break;
            }
            domain_substr_list = domain_substr_list_tmp;
        } else {
            free(line);
        }
    }
    if (!feof(fp)) {
        fpst_free(domain_list, free_list);
        fpst_free(domain_rev_list, free_list);
        fpst_free(domain_substr_list, free_list);
    } else {
        *domain_list_p = domain_list;
        *domain_rev_list_p = domain_rev_list;
        *domain_substr_list_p = domain_substr_list;
        ret = 0;
    }
    fclose(fp);

    return ret;
}
Exemple #4
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");
    }
Exemple #5
0
/**
 * \ingroup XBT_replay
 * \brief Registers a function to handle a kind of action
 *
 * Registers a function to handle a kind of action
 * This table is then used by \ref xbt_replay_action_runner
 *
 * The argument of the function is the line describing the action, splitted on spaces with xbt_str_split_quoted()
 *
 * \param action_name the reference name of the action.
 * \param function prototype given by the type: void...(xbt_dynar_t action)
 */
void xbt_replay_action_register(const char *action_name, action_fun function)
{
  char* lowername = str_tolower (action_name);
  xbt_dict_set(xbt_action_funs, lowername, function, NULL);
  xbt_free(lowername);
}
Exemple #6
0
/** \ingroup XBT_replay
 * \brief Unregisters a function, which handled a kind of action
 *
 * \param action_name the reference name of the action.
 */
void xbt_replay_action_unregister(const char *action_name)
{
  char* lowername = str_tolower (action_name);
  xbt_dict_remove(xbt_action_funs, lowername);
  xbt_free(lowername);
}
Exemple #7
0
static void download_one_url(const char *url)
{
	bool use_proxy;                 /* Use proxies if env vars are set  */
	int redir_limit;
	len_and_sockaddr *lsa;
	FILE *sfp;                      /* socket to web/ftp server         */
	FILE *dfp;                      /* socket to ftp server (data)      */
	char *proxy = NULL;
	char *fname_out_alloc;
	struct host_info server;
	struct host_info target;

	server.allocated = NULL;
	target.allocated = NULL;
	server.user = NULL;
	target.user = NULL;

	parse_url(url, &target);

	/* Use the proxy if necessary */
	use_proxy = (strcmp(G.proxy_flag, "off") != 0);
	if (use_proxy) {
		proxy = getenv(target.is_ftp ? "ftp_proxy" : "http_proxy");
		use_proxy = (proxy && proxy[0]);
		if (use_proxy)
			parse_url(proxy, &server);
	}
	if (!use_proxy) {
		server.port = target.port;
		if (ENABLE_FEATURE_IPV6) {
			//free(server.allocated); - can't be non-NULL
			server.host = server.allocated = xstrdup(target.host);
		} else {
			server.host = target.host;
		}
	}

	if (ENABLE_FEATURE_IPV6)
		strip_ipv6_scope_id(target.host);

	/* If there was no -O FILE, guess output filename */
	fname_out_alloc = NULL;
	if (!(option_mask32 & WGET_OPT_OUTNAME)) {
		G.fname_out = bb_get_last_path_component_nostrip(target.path);
		/* handle "wget http://kernel.org//" */
		if (G.fname_out[0] == '/' || !G.fname_out[0])
			G.fname_out = (char*)"index.html";
		/* -P DIR is considered only if there was no -O FILE */
		if (G.dir_prefix)
			G.fname_out = fname_out_alloc = concat_path_file(G.dir_prefix, G.fname_out);
		else {
			/* redirects may free target.path later, need to make a copy */
			G.fname_out = fname_out_alloc = xstrdup(G.fname_out);
		}
	}
#if ENABLE_FEATURE_WGET_STATUSBAR
	G.curfile = bb_get_last_path_component_nostrip(G.fname_out);
#endif

	/* Determine where to start transfer */
	G.beg_range = 0;
	if (option_mask32 & WGET_OPT_CONTINUE) {
		G.output_fd = open(G.fname_out, O_WRONLY);
		if (G.output_fd >= 0) {
			G.beg_range = xlseek(G.output_fd, 0, SEEK_END);
		}
		/* File doesn't exist. We do not create file here yet.
		 * We are not sure it exists on remote side */
	}

	redir_limit = 5;
 resolve_lsa:
	lsa = xhost2sockaddr(server.host, server.port);
	if (!(option_mask32 & WGET_OPT_QUIET)) {
		char *s = xmalloc_sockaddr2dotted(&lsa->u.sa);
		fprintf(stderr, "Connecting to %s (%s)\n", server.host, s);
		free(s);
	}
 establish_session:
	/*G.content_len = 0; - redundant, got_clen = 0 is enough */
	G.got_clen = 0;
	G.chunked = 0;
	if (use_proxy || !target.is_ftp) {
		/*
		 *  HTTP session
		 */
		char *str;
		int status;


		/* Open socket to http server */
		sfp = open_socket(lsa);

		/* Send HTTP request */
		if (use_proxy) {
			fprintf(sfp, "GET %stp://%s/%s HTTP/1.1\r\n",
				target.is_ftp ? "f" : "ht", target.host,
				target.path);
		} else {
			if (option_mask32 & WGET_OPT_POST_DATA)
				fprintf(sfp, "POST /%s HTTP/1.1\r\n", target.path);
			else
				fprintf(sfp, "GET /%s HTTP/1.1\r\n", target.path);
		}

		fprintf(sfp, "Host: %s\r\nUser-Agent: %s\r\n",
			target.host, G.user_agent);

		/* Ask server to close the connection as soon as we are done
		 * (IOW: we do not intend to send more requests)
		 */
		fprintf(sfp, "Connection: close\r\n");

#if ENABLE_FEATURE_WGET_AUTHENTICATION
		if (target.user) {
			fprintf(sfp, "Proxy-Authorization: Basic %s\r\n"+6,
				base64enc(target.user));
		}
		if (use_proxy && server.user) {
			fprintf(sfp, "Proxy-Authorization: Basic %s\r\n",
				base64enc(server.user));
		}
#endif

		if (G.beg_range != 0)
			fprintf(sfp, "Range: bytes=%"OFF_FMT"u-\r\n", G.beg_range);

#if ENABLE_FEATURE_WGET_LONG_OPTIONS
		if (G.extra_headers)
			fputs(G.extra_headers, sfp);

		if (option_mask32 & WGET_OPT_POST_DATA) {
			fprintf(sfp,
				"Content-Type: application/x-www-form-urlencoded\r\n"
				"Content-Length: %u\r\n"
				"\r\n"
				"%s",
				(int) strlen(G.post_data), G.post_data
			);
		} else
#endif
		{
			fprintf(sfp, "\r\n");
		}

		fflush(sfp);

		/*
		 * Retrieve HTTP response line and check for "200" status code.
		 */
 read_response:
		fgets_and_trim(sfp);

		str = G.wget_buf;
		str = skip_non_whitespace(str);
		str = skip_whitespace(str);
		// FIXME: no error check
		// xatou wouldn't work: "200 OK"
		status = atoi(str);
		switch (status) {
		case 0:
		case 100:
			while (gethdr(sfp) != NULL)
				/* eat all remaining headers */;
			goto read_response;
		case 200:
/*
Response 204 doesn't say "null file", it says "metadata
has changed but data didn't":

"10.2.5 204 No Content
The server has fulfilled the request but does not need to return
an entity-body, and might want to return updated metainformation.
The response MAY include new or updated metainformation in the form
of entity-headers, which if present SHOULD be associated with
the requested variant.

If the client is a user agent, it SHOULD NOT change its document
view from that which caused the request to be sent. This response
is primarily intended to allow input for actions to take place
without causing a change to the user agent's active document view,
although any new or updated metainformation SHOULD be applied
to the document currently in the user agent's active view.

The 204 response MUST NOT include a message-body, and thus
is always terminated by the first empty line after the header fields."

However, in real world it was observed that some web servers
(e.g. Boa/0.94.14rc21) simply use code 204 when file size is zero.
*/
		case 204:
			if (G.beg_range != 0) {
				/* "Range:..." was not honored by the server.
				 * Restart download from the beginning.
				 */
				reset_beg_range_to_zero();
			}
			break;
		case 300:  /* redirection */
		case 301:
		case 302:
		case 303:
			break;
		case 206: /* Partial Content */
			if (G.beg_range != 0)
				/* "Range:..." worked. Good. */
				break;
			/* Partial Content even though we did not ask for it??? */
			/* fall through */
		default:
			bb_error_msg_and_die("server returned error: %s", sanitize_string(G.wget_buf));
		}

		/*
		 * Retrieve HTTP headers.
		 */
		while ((str = gethdr(sfp)) != NULL) {
			static const char keywords[] ALIGN1 =
				"content-length\0""transfer-encoding\0""location\0";
			enum {
				KEY_content_length = 1, KEY_transfer_encoding, KEY_location
			};
			smalluint key;

			/* gethdr converted "FOO:" string to lowercase */

			/* strip trailing whitespace */
			char *s = strchrnul(str, '\0') - 1;
			while (s >= str && (*s == ' ' || *s == '\t')) {
				*s = '\0';
				s--;
			}
			key = index_in_strings(keywords, G.wget_buf) + 1;
			if (key == KEY_content_length) {
				G.content_len = BB_STRTOOFF(str, NULL, 10);
				if (G.content_len < 0 || errno) {
					bb_error_msg_and_die("content-length %s is garbage", sanitize_string(str));
				}
				G.got_clen = 1;
				continue;
			}
			if (key == KEY_transfer_encoding) {
				if (strcmp(str_tolower(str), "chunked") != 0)
					bb_error_msg_and_die("transfer encoding '%s' is not supported", sanitize_string(str));
				G.chunked = 1;
			}
			if (key == KEY_location && status >= 300) {
				if (--redir_limit == 0)
					bb_error_msg_and_die("too many redirections");
				fclose(sfp);
				if (str[0] == '/') {
					free(target.allocated);
					target.path = target.allocated = xstrdup(str+1);
					/* lsa stays the same: it's on the same server */
				} else {
					parse_url(str, &target);
					if (!use_proxy) {
						free(server.allocated);
						server.allocated = NULL;
						server.host = target.host;
						/* strip_ipv6_scope_id(target.host); - no! */
						/* we assume remote never gives us IPv6 addr with scope id */
						server.port = target.port;
						free(lsa);
						goto resolve_lsa;
					} /* else: lsa stays the same: we use proxy */
				}
				goto establish_session;
			}
		}
//		if (status >= 300)
//			bb_error_msg_and_die("bad redirection (no Location: header from server)");

		/* For HTTP, data is pumped over the same connection */
		dfp = sfp;

	} else {
Exemple #8
0
FILE *start_wget(char *url, int *total)
{
	char buf[512];
	struct host_info server, target;
	len_and_sockaddr *lsa;
	int redir_limit;
#if ENABLE_FEATURE_WGET_LONG_OPTIONS
	char *post_data;
	char *extra_headers = NULL;
	llist_t *headers_llist = NULL;
#endif
	FILE *sfp;                      /* socket to web/ftp server         */
	int use_proxy = 0;              /* Use proxies if env vars are set  */
	const char *user_agent = "Wget";/* "User-Agent" header field        */
	struct globals state;
	char *str;
	int status;
    bzero(&state, sizeof(state));

	static const char keywords[] =
		"content-length\0""transfer-encoding\0""chunked\0""location\0";
	enum {
		KEY_content_length = 1, KEY_transfer_encoding, KEY_chunked, KEY_location
	};

	target.user = NULL;
	parse_url(url, &target);

	state.timeout_seconds = 900;
	server.port = target.port;
	server.host = target.host;

#if 0
	if (opt & WGET_OPT_CONTINUE) {
		output_fd = open(fname_out, O_WRONLY);
		if (output_fd >= 0) {
			state.beg_range = xlseek(output_fd, 0, SEEK_END);
		}
		/* File doesn't exist. We do not create file here yet.
		 * We are not sure it exists on remove side */
	}
#endif

	redir_limit = 5;
 resolve_lsa:
	lsa = xhost2sockaddr(server.host, server.port);
 establish_session:
	/*
	 *  HTTP session
	 */

	/* Open socket to http server */
	sfp = open_socket(lsa);
	if (!sfp) {
		ERROR("Couldn't connect to %s:%d", server.host, server.port);
		return NULL;
	}

	/* Send HTTP request */
	fprintf(sfp, "GET /%s HTTP/1.1\r\n", target.path);

	fprintf(sfp, "Host: %s\r\nUser-Agent: %s\r\n",
		target.host, user_agent);

	/* Ask server to close the connection as soon as we are done
	 * (IOW: we do not intend to send more requests)
	 */
	fprintf(sfp, "Connection: close\r\n");

	if (state.beg_range)
		fprintf(sfp, "Range: bytes=%lu-\r\n", state.beg_range);

	fprintf(sfp, "\r\n");
	fflush(sfp);


	/*
	 * Retrieve HTTP response line and check for "200" status code.
	 */
 read_response:
	if (fgets(buf, sizeof(buf), sfp) == NULL)
		ERROR("no response from server");

	str = buf;
	str = skip_non_whitespace(str);
	str = skip_whitespace(str);
	// FIXME: no error check
	// xatou wouldn't work: "200 OK"
	status = atoi(str);
	switch (status) {
	case 0:
	case 100:
		while (gethdr(buf, sizeof(buf), sfp /*, &n*/) != NULL)
			/* eat all remaining headers */;
		goto read_response;
	case 200:
/*
Response 204 doesn't say "null file", it says "metadata
has changed but data didn't":

"10.2.5 204 No Content
The server has fulfilled the request but does not need to return
an entity-body, and might want to return updated metainformation.
The response MAY include new or updated metainformation in the form
of entity-headers, which if present SHOULD be associated with
the requested variant.

If the client is a user agent, it SHOULD NOT change its document
view from that which caused the request to be sent. This response
is primarily intended to allow input for actions to take place
without causing a change to the user agent's active document view,
although any new or updated metainformation SHOULD be applied
to the document currently in the user agent's active view.

The 204 response MUST NOT include a message-body, and thus
is always terminated by the first empty line after the header fields."

However, in real world it was observed that some web servers
(e.g. Boa/0.94.14rc21) simply use code 204 when file size is zero.
*/
	case 204:
		break;
	case 300:  /* redirection */
	case 301:
	case 302:
	case 303:
		break;
	case 206:
		if (state.beg_range)
			break;
		/* fall through */
	default:
		ERROR("server returned error: %s", sanitize_string(buf));
	}

	/*
	 * Retrieve HTTP headers.
	 */
	while ((str = gethdr(buf, sizeof(buf), sfp /*, &n*/)) != NULL) {
		/* gethdr converted "FOO:" string to lowercase */
		smalluint key;
		/* strip trailing whitespace */
		char *s = strchrnul(str, '\0') - 1;
		while (s >= str && (*s == ' ' || *s == '\t')) {
			*s = '\0';
			s--;
		}
		key = index_in_strings(keywords, buf) + 1;
		if (key == KEY_content_length) {
			state.content_len = strtoul(str, NULL, 10);
			state.total_len   = strtoul(str, NULL, 10);
			if (state.content_len < 0 || errno) {
				ERROR("content-length %s is garbage", sanitize_string(str));
			}
			state.got_clen = 1;
			continue;
		}
		if (key == KEY_transfer_encoding) {
			if (index_in_strings(keywords, str_tolower(str)) + 1 != KEY_chunked)
				ERROR("transfer encoding '%s' is not supported", sanitize_string(str));
			state.chunked = state.got_clen = 1;
		}
		if (key == KEY_location && status >= 300) {
			if (--redir_limit == 0)
				ERROR("too many redirections");
			fclose(sfp);
			state.got_clen = 0;
			state.chunked = 0;
			if (str[0] == '/')
				/* free(target.allocated); */
				target.path = /* target.allocated = */ strdup(str+1);
				/* lsa stays the same: it's on the same server */
			else {
				parse_url(str, &target);
				if (!use_proxy) {
					server.host = target.host;
					server.port = target.port;
					free(lsa);
					goto resolve_lsa;
				} /* else: lsa stays the same: we use proxy */
			}
			goto establish_session;
		}
	}
//		if (status >= 300)
//			ERROR("bad redirection (no Location: header from server)");


	if (total)
		*total = state.content_len;
	ndelay_off(fileno(sfp));
	clearerr(sfp);
	return sfp;
#if 0
	if (retrieve_file_data(&state, sfp, progress, handle, data))
		return -1;
	handle(data, NULL, 0);

	return EXIT_SUCCESS;
#endif
}
Exemple #9
0
static void parse_file_list(FileData *file_data, int num_paths, const char *lsfile, const char *path_dir, AccessMethod method, int host)
{
	FileState *file_state = NULL;
	FILE *fp;
	char *path_file;
	char *temp;
	char *text;

	char *name;
	time_t time;
	off_t size;
	mode_t mode;
	int type;

	char *ssh_command;
	int num_files = 0;

	fp = fopen(lsfile, "r");
	if (fp == NULL) {
		perror("fopen");
		fprintf(stderr, _("Cannot open file `%s'.\n"), lsfile);
		fatal_error(host);
	}

	while ((text = str_fgets(fp)) != NULL) {
		if (strncmp(text, "total", 5) == 0) { /* skip */
			free(text);
			continue;
		}
		if (strncmp(text, "/bin/ls:", 8) == 0) {
			fprintf(stderr, _("Listing remote directory contents failed: %s\nThe directory doesn't exist or permission denied.\n"), path_dir);
			fatal_error(host);
		}

		switch (method) {
		case FTP:
			ftp_extract_file_status(text, &name, &size, &mode, &type, host);
			break;
		case SCP:
		case RSYNC:
			ssh_extract_file_status(text, &name, &time, &size, &mode, &type, host);
			break;
		default:
			internal_error(__FILE__, __LINE__);
		} 
		free(text);

		if (strcmp(name, ".") == 0 || strcmp(name, "..") == 0) {
			free(name);
			continue;
		}

		path_file = str_concat(path_dir, "/", name, NULL);

		if (type == 'l') { /* Check whether the symbolic link is directory or not. */
			switch (method) {
			case FTP:
				type = ftp_chdir(path_file) ? 'd' : '-';
				break;
			case SCP:
			case RSYNC:
				ssh_command = str_dup_printf("ssh %s@%s cd %s", config.login_name[host], config.host_name[host], path_file);
				type = (system(ssh_command) == 0) ? 'd' : '-';
				free(ssh_command);
				break;
			default:
				internal_error(__FILE__, __LINE__);
			}
		}

		if ((type == 'd' && is_match_dir(path_file, config.ignore_remote_dir[host], host)) ||
		    (type != 'd' && (is_match_file(path_file, path_dir, config.ignore_remote_file[host], host) ||
				     is_match_file(path_file, path_dir, config.ignore_file[host], host)))) {
			free(path_file);
			free(name);
			continue;
		}

		if (config.conv_to_lower[host]) {
			temp = str_tolower(name);
			free(name);
			name = temp;

			free(path_file);
			path_file = str_concat(path_dir, "/", name, NULL);
		}

		if (method == FTP) {
			if (type != 'd') {
				time = ftp_get_last_modification_time(path_file, host);
			} else {
				time = 0;
			}
		}

                file_state = str_realloc(file_state, (num_files + 1) * sizeof(FileState));
		file_state[num_files].name = name;
		file_state[num_files].time = time;
		file_state[num_files].size = size;
		file_state[num_files].mode = mode;
		file_state[num_files].isdir = (type == 'd');
		file_state[num_files].isremoved = FALSE;

		num_files++;

		free(path_file);
	}

	if (fclose(fp) != 0) {
		perror("fclose");
		fprintf(stderr, _("Cannot close file `%s'.\n"), lsfile);
		fatal_error(host);
        }

	sort_file_state(file_state, num_files);

	file_data->path_state[num_paths].num_files = num_files;
	file_data->path_state[num_paths].file_state = file_state;
}
Exemple #10
0
/* Creates a tree model containing the completions */
void _search_entry(sview_search_info_t *sview_search_info)
{
	int id = 0;
	char title[100];
	ListIterator itr = NULL;
	popup_info_t *popup_win = NULL;
	GError *error = NULL;
	char *upper = NULL, *lower = NULL;
	char *type;

	if (cluster_flags & CLUSTER_FLAG_BG)
		type = "Midplane";
	else
		type = "Node";

	if (sview_search_info->int_data == NO_VAL &&
	    (!sview_search_info->gchar_data
	     || !strlen(sview_search_info->gchar_data))) {
		g_print("nothing given to search for.\n");
		return;
	}

	switch(sview_search_info->search_type) {
	case SEARCH_JOB_STATE:
		id = JOB_PAGE;
		upper = job_state_string(sview_search_info->int_data);
		lower = str_tolower(upper);
		snprintf(title, 100, "Job(s) in the %s state", lower);
		xfree(lower);
		break;
	case SEARCH_JOB_ID:
		id = JOB_PAGE;
		snprintf(title, 100, "Job %s info",
			 sview_search_info->gchar_data);
		break;
	case SEARCH_JOB_USER:
		id = JOB_PAGE;
		snprintf(title, 100, "Job(s) info for user %s",
			 sview_search_info->gchar_data);
		break;
	case SEARCH_BLOCK_STATE:
		id = BLOCK_PAGE;
		upper = bg_block_state_string(sview_search_info->int_data);
		lower = str_tolower(upper);
		snprintf(title, 100, "BG Block(s) in the %s state", lower);
		xfree(lower);
		break;
	case SEARCH_BLOCK_NAME:
		id = BLOCK_PAGE;
		snprintf(title, 100, "Block %s info",
			 sview_search_info->gchar_data);
		break;
	case SEARCH_BLOCK_SIZE:
		id = BLOCK_PAGE;
		sview_search_info->int_data =
			revert_num_unit(sview_search_info->gchar_data);
		if (sview_search_info->int_data == -1)
			return;
		snprintf(title, 100, "Block(s) of size %d cnodes",
			 sview_search_info->int_data);
		break;
	case SEARCH_PARTITION_NAME:
		id = PART_PAGE;
		snprintf(title, 100, "Partition %s info",
			 sview_search_info->gchar_data);
		break;
	case SEARCH_PARTITION_STATE:
		id = PART_PAGE;
		if (sview_search_info->int_data)
			snprintf(title, 100, "Partition(s) that are up");
		else
			snprintf(title, 100, "Partition(s) that are down");
		break;
	case SEARCH_NODE_NAME:
		id = NODE_PAGE;
		snprintf(title, 100, "%s(s) %s info",
			 type, sview_search_info->gchar_data);
		break;
	case SEARCH_NODE_STATE:
		id = NODE_PAGE;
		upper = node_state_string(sview_search_info->int_data);
		lower = str_tolower(upper);
		snprintf(title, 100, "%s(s) in the %s state",
			 type, lower);
		xfree(lower);

		break;
	case SEARCH_RESERVATION_NAME:
		id = RESV_PAGE;
		snprintf(title, 100, "Reservation %s info",
			 sview_search_info->gchar_data);
		break;
	default:
		g_print("unknown search type %d.\n",
			sview_search_info->search_type);

		return;
	}

	itr = list_iterator_create(popup_list);
	while ((popup_win = list_next(itr))) {
		if (popup_win->spec_info)
			if (!strcmp(popup_win->spec_info->title, title)) {
				break;
			}
	}
	list_iterator_destroy(itr);

	if (!popup_win) {
		popup_win = create_popup_info(id, id, title);
	} else {
		gtk_window_present(GTK_WINDOW(popup_win->popup));
		return;
	}
	memcpy(popup_win->spec_info->search_info, sview_search_info,
	       sizeof(sview_search_info_t));

	if (!sview_thread_new((gpointer)popup_thr, popup_win, FALSE, &error)) {
		g_printerr ("Failed to create main popup thread: %s\n",
			    error->message);
		return;
	}
	return;
}
Exemple #11
0
/* ---------------------------------------------------------------------- */
int
spread_row_to_solution (struct spread_row *heading, struct spread_row *units,
			struct spread_row *data, struct defaults defaults)
/* ---------------------------------------------------------------------- */
{
  int i, j, n, l, next_keyword_save;
  int n_user, n_user_end;
  int default_pe, alk;
  int count_isotopes;
  int max_mass_balance, count_mass_balance;
  char *ptr, *ptr1;
  char *description;
  char token[MAX_LENGTH], token1[MAX_LENGTH];
  char string[2 * MAX_LENGTH];
  LDBLE dummy;

  int return_value, opt;
  char *next_char;
  const char *opt_list[] = {
    "temp",			/* 0 */
    "temperature",		/* 1 */
    "dens",			/* 2 */
    "density",			/* 3 */
    "units",			/* 4 */
    "redox",			/* 5 */
    "ph",			/* 6 */
    "pe",			/* 7 */
    "unit",			/* 8 */
    "isotope",			/* 9 */
    "water",			/* 10 */
    "description",		/* 11 */
    "desc",			/* 12 */
    "descriptor"		/* 13 */
  };
  int count_opt_list = 14;

/*
 *      look for solution number
 */
  n_user = -1;
  n_user_end = -1;
  description = string_duplicate ("");
  for (i = 0; i < heading->count; i++)
  {
    if (strcmp_nocase (heading->char_vector[i], "number") == 0)
    {
      break;
    }
  }
  if (i == heading->count || data->type_vector[i] == EMPTY
      || data->count <= i)
  {
    n_user = -1;
#ifdef SKIP
    for (i = 0; i < count_solution; i++)
    {
      if (n_user <= solution[i]->n_user)
      {
	n_user = solution[i]->n_user + 1;
      }
    }
#endif
  }
  else if (data->type_vector[i] == STRING)
  {
    input_error++;
    sprintf (error_string,
	     "Expected solution number or number range in 'number' column, found:  %s.",
	     data->char_vector[i]);
    error_msg (error_string, CONTINUE);
  }
  else
  {
    strcpy (string, "solution_s ");
    strcat (string, data->char_vector[i]);
    ptr = string;
    description = (char *) free_check_null (description);
    next_keyword_save = next_keyword;
    next_keyword = 42;
    read_number_description (ptr, &n_user, &n_user_end, &description);
    next_keyword = next_keyword_save;
  }
/*
 *   set up solution
 */

  if (n_user >= 0 && solution_bsearch (n_user, &n, FALSE) != NULL)
  {
    solution_free (solution[n]);
  }
  else
  {
    n = count_solution++;
    if (count_solution >= max_solution)
    {
      space ((void **) ((void *) &(solution)), count_solution, &max_solution,
	     sizeof (struct solution *));
    }
  }
  solution[n] = solution_alloc ();

  solution[n]->n_user = n_user;
  solution[n]->n_user_end = n_user_end;
  if (use.solution_in == FALSE)
  {
    use.solution_in = TRUE;
    use.n_solution_user = n_user;
  }
  max_mass_balance = MAX_MASS_BALANCE;
/*
 *   Set default ph, temp, density, pe, units
 */
  solution[n]->description = description;
  solution[n]->tc = defaults.temp;
  solution[n]->ph = defaults.ph;
  solution[n]->density = defaults.density;
  solution[n]->solution_pe = defaults.pe;
  solution[n]->mass_water = defaults.water;
  solution[n]->ah2o = 1.0;
  solution[n]->mu = 1e-7;
  solution[n]->cb = 0.0;
  default_pe = 0;
  solution[n]->units = defaults.units;
  solution[n]->totals[0].description = NULL;
  count_mass_balance = 0;
  count_isotopes = 0;
  default_pe = pe_data_store (&(solution[n]->pe), defaults.redox);
/*
 *   Read concentration data
 */
  return_value = UNKNOWN;
  for (i = 0; i < heading->count; i++)
  {
    if (strcmp_nocase (heading->char_vector[i], "number") == 0)
      continue;
    if (strcmp_nocase (heading->char_vector[i], "uncertainty") == 0)
      continue;
    if (strcmp_nocase (heading->char_vector[i], "uncertainties") == 0)
      continue;
    if (strcmp_nocase (heading->char_vector[i], "isotope_uncertainty") == 0)
      continue;
    /*
     *  Copy in element name
     */
    if (heading->type_vector[i] == EMPTY)
      continue;
    strcpy (string, heading->char_vector[i]);
    strcat (string, " ");
    /*
     *  Copy in concentration data
     */
    if (i >= data->count || data->type_vector[i] == EMPTY)
      continue;
    strcat (string, data->char_vector[i]);
    strcat (string, " ");
    /*
     *  Copy in concentration data
     */
    if (units != NULL && i < units->count && units->type_vector[i] != EMPTY)
    {
      strcat (string, units->char_vector[i]);
    }
/*
 *   Parse string just like read_solution input 
 */
    next_char = string;
    opt = get_option_string (opt_list, count_opt_list, &next_char);
    if (opt == OPTION_DEFAULT && heading->type_vector[i] == NUMBER)
    {
      opt = 9;
    }
    switch (opt)
    {
    case OPTION_EOF:		/* end of file */
      return_value = EOF;
      break;
    case OPTION_KEYWORD:	/* keyword */
      return_value = KEYWORD;
      break;
    case OPTION_ERROR:
      input_error++;
      error_msg ("Unknown input in SOLUTION keyword.", CONTINUE);
      error_msg (line_save, CONTINUE);
      break;
    case 0:			/* temperature */
    case 1:
      sscanf (next_char, SCANFORMAT, &(solution[n]->tc));
      break;
    case 2:			/* density */
    case 3:
      sscanf (next_char, SCANFORMAT, &(solution[n]->density));
      break;
    case 4:			/* units */
    case 8:			/* unit */
      if (copy_token (token, &next_char, &l) == EMPTY)
	break;
      if (check_units (token, FALSE, FALSE, solution[n]->units, TRUE) == OK)
      {
	solution[n]->units = string_hsave (token);
      }
      else
      {
	input_error++;
      }
      break;
    case 5:			/* redox */
      if (copy_token (token, &next_char, &l) == EMPTY)
	break;
      if (parse_couple (token) == OK)
      {
	default_pe = pe_data_store (&(solution[n]->pe), token);
      }
      else
      {
	input_error++;
      }
      break;
    case 6:			/* ph */
      next_char = string;
      if (read_conc (n, count_mass_balance, next_char) == ERROR)
      {
	input_error++;
	break;
      }
      solution[n]->ph = solution[n]->totals[count_mass_balance].input_conc;
      if (solution[n]->totals[count_mass_balance].equation_name == NULL)
      {
	break;
      }
      solution[n]->totals[count_mass_balance].description =
	string_hsave ("H(1)");
      count_mass_balance++;
      break;
    case 7:			/* pe */
      next_char = string;
      if (read_conc (n, count_mass_balance, next_char) == ERROR)
      {
	input_error++;
	break;
      }
      solution[n]->solution_pe =
	solution[n]->totals[count_mass_balance].input_conc;
      if (solution[n]->totals[count_mass_balance].equation_name == NULL)
      {
	break;
      }
      solution[n]->totals[count_mass_balance].description =
	string_hsave ("E");
      count_mass_balance++;
      break;
    case 9:			/* isotope */
      next_char = string;
      if (copy_token (token, &next_char, &l) != DIGIT)
      {
	input_error++;
	sprintf (error_string, "Expected isotope name to"
		 " begin with an isotopic number.");
	error_msg (error_string, CONTINUE);
	continue;
      }
      solution[n]->isotopes =
	(struct isotope *) PHRQ_realloc (solution[n]->isotopes,
					 (size_t) (count_isotopes +
						   1) *
					 sizeof (struct isotope));
      if (solution[n]->isotopes == NULL)
	malloc_error ();
      /* read and save element name */
      ptr1 = token;
      get_num (&ptr1,
	       &(solution[n]->isotopes[count_isotopes].isotope_number));
      if (ptr1[0] == '\0' || isupper ((int) ptr1[0]) == FALSE)
      {
	error_msg ("Expecting element name.", CONTINUE);
	error_msg (line_save, CONTINUE);
	input_error++;
	return (ERROR);
      }
      solution[n]->isotopes[count_isotopes].elt_name = string_hsave (ptr1);

      /* read and store isotope ratio */
      if (copy_token (token, &next_char, &l) != DIGIT)
      {
	input_error++;
	sprintf (error_string, "Expected numeric value for isotope ratio.");
	error_msg (error_string, CONTINUE);
	continue;
      }
      sscanf (token, SCANFORMAT,
	      &(solution[n]->isotopes[count_isotopes].ratio));

      /* read and store isotope ratio uncertainty */
      /* first choice is next column */
      if ((i + 1) < heading->count &&
	  (strcmp_nocase (heading->char_vector[i + 1], "uncertainty") == 0 ||
	   strcmp_nocase (heading->char_vector[i + 1],
			  "isotope_uncertainty") == 0
	   || strcmp_nocase (heading->char_vector[i + 1],
			     "uncertainties") == 0) && (i + 1) < data->count
	  && data->type_vector[i + 1] == NUMBER)
      {
	solution[n]->isotopes[count_isotopes].ratio_uncertainty =
	  data->d_vector[i + 1];
      }
      else
      {
	next_char = string;
	copy_token (token, &next_char, &l);
	for (j = 0; j < defaults.count_iso; j++)
	{
	  if (strcmp (token, defaults.iso[j].name) == 0)
	  {
	    solution[n]->isotopes[count_isotopes].ratio_uncertainty =
	      defaults.iso[j].uncertainty;
	    break;
	  }
	}
	if (j == defaults.count_iso)
	{
	  solution[n]->isotopes[count_isotopes].ratio_uncertainty = NAN;
	}
      }
      count_isotopes++;
      break;
    case 10:			/* water */
      j = copy_token (token, &next_char, &l);
      if (j == EMPTY)
      {
	solution[n]->mass_water = 1.0;
      }
      else if (j != DIGIT)
      {
	input_error++;
	sprintf (error_string,
		 "Expected numeric value for mass of water in solution.");
	error_msg (error_string, CONTINUE);
      }
      else
      {
	sscanf (token, SCANFORMAT, &dummy);
	solution[n]->mass_water = (LDBLE) dummy;
      }
      break;
    case 11:			/* description */
    case 12:			/* desc */
    case 13:			/* descriptor */
      solution[n]->description =
	(char *) free_check_null (solution[n]->description);
      solution[n]->description = string_duplicate (next_char);
      break;
    case OPTION_DEFAULT:
/*
 *   Read concentration
 */
      next_char = string;
      if (copy_token (token, &next_char, &l) == LOWER)
	continue;
      next_char = string;
      if (read_conc (n, count_mass_balance, next_char) == ERROR)
      {
#ifdef SKIP
	input_error++;
	break;
#endif
      }
      count_mass_balance++;
      break;
    }
    if (count_mass_balance + 1 >= max_mass_balance)
    {
      space ((void **) ((void *) &(solution[n]->totals)), count_mass_balance + 1,
	     &max_mass_balance, sizeof (struct conc));
    }
    if (return_value == EOF || return_value == KEYWORD)
      break;
  }
/*
 *   Sort totals by description
 */
  qsort (solution[n]->totals,
	 (size_t) count_mass_balance,
	 (size_t) sizeof (struct conc), conc_compare);
/*
 *   fix up default units and default pe
 */
  for (i = 0; i < count_mass_balance; i++)
  {
    strcpy (token, solution[n]->totals[i].description);
    str_tolower (token);
    if (solution[n]->totals[i].units == NULL)
    {
      solution[n]->totals[i].units = solution[n]->units;
    }
    else
    {
      alk = FALSE;
      if (strstr (token, "alk") == token)
	alk = TRUE;
      strcpy (token1, solution[n]->totals[i].units);
      if (check_units (token1, alk, TRUE, solution[n]->units, TRUE) == ERROR)
      {
	input_error++;
      }
      else
      {
	solution[n]->totals[i].units = string_hsave (token1);
      }
    }
    if (solution[n]->totals[i].n_pe < 0)
    {
      solution[n]->totals[i].n_pe = default_pe;
    }
  }
  solution[n]->default_pe = default_pe;
/*
 *   Mark end of solution
 */
  solution[n]->totals[count_mass_balance].description = NULL;
  solution[n]->count_isotopes = count_isotopes;
  if (count_isotopes > 0)
  {
    qsort (solution[n]->isotopes,
	   (size_t) count_isotopes,
	   (size_t) sizeof (struct isotope), isotope_compare);
  }
  else
  {
    solution[n]->isotopes =
      (struct isotope *) free_check_null (solution[n]->isotopes);
  }
  return (return_value);
}
Exemple #12
0
static void write_cf(void)
{
	char tmp[0x100], rv[0x40];
	struct conf_item *ci = NULL;
	char *lp, *cp;
	int add, i;
	char *cfname = get_confname();
	int cfld = ll_create();
	FILE *fd = fopen(cfname, "w");

	if (fd == NULL)
		err_sys("failed to open configuration file '%s'", cfname);

	for (ll_reset(conf_items); (ci = ll_getall(conf_items)); ) {
		if (ci->type != t_sep && ci->type != t_func &&
		    (!ci->dep || (ci->dep && *ci->dep))) {
			switch (ci->type) {
			case t_int:
				sprintf(rv, "%d", *ci->v.i);
				break;
			case t_list:
				if (!argv_count(ci->list))
					continue;
				sprintf(rv, "%s", ci->list[*ci->v.i]);
				str_tolower(rv);
				break;
			case t_sep:
			case t_func:
				break;
			}

			add = 1;

			for (i = 0; i < ll_size(cfld); i++) {
				lp = ll_get(cfld, i);
				cp = lp += strspn(lp, " ");
				if (!strncasecmp(cp, ci->cfname, strcspn(cp, " ="))
				    && strlen(ci->cfname) == strcspn(cp, " =")) {
					add = 0;
					cp += strcspn(cp, "=") + 1;
					cp += strspn(cp, " ");
					strncpy(tmp, cp, strcspn(cp, " #\n"));
					if (strcasecmp(tmp, rv)) {
						strncpy(tmp, lp, strcspn(lp, " ="));
						tmp[strcspn(lp, " =")] = '\0';
						strcat(tmp, " = ");
						strcat(tmp, rv);
						strcat(tmp, "\n");
						ll_replace(cfld, i, "s", tmp);
					}
				}
			}

			if (add) {
				strcpy(tmp, ci->cfname);
				strcat(tmp, " = ");
				strcat(tmp, rv);
				strcat(tmp, "\n");
				ll_push(cfld, "s", tmp);
			}
		}
	}

	for (ll_reset(cfld); (lp = ll_getall(cfld)); )
		fputs(lp, fd);
	fclose(fd);

	ll_destroy(cfld);
	free(cfname);
}
Exemple #13
0
int		main(int argc, char **argv)
{
	if (argc != 2)
	{
		ft_putchar('\n');
		return (0);
	}
	int words;
	int i;
	int x;
	int h;
	int trie;

	words = count_words(argv[1]);
	t_elem *tab = malloc(sizeof(t_elem) * words);
	i = 0;
	x = -1;
	h = 0;
	while (argv[1][i])
	{
		while (argv[1][i] && (argv[1][i] == ' ' || argv[1][i] == '\t'))
			i++;	
		if (argv[1][i])
		{
			x++;
			h = i;
		}
		while (argv[1][h] && argv[1][h] != ' ' && argv[1][h] != '\t')
			h++;
		tab[x].str =ft_strsub(argv[1], i, h - i);
		tab[x].strlow = str_tolower(ft_strsub(argv[1], i, h - i));
		tab[x].pos = x;
		tab[x].len = ft_strlen(tab[x].str);
		i = h;
	}
	x = 0;
	trie = 0;
	t_elem temp;
	while (!trie)
	{
		x = 0;
		trie = 1;
		while (x < words - 1)
		{	
			if (tab[x].len > tab[x + 1].len)
			{
				temp = tab[x];
				tab[x] = tab[x + 1];
				tab[x + 1] = temp;
				trie = 0;
			}	
			x++;
		}
	}
	x = 0;
	trie = 0;
	while (!trie)
	{
		x = 0;
		trie = 1;
		while (x < words -1)
		{
			if (tab[x].len == tab[x + 1].len && ft_strcmp(tab[x].strlow, tab[x + 1].strlow) > 0)
			{
				temp = tab[x];
				tab[x] = tab[x + 1];
				tab[x + 1] = temp;
				trie = 0;	
			}
			x++;
		}
	}
	trie = 0;
	while(!trie)
	{
		x = 0;
		trie = 1;
		while (x < words - 1)
		{
			if (tab[x].len == tab[x + 1].len && ft_strcmp(tab[x].strlow, tab[x + 1].strlow) == 0)
			{
				if (tab[x].pos > tab[x + 1].pos)
				{
					temp = tab[x];
					tab[x] = tab[x + 1];
					tab[x + 1] = temp;
					trie = 0;
					ft_putchar('c');
				}
			}
			x++;
		}
	}
	Dprinttab(tab, words);

	return (0);
}
void mutt_FormatString (char *dest,     /* output buffer */
                        size_t destlen, /* output buffer len */
                        const char *src,        /* template string */
                        format_t * callback,    /* callback for processing */
                        unsigned long data,     /* callback data */
                        format_flag flags)
{                               /* callback flags */
  char prefix[SHORT_STRING], buf[LONG_STRING], *cp, *wptr = dest, ch;
  char ifstring[SHORT_STRING], elsestring[SHORT_STRING];
  size_t wlen, count, len, col, wid;

  prefix[0] = '\0';
  destlen--;                    /* save room for the terminal \0 */
  wlen = (flags & M_FORMAT_ARROWCURSOR && option (OPTARROWCURSOR)) ? 3 : 0;
  col = wlen;

  while (*src && wlen < destlen) {
    if (*src == '%') {
      if (*++src == '%') {
        *wptr++ = '%';
        wlen++;
        col++;
        src++;
        continue;
      }

      if (*src == '?') {
        flags |= M_FORMAT_OPTIONAL;
        src++;
      }
      else {
        flags &= ~M_FORMAT_OPTIONAL;

        /* eat the format string */
        cp = prefix;
        count = 0;
        while (count < sizeof (prefix) &&
               (isdigit ((unsigned char) *src) || *src == '.' || *src == '-'))
        {
          *cp++ = *src++;
          count++;
        }
        *cp = 0;
      }

      if (!*src)
        break;                  /* bad format */

      ch = *src++;              /* save the character to switch on */

      if (flags & M_FORMAT_OPTIONAL) {
        if (*src != '?')
          break;                /* bad format */
        src++;

        /* eat the `if' part of the string */
        cp = ifstring;
        count = 0;
        while (count < sizeof (ifstring) && *src && *src != '?'
               && *src != '&') {
          *cp++ = *src++;
          count++;
        }
        *cp = 0;

        /* eat the `else' part of the string (optional) */
        if (*src == '&')
          src++;                /* skip the & */
        cp = elsestring;
        count = 0;
        while (count < sizeof (elsestring) && *src && *src != '?') {
          *cp++ = *src++;
          count++;
        }
        *cp = 0;

        if (!*src)
          break;                /* bad format */

        src++;                  /* move past the trailing `?' */
      }

      /* handle generic cases first */
      if (ch == '>') {
        /* right justify to EOL */
        ch = *src++;            /* pad char */
        /* calculate space left on line.  if we've already written more data
           than will fit on the line, ignore the rest of the line */
        if (DrawFullLine || option (OPTSTATUSONTOP))
          count = (COLS < destlen ? COLS : destlen);
        else
          count = ((COLS - SW) < destlen ? (COLS - SW) : destlen);
        if (count > col) {
          count -= col;         /* how many columns left on this line */
          mutt_FormatString (buf, sizeof (buf), src, callback, data, flags);
          wid = str_len (buf);
          if (count > wid) {
            count -= wid;       /* how many chars to pad */
            memset (wptr, ch, count);
            wptr += count;
            col += count;
          }
          if (wid + wlen > destlen)
            len = destlen - wlen;
          else
            len = wid;
          memcpy (wptr, buf, len);
          wptr += len;
          wlen += len;
          col += mutt_strwidth (buf);
        }
        break;                  /* skip rest of input */
      }
      else if (ch == '|') {
        /* pad to EOL */
        ch = *src++;
        if (destlen > COLS)
          destlen = COLS;
        if (destlen > wlen) {
          count = destlen - wlen;
          memset (wptr, ch, count);
          wptr += count;
        }
        break;                  /* skip rest of input */
      }
      else {
        short tolower = 0;
        short nodots = 0;

        while (ch == '_' || ch == ':') {
          if (ch == '_')
            tolower = 1;
          else if (ch == ':')
            nodots = 1;

          ch = *src++;
        }

        /* use callback function to handle this case */
        src =
          callback (buf, sizeof (buf), ch, src, prefix, ifstring, elsestring,
                    data, flags);

        if (tolower)
          str_tolower (buf);
        if (nodots) {
          char *p = buf;

          for (; *p; p++)
            if (*p == '.')
              *p = '_';
        }

        if ((len = str_len (buf)) + wlen > destlen)
          len = (destlen - wlen > 0) ? (destlen - wlen) : 0;

        memcpy (wptr, buf, len);
        wptr += len;
        wlen += len;
        col += mutt_strwidth (buf);
      }
    }
    else if (*src == '\\') {
      if (!*++src)
        break;
      switch (*src) {
      case 'n':
        *wptr = '\n';
        break;
      case 't':
        *wptr = '\t';
        break;
      case 'r':
        *wptr = '\r';
        break;
      case 'f':
        *wptr = '\f';
        break;
      case 'v':
        *wptr = '\v';
        break;
      default:
        *wptr = *src;
        break;
      }
      src++;
      wptr++;
      wlen++;
      col++;
    }
    else {
      unsigned int bar = mutt_skipchars (src, "%\\");
      char *bar2 = mem_malloc (bar + 1);

      strfcpy (bar2, src, bar + 1);
      while (bar--) {
        *wptr++ = *src++;
        wlen++;
      }
      col += mutt_strwidth (bar2);
      mem_free (&bar2);
    }
  }
  *wptr = 0;

#if 0
  if (flags & M_FORMAT_MAKEPRINT) {
    /* Make sure that the string is printable by changing all non-printable
       chars to dots, or spaces for non-printable whitespace */
    for (cp = dest; *cp; cp++)
      if (!IsPrint (*cp) && !((flags & M_FORMAT_TREE) && (*cp <= M_TREE_MAX)))
        *cp = isspace ((unsigned char) *cp) ? ' ' : '.';
  }
#endif
}
Exemple #15
0
int main(int argc, char **argv)
{
    SDDS_TABLE SDDS_table;
    SCANNED_ARG *scanned;
    long i, i_arg, index, points, lsb_first, bytes_per_number;
    char *input, *output, buffer[BUFSIZE];
    char *signal_name, *ptr, *parameter_name;
    char *mpl_title, *mpl_topline, *descrip_text, *descrip_contents;
    FILE *fpi;
    long code, binary;
    double xIncrement, xZero, yMultiplier, yZero;
    char *xUnits, *yUnits;
    double *time, *data;
    short columnMajorOrder=0;
    unsigned long majorOrderFlag;
    
    xUnits = yUnits = NULL;

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

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

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

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

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

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

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

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

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

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

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