Esempio n. 1
0
void setupTransmuteElements(NAMELIST_TEXT *nltext, RUN *run, 
			 LINE_LIST *beamline)
{
  long i, j, newType;
  /* process the namelist text */
  set_namelist_processing_flags(STICKY_NAMELIST_DEFAULTS);
  set_print_namelist_flags(0);
  if (processNamelist(&transmute_elements, nltext)==NAMELIST_ERROR)
    bombElegant(NULL, NULL);
  if (echoNamelists) print_namelist(stdout, &transmute_elements);

  if (clear_all) {
    clearTransmutationSpecs();
    if (!name && !type)
      return;
  }
  if (disable)
    return;

  if (!new_type)
    bombElegant("new_type must be given", NULL);
  str_toupper(new_type);
  j = -1;
  for (i=0; i<N_TYPES; i++) {
    if (strncmp(entity_name[i], new_type, strlen(new_type))==0) {
      if (j>=0) 
        bombElegant("new_type matches more than one element type", NULL);
      j = i;
    }
  }
  if (j==-1)
    bombElegant("new_type does not match a known element type", NULL);
  newType = j;
  
  if (!name || !strlen(name))
    bombElegant("no name given", NULL);
  str_toupper(name);
  if (has_wildcards(name) && strchr(name, '-'))
    name = expand_ranges(name);
  if (type) {
    str_toupper(type);
    if (has_wildcards(type) && strchr(type, '-'))
      type = expand_ranges(type);
    for (i=0; i<N_TYPES; i++)
      if (wild_match(entity_name[i], type))
	break;
    if (i==N_TYPES) {
      fprintf(stderr, "type pattern %s does not match any known type", type);
      exitElegant(1);
    }
  }
  if (exclude) {
    str_toupper(exclude);
    if (has_wildcards(exclude) && strchr(exclude, '-'))
      exclude = expand_ranges(exclude);
  }
  
  addTransmutationSpec(name, type, exclude, newType);
}
Esempio n. 2
0
File: lib.c Progetto: sfionov/mc-dev
GString *
mc_search__toupper_case_str (const char *charset, const char *str, gsize str_len)
{
    GString *ret;
#ifdef HAVE_CHARSET
    gchar *converted_str, *tmp_str1, *tmp_str2, *tmp_str3;
    gsize converted_str_len;
    gsize tmp_len;

    if (charset == NULL)
        charset = cp_source;

    tmp_str2 = converted_str =
        mc_search__recode_str (str, str_len, charset, cp_display, &converted_str_len);
    if (converted_str == NULL)
        return NULL;

    tmp_len = converted_str_len + 1;

    tmp_str3 = tmp_str1 = g_strdup (converted_str);

    while (str_toupper (tmp_str1, &tmp_str2, &tmp_len))
        tmp_str1 += str_length_char (tmp_str1);

    g_free (tmp_str3);

    tmp_str2 =
        mc_search__recode_str (converted_str, converted_str_len, cp_display, charset, &tmp_len);
    g_free (converted_str);
    if (tmp_str2 == NULL)
        return NULL;

    ret = g_string_new_len (tmp_str2, tmp_len);
    g_free (tmp_str2);
    return ret;
#else
    const gchar *tmp_str1 = str;
    gchar *converted_str, *tmp_str2;
    gsize converted_str_len = str_len + 1;

    tmp_str2 = converted_str = g_strndup (str, str_len);

    while (str_toupper (tmp_str1, &tmp_str2, &converted_str_len))
        tmp_str1 += str_length_char (tmp_str1);

    ret = g_string_new_len (converted_str, str_len);
    g_free (converted_str);
    return ret;
#endif
}
Esempio n. 3
0
void parse_command_string(char command_name[32], char* command_param, char* to_parse)
{
	// initialize output
	command_name[0] = '\0';
	command_param[0] = '\0';

	char* token = strchr(to_parse, ' ');
	int namelen = 0;

	if(token != NULL)
	{
		// has params
		namelen = token - to_parse;
	}
	else
	{
		// no params
		namelen = strlen(to_parse);
	}

	if(namelen > 32)
	{
		namelen = 32;
	}

	// copy strings
	str_toupper(command_name, to_parse, namelen);

	if(token != NULL)
	{
		strcpy(command_param, token + 1);
	}
}
Esempio n. 4
0
File: process.c Progetto: dcant/zftp
void handle_ftpcmd(session_t *sess)
{
	char buf[MAXCMD] = {0};
	sprintf(buf, "Welcome to zftp!\r\n%d", FTP_READY);
	ftp_cmdio_write_m(sess->ctrl_fd, FTP_READY, buf);
	while (1) {
		start_signal_alarm_ctrl();
		_reset_session_cmd(sess);

		int ret = ftp_cmdio_get_cmd_args(sess->ctrl_fd, sess->ftp_cmd_line,
			MAXCMD);
		if (ret == -1) {
			if (errno == EINTR)
				continue;
			ERROR_EXIT("ftp_cmdio_get_cmd_args");
		} else if (ret == 0)
			exit(0);

		str_trim_crlf(sess->ftp_cmd_line);
		str_split(sess->ftp_cmd_line, sess->ftp_cmd_op,
			sess->ftp_cmd_arg, ' ');
		str_toupper(sess->ftp_cmd_op);

		_handle_map(sess);
	}
}
Esempio n. 5
0
void fn_toupper (char *s)
/*
** Convert file to upper case
** ignoring directory path head
*/
{
    str_toupper(fn_tail(s));
}
Esempio n. 6
0
int main(int argc, char *argv[])
{
    char t[255]="alphaBETA";
    str_toupper(t);
    printf("uppercase: %s\n", t);
    str_tolower(t);
    printf("lowercase: %s\n", t);
    return 0;
}
Esempio n. 7
0
int main(void)
{
  const char *s = "ABCD1234EFGHXXXX";
  const char *t = "ABCD1234EFGHXXXX";
  const char *u = "AbCdEfGh";
  const char *v = "aBcDeFgH";
  char *x;
  long i;
  unsigned long pos;

  test_assert(str_chr(s, 'D') == 3);

  i = str_char(s, 'D', &pos);
  test_assert(i == 1);
  test_assert(pos == 3);

  test_assert(str_diff(s, t) == 0);
  test_assert(str_same(s, t));
  test_assert(str_ndiff(s, t, 8) == 0);
  test_assert(str_nsame(s, t, 8) == 1);

  test_assert(str_casei_diff(u, v) == 0);
  test_assert(str_casei_same(u, v) == 1);
  test_assert(str_casei_ndiff(u, v, 8) == 0);
  test_assert(str_casei_nsame(u, v, 8) == 1);;

  test_assert(str_rchr(s, 'X') == 15);

  i = str_rchar(s, 'X', &pos);
  test_assert(i == 1);
  test_assert(pos == 15);

  test_assert(str_dup(s, &x));

  test_assert(str_same(s, x) == 1);
  test_assert(str_nsame(s, x, 8) == 1);

  test_assert(str_starts(s, "ABCD") == 1);
  test_assert(str_starts(s, "XYZA") == 0);
  test_assert(str_starts(s, "1234EFGH1234EFGH1234EFGH") == 0);

  test_assert(str_ends(s, "XXXX") == 1);
  test_assert(str_ends(s, "ABCD") == 0);
  test_assert(str_ends(s, "GH1234EFGH123GH1234EFGH123") == 0);

  test_assert(str_len(s) == 16);
  
  str_toupper(x);
  test_assert(x[0] == 'A');
  str_tolower(x);
  test_assert(x[0] == 'a');

  return 0;
}
Esempio n. 8
0
/*
 * Full name of the HEADER KEY expected by the PXF service
 * Converts input string to upper case and prepends "X-GP-OPTIONS-" string
 * This will be used for all user defined parameters to be isolate from internal parameters
 */
char *
normalize_key_name(const char *key)
{
	if (!key || strlen(key) == 0)
	{
		ereport(ERROR,
				(errcode(ERRCODE_INTERNAL_ERROR),
				 errmsg("internal error in pxfutils.c:normalize_key_name. Parameter key is null or empty.")));
	}

	return psprintf("X-GP-OPTIONS-%s", str_toupper(pstrdup(key), strlen(key)));
}
Esempio n. 9
0
int main(void) {
    char  str[100];

    printf("請輸入一個字串:");
    scanf("%s", str);

    str_toupper(str);
    printf("大寫:%s\n", str);

    str_tolower(str);
    printf("小寫:%s\n", str);

    return (0);
}
Esempio n. 10
0
Datum
upper(PG_FUNCTION_ARGS)
{
	text	   *in_string = PG_GETARG_TEXT_PP(0);
	char	   *out_string;
	text	   *result;

	out_string = str_toupper(VARDATA_ANY(in_string),
							 VARSIZE_ANY_EXHDR(in_string),
							 PG_GET_COLLATION());
	result = cstring_to_text(out_string);
	pfree(out_string);

	PG_RETURN_TEXT_P(result);
}
Esempio n. 11
0
byte getFile(dir_entry_t* de, byte* buf, char* filename, byte length)
{
  int i,j;
  word cluster;
  dword file_size;
  byte b;
  char filename_upper[12];
  
  for (i = 0; i < prtn.root_dir_size/512; i++)
  {
    b = read_block(buf, prtn.root_dir_addr + i*512);
    for(j = 0; j < 16; j++)
    {
      if (*(buf + j*32)==0 || *(buf + j*32)==0x2e || *(buf + j*32)==0xe5)
      { continue; }
      
      strncpy(filename_upper, (char*)(buf+j*32), 11);
      filename_upper[11] = '\0';
      
      if(strcmp(filename, str_toupper(filename_upper)) == 0)
      {
        #if DEBUG
        pmsg("found file!\r\n");
        #endif
        
        memreverse(buf + j*32 + 0x1c, &file_size, 4);
        memreverse(buf + j*32 + 0x1a, &cluster, 2);
        
        #if DEBUG
        pmsg("cluster numer:"); disword_dec(cluster); pmsg("\r\n");
        #endif
        
        // fill in dir_entry
        memmove(de->filename, filename, length);
        de->attributes = *(buf + j*32 + 0x0b);
        memmove(de->unused_attr, buf + j*32 + 0x0c, 14);
        de->filesize = file_size;
        de->entry_addr = prtn.root_dir_addr + i*512 + j*32;
        de->first_cluster = cluster;
        
        return 1;                        
      }
    }
  }
  
  return 0;
}
Esempio n. 12
0
File: str.c Progetto: hollow/lucid
static
int str_toupper_t(void)
{
	int rc = 0;

	char orig[] = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ"
	               "[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";

	char upper[] = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ"
	               "[\\]^_`ABCDEFGHIJKLMNOPQRSTUVWXYZ{|}~";

	char *buf = str_toupper(orig);

	if (strcmp(buf, upper))
		rc += log_error("[%s]\nE[%s]\nR[%s]", __FUNCTION__, upper, buf);

	return rc;
}
Esempio n. 13
0
int		main(void)
{
	bool		end = false;
	PhoneBook	PhoneBook;
	std::string	str;

	while (end == false) {
		std::cout << "What do you want? (ADD, SEARCH, EXIT) : ";
		std::getline(std::cin, str);
		str_toupper(&str);
		if (str.compare("ADD") == 0)
			PhoneBook.addContact();
		else if (str.compare("SEARCH") == 0)
			PhoneBook.search();
		else if (str.compare("EXIT") == 0)
			end = true;
		else
			std::cout << "[" << str << "]" << " is invalid input." << std::endl;
	}
	return (0);
}
Esempio n. 14
0
File: process.c Progetto: dcant/zftp
static void _handle_user(session_t *sess)
{
	if (strlen(sess->ftp_cmd_arg) != 0) {
		char buf[MAXCMD] = {0};
		strcpy(buf, sess->ftp_cmd_arg);
		str_toupper(buf);
		if (strcmp(buf, "ANONYMOUS") == 0) {
			sess->userid = -1;
			ftp_cmdio_write(sess->ctrl_fd, FTP_PASS,
				"Please specify password");
			return;
		}
		struct passwd *pw = getpwnam(sess->ftp_cmd_arg);
		if (pw == NULL)
			sess->userid = -2;
		else
			sess->userid = pw->pw_uid;
	} else
		sess->userid = -2;
	ftp_cmdio_write(sess->ctrl_fd, FTP_PASS, "Please specify password");
}
Esempio n. 15
0
static void set_module_name(BOOL setUC)
{
    const char*	ptr;
    char*	buf;
    int		len;

    /* FIXME: we shouldn't assume all module extensions are .dll in winedump
     * in some cases, we could have some .drv for example
     */
    /* get module name from name */
    if ((ptr = strrchr (globals.input_name, '/')))
	ptr++;
    else
	ptr = globals.input_name;
    len = strlen(ptr);
    if (len > 4 && strcmp(ptr + len - 4, ".dll") == 0)
	len -= 4;
    buf = malloc(len + 1);
    memcpy(buf, (const void*)ptr, len);
    buf[len] = 0;
    globals.input_module = buf;
    OUTPUT_UC_DLL_NAME = (setUC) ? str_toupper( strdup (OUTPUT_DLL_NAME)) : "";
}
Esempio n. 16
0
/**********************************************************************
 *
 *	main
 */
int main(REG1 int argc, char* argv[])
{
	REG2 int	optind;
	REG3 char*	s;
	REG4 int	len;
	int		nfile;
	char**		envargs;
	
#ifdef PROFILE
	prof_start(argv[0]);
#endif
	if (argc == 1)
		short_usage();
	alloc_buffer();	/* Allocate I/O buffer */
	s = getenv("DGREP");
	if (s != NULL) {
		envargs = malloc(sizeof(argv[0]) * (argc + 2));
		if (envargs == NULL)
			error("Out of memory", 2);
		envargs[0] = argv[0];
		envargs[1] = s;
		memcpy(&envargs[2], &argv[1], sizeof(argv[0]) * argc);
		argv = envargs;
	}
	optind = get_args(argc, argv);
	if (optind >= argc && !expr)
		short_usage();
	if (!expr)
		expr = argv[optind++];
#ifdef BSD
	/* It is faster to count lines with dfa in Bsd. (Bsd doesn't
	   have system memchr, and my version is too slow?) In PC
	   current method is faster. I don't know about other systems. */
	if (number)
		no_boymoore = TRUE;
#endif
	len = strlen(expr);
	if (exact && (no_boymoore || len > MAXREGMUST)) {
		/* Bm can handle only MAXREGMUST long patterns with
		   N+M worst case. So we verify match with reg_exec,
		   which does it in N+M time. (We use bm with the
		   regmust pattern from reg_comp.) */
		expr = quote_expr(expr, len);
		exact = FALSE;
	}
	if (!exact) {
		char eolbuf[2];
		eolbuf[0] = EOL1;
		eolbuf[1] = EOL2;
		s = reg_comp_eol(expr, eolbuf, NEOL(eolbuf), type_bits);
		if (s != NULL)
			error(s, 2);
	}
	if (!no_boymoore)
		regmust = exact ? expr : rbuf.regmust;
	if (regmust) {
		if (ignorecase) {
			str_toupper(regmust);
			str_toupper(expr);
		}
		regmust_only = (strcmp(regmust,expr) == 0);
		regmustlen = strlen(regmust);
		if (!regmust_only && regmustlen <= 1)
			regmust = NULL;
		else
			gosper(regmust, regmustlen, ignorecase);
	}
	use_normal = nonmatch || (regmust && number);
	nfile = argc - optind;
	if (nfile > 0) {
		if (block_mode)
			show_fname = BLOCK;
		else
			show_fname = BEFORE_LINE;
		while (optind < argc)
			dgrep_file(argv[optind++]);
	} else
		dgrep(fileno(stdin));
#ifdef TEST
	if (debug) {
		printf("maxbuf = %d\n", maxbuf);
		show_dfa_report();
		show_boyer_moore_report();
		fflush(stdout);
	}
#endif
	return (file_not_found || touch_failed) ? 2 : was_match ? 0 : 1;
}
Esempio n. 17
0
void 
pocl_init_devices()
{
  static unsigned int init_done = 0;
  static pocl_lock_t pocl_init_lock = POCL_LOCK_INITIALIZER;

  int i, j, dev_index;
  char env_name[1024];
  char dev_name[MAX_DEV_NAME_LEN] = {0};
  unsigned int device_count[POCL_NUM_DEVICE_TYPES];

  if (init_done == 0)
    POCL_INIT_LOCK(pocl_init_lock);
  POCL_LOCK(pocl_init_lock);
  if (init_done) 
    {
      POCL_UNLOCK(pocl_init_lock);
      return;
    }

  /* Set a global debug flag, so we don't have to call pocl_get_bool_option
   * everytime we use the debug macros */
#ifdef POCL_DEBUG_MESSAGES
  pocl_debug_messages = pocl_get_bool_option("POCL_DEBUG", 0);
#endif

  /* Init operations */
  for (i = 0; i < POCL_NUM_DEVICE_TYPES; ++i)
    {
      pocl_devices_init_ops[i](&pocl_device_ops[i]);
      assert(pocl_device_ops[i].device_name != NULL);

      /* Probe and add the result to the number of probbed devices */
      assert(pocl_device_ops[i].probe);
      device_count[i] = pocl_device_ops[i].probe(&pocl_device_ops[i]);
      pocl_num_devices += device_count[i];
    }

  assert(pocl_num_devices > 0);
  pocl_devices = calloc(pocl_num_devices, sizeof(struct _cl_device_id));
  if (pocl_devices == NULL)
    POCL_ABORT("Can not allocate memory for devices\n");

  dev_index = 0;
  /* Init infos for each probbed devices */
  for (i = 0; i < POCL_NUM_DEVICE_TYPES; ++i)
    {
      assert(pocl_device_ops[i].init);
      for (j = 0; j < device_count[i]; ++j)
        {
          pocl_devices[dev_index].ops = &pocl_device_ops[i];
          /* The default value for the global memory space identifier is
             the same as the device id. The device instance can then override 
             it to point to some other device's global memory id in case of
             a shared global memory. */
          pocl_devices[dev_index].global_mem_id = dev_index;
          
          pocl_device_ops[i].init_device_infos(&pocl_devices[dev_index]);

          pocl_device_common_init(&pocl_devices[dev_index]);

          str_toupper(dev_name, pocl_device_ops[i].device_name);
          /* Check if there are device-specific parameters set in the
             POCL_DEVICEn_PARAMETERS env. */
          if (snprintf (env_name, 1024, "POCL_%s%d_PARAMETERS", dev_name, j) < 0)
            POCL_ABORT("Unable to generate the env string.");

          pocl_devices[dev_index].ops->init(&pocl_devices[dev_index], getenv(env_name));

          if (dev_index == 0)
            pocl_devices[dev_index].type |= CL_DEVICE_TYPE_DEFAULT;
          
          ++dev_index;
        }
    }

  init_done = 1;
  POCL_UNLOCK(pocl_init_lock);
}
Esempio n. 18
0
File: test.c Progetto: Jing0/neolibc
int main(int argc, char const *argv[]) {
    /* str_new */
    str_t string = str_new();
    /* str_set */
    str_set(string, "   %d%d%d", 1, 2, 3);
    /* str_append */
    str_append(string, "appending   end");
    /* str_println */
    str_println(string);
    /* str_reverse */
    str_reverse(string);
    str_println(string);
    /* str_length */
    printf("size before trimming:\t%zu\n", str_length(string));
    /* str_trim */
    str_trim(string);
    printf("size after trimming:\t%zu\n", str_length(string));
    /* str_substr */
    str_t substr = str_substr(string, 0, 3);
    printf("substr before swap:\t");
    str_println(substr);
    printf("string before swap:\t");
    str_println(string);
    str_swap(substr, string);
    printf("substr after swap:\t");
    str_println(substr);
    printf("string after swap:\t");
    str_println(string);
    printf("is string empty?\t%s\n",
           str_isempty(string) ? "Yes" : "No");
    printf("is substr equal to string?\t%s\n",
           str_compare(substr, string) ? "No" : "Yes");

    /* str_readFromFile */
    str_readFromFile(string, "neostring.c");
    printf("string size: %zu\t", str_length(string));
    printf("string capacity: %zu\n", string->capacity);
    str_set(string, "ok");
    printf("Before trimToSize():\n");
    printf("string size: %zu\t", str_length(string));
    printf("string capacity: %zu\n", string->capacity);
    /* str_trimToSize */
    str_trimToSize(string);
    printf("After trimToSize():\n");
    printf("string size: %zu\t", str_length(string));
    printf("string capacity: %zu\n", string->capacity);
    str_set(string, "hello, world");
    str_println(string);
    printf("%zu\n", string->size);
    printf("string has prefix ello?\t%s\n", str_hasPrefix(string, "ello") ? "Yes" : "No");
    printf("%zu\n", string->size);
    printf("string has suffix orld?\t%s\n", str_hasSuffix(string, "orld") ? "Yes" : "No");
    /* str_clone */
    str_t clone = str_clone(string);
    /* str_toupper */
    str_toupper(clone);
    /* str_writeToFile */
    str_writeToFile(clone, "./test.txt");
    /* str_destroy */
    str_destroy(string);
    str_destroy(clone);
    str_destroy(substr);
    return 0;
}
Esempio 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");
    
}
Esempio n. 20
0
EDELIB_NS_USE

#define CCHARP(str)           ((const char*)str)
#define STR_EQUAL(str1, str2) (strcmp(CCHARP(str1), CCHARP(str2)) == 0)

UT_FUNC(strtest, "Test strutil")
{
	unsigned char s1[] = "StRiNG1";
	UT_VERIFY( STR_EQUAL("string1", str_tolower(s1)) );

	unsigned char s2[] = "some Sample Of sTrinG";
	UT_VERIFY( STR_EQUAL("some sample of string", str_tolower(s2)) );

	unsigned char s3[] = "sTRinG2";
	UT_VERIFY( STR_EQUAL("STRING2", str_toupper(s3)) );

	unsigned char s4[] = "xxx AbA BbCCbBc xxx !@# . Abb";
	UT_VERIFY( STR_EQUAL("XXX ABA BBCCBBC XXX !@# . ABB", str_toupper(s4)) );

	char s5[] = "  some with spaces";
	UT_VERIFY( STR_EQUAL("some with spaces", str_trimleft(s5)) );

	char s6[] = "				  some with spaces";
	UT_VERIFY( STR_EQUAL("some with spaces", str_trimleft(s6)) );

	char s6a[] = "|				some with spaces";
	UT_VERIFY( STR_EQUAL("|				some with spaces", str_trimleft(s6a)) );

	char s7[] = ".  some with spaces";
	UT_VERIFY( STR_EQUAL(".  some with spaces", str_trimleft(s7)) );
Esempio n. 21
0
File: emit_c.c Progetto: tbeu/lcm
static void emit_c_get_field(lcmgen_t *lcm, FILE *f, lcm_struct_t *ls)
{
    char *tn = ls->structname->lctypename;
    char *tn_ = dots_to_underscores(tn);

    emit(0,"int %s_get_field(const %s *p, int i, lcm_field_t *f)", tn_, tn_);
    emit(0,"{");
    emit(1,"if (0 > i || i >= %s_num_fields())", tn_);
    emit(2,"return 1;");
    emit(1,"");

    emit(1,"switch (i) {");
    emit(1,"");

    int num_fields = g_ptr_array_size(ls->members);
    for(int i = 0; i < num_fields; i++) {
        emit(2,"case %d: {", i);

        lcm_member_t *m = (lcm_member_t *)g_ptr_array_index(ls->members, i);

        const char *type_val = NULL;
        if(lcm_is_primitive_type(m->type->shortname)) {
            type_val = str_toupper(g_strdup_printf("LCM_FIELD_%s", m->type->shortname));
        } else {
            emit(3,"/* %s */", m->type->shortname);
            type_val = "LCM_FIELD_USER_TYPE";
        }

        emit(3,"f->name = \"%s\";", m->membername);
        emit(3,"f->type = %s;", type_val);
        emit(3,"f->typestr = \"%s\";", m->type->shortname);

        int num_dim = g_ptr_array_size(m->dimensions);
        emit(3,"f->num_dim = %d;", num_dim);

        if(num_dim != 0) {

            for(int j = 0; j < num_dim; j++) {
                lcm_dimension_t *d = (lcm_dimension_t*) g_ptr_array_index(m->dimensions, j);
                if(d->mode == LCM_VAR)
                    emit(3,"f->dim_size[%d] = p->%s;", j, d->size);
                else
                    emit(3,"f->dim_size[%d] = %s;", j, d->size);
            }

            for(int j = 0; j < num_dim; j++) {
                lcm_dimension_t *d = (lcm_dimension_t*) g_ptr_array_index(m->dimensions, j);
                emit(3,"f->dim_is_variable[%d] = %d;", j, d->mode == LCM_VAR);
            }

        }

        emit(3, "f->data = (void *) &p->%s;", m->membername);

        emit(3, "return 0;");
        emit(2,"}");
        emit(2,"");
    }
    emit(2,"default:");
    emit(3,"return 1;");
    emit(1,"}");
    emit(0,"}");
    emit(0,"");
}
Esempio n. 22
0
int tokenize(struct token_list* tk_list, char* file_buffer)
{
  enum Status status;
   line_num;
  size_t token_begin, token_end;
  token_begin = 0, token_end  = 0;
  status = STATUS_INVALID;
  str_toupper(file_buffer);
  /*
   * Careful: it seems an error to let "i <= len", 
   * but we need one more execution to flush the last token into token list.
   */
  size_t line_num = 1;
  for (size_t i = 0; ; ++i) {
    struct token_node* tok_node;
    switch (status) {
    case STATUS_LETTER:
      if (!IS_LETTER(file_buffer[i]) && !IS_DIGIT(file_buffer[i])) {
        token_end = i;
        tok_node = create_token(TOKEN_LABEL, file_buffer + token_begin, token_end - token_begin);
        tok_node->type = letter_type(tok_node->liter, tok_node->len);
        token_append(tk_list, tok_node);
        token_begin = i;
        status = next_status(status, file_buffer[i]);
      }
      break;
    case STATUS_PRAGMA:
      if (!IS_LETTER(file_buffer[i])) {
        int type;
        token_end = i;
        type = pragma_type(file_buffer + token_begin, token_end - token_begin);
        if (type < 0) {
          error("invalid pragma ad line %d\n", line_num);
          return -4;
        }
        tok_node = create_token(type, file_buffer + token_begin, token_end - token_begin);
        token_append(tk_list, tok_node);
        token_begin = i;
        status = next_status(status, file_buffer[i]);
      }
      break;
    case STATUS_PUNCTUATION:
      token_end = i;
      tok_node = create_token(file_buffer[token_begin], file_buffer + token_begin, token_end - token_begin);
      token_append(tk_list, tok_node);
      token_begin = i;
      status = next_status(status, file_buffer[i]);
      break;
    case STATUS_NUMBER:
      if (!IS_NUMBER(file_buffer[i])) {
        token_end = i;
        if (!check_number(file_buffer + token_begin, token_end - token_begin)) {
          error("invalid number format at line %d\n", line_num);
          return -2;
        }
        tok_node = create_token(TOKEN_NUMBER, file_buffer + token_begin, token_end - token_begin);
        tok_node->data = parse_number(tok_node->liter);
        token_append(tk_list, tok_node);
        token_begin = i;
        status = next_status(status, file_buffer[i]);
      }
      break;
    case STATUS_BLANK:
      if (!IS_BLANK(file_buffer[i])) {
        token_begin = i;
        status = next_status(status, file_buffer[i]);
      }
      break;
    case STATUS_COMMENTS:
      //once status is in comments, it will always be in comments
      if ('\n' == file_buffer[i]) {
        token_begin = i;
        status = next_status(status, file_buffer[i]);
      }
      break;
    case STATUS_INVALID:
      token_begin = i;
      status = next_status(status, file_buffer[i]);
      if (STATUS_INVALID == status && 0 != file_buffer[i]) {
        error("invalid format at line %d\n", line_num);
        return -3;
      }
      break;
    }
    if (0 == file_buffer[i])
      break;
    else if ('\n' == file_buffer[i])
      ++line_num;
  }
  return 0;
}
Esempio n. 23
0
/* internal function to execute queries from a topic file against an
 * index and output the results in trec_eval format */
static int process_topic_file(FILE *fp, struct args *args, FILE *output, 
  struct treceval *teresults) {
    struct index_stats stats;
    char *query,
         *querynum = NULL;
    struct index_result *results = NULL;
    unsigned int returned,
                 i;
    int est;
    double total_results;
    struct mlparse_wrap *parser;
    struct timeval now, then;
    struct timeval topic_now, topic_then;

    gettimeofday(&topic_then, NULL);

    if (!index_stats(args->idx, &stats)) {
        return 0;
    }

    if ((parser = mlparse_wrap_new_file(stats.maxtermlen, LOOKAHEAD, fp, 
        BUFSIZ, 0))
      && (results = malloc(sizeof(*results) * args->numresults))
      && (querynum = malloc(stats.maxtermlen + 2))) {

        while ((query = get_next_query(parser, 
            querynum, stats.maxtermlen + 1, args->title, args->descr, 
            args->narr, &args->sopt.word_limit, args))) {

            /* check that we actually got a query */
            if (!str_len(query)) {
                if (!args->cont) {
                    fprintf(stderr, "failed to extract query for topic %s\n", 
                      querynum);
                }
                if (atoi((const char *) querynum) == 201) {
                    fprintf(stderr, "looks like it occurred on TREC topics "
                      "201-250, which is probably because you specified a "
                      "title-only run and it doesn't contain titles\n");
                }

                if (args->cont && strlen(querynum)) {
                    /* continue evaluation */
                    if (args->dummy) {
                        /* no results, insert dummy result if requested */
                        fprintf(output, "%s\tQ0\t%s\t%u\t%f\t%s\n", querynum,
                          "XXXX-XXX-XXXXXXX", 1, 0.0, args->run_id);
                    }
                } else {
                    /* give up evaluation */
                    free(query);
                    free(results);
                    free(querynum);
                    mlparse_wrap_delete(parser);
                    return 0;
                }
            }
 
            args->sopt.summary_type = INDEX_SUMMARISE_NONE;

            /* FIXME: detect errors */

            gettimeofday(&then, NULL);
            if (index_search(args->idx, (const char *) query, 0, 
                args->numresults, results, &returned, 
                &total_results, &est, (args->sopts | INDEX_SEARCH_WORD_LIMIT | 
                INDEX_SEARCH_SUMMARY_TYPE), &args->sopt)) {
                char aux_buf[512];

                gettimeofday(&now, NULL);

                if (args->print_queries) {
                    //fprintf(stderr,
                    // sengor
                    printf( 
                      "query '%s' completed in %lu microseconds\n", query,
                      (unsigned long int) now.tv_usec - then.tv_usec 
                        + (now.tv_sec - then.tv_sec) * 1000000);
                }

                /* print results */
                for (i = 0; i < returned; i++) {
                    char *docno = NULL;

                    /* hack: any document that doesn't have a TREC docno will
                     * inherit the docno of the previous document (until we 
                     * find one that has a docno) */

                    if (results[i].auxilliary && results[i].auxilliary[0]) {
                        strncpy(aux_buf, results[i].auxilliary, 
                          sizeof(aux_buf));
                        docno = aux_buf;
                    } else {
                        int ret = 1;
                        unsigned long int docnum = results[i].docno;
                        unsigned int aux_len = 0;

                        /* retrieve TREC docno for progressively higher docs */
                        while (ret && (docnum > 0) && !aux_len) {
                            docnum--;
                            ret = index_retrieve_doc_aux(args->idx, docnum,
                              aux_buf, sizeof(aux_buf) - 1, &aux_len);
                            /* XXX assume trec docno always < 512 bytes long */
                        }
                        if (ret && aux_len) {
                            docno = aux_buf;
                        }
                    }
                    aux_buf[sizeof(aux_buf) - 1] = '\0';

                    if (teresults 
                      && docno
                      && treceval_add_result(teresults, atoi(querynum), 
                          docno, (float) results[i].score)) {
                        /* they want evaluated results, stuck it in the results
                         * structure */
                    } else if (!teresults && docno) {
                        str_toupper(docno);

                        /* print out query_id, iter (ignored - so we print
                         * out number of seconds taken), docno, rank
                         * (ignored), score, run_id */
                        fprintf(output, "%s\tQ0\t%s\t%u\t%f\t%s\n", querynum, 
                          docno, i + 1, results[i].score, 
                          args->run_id);
                    } else if (teresults && docno) {
                        fprintf(stderr, "failed to add to treceval results\n");
                        free(results);
                        free(querynum);
                        free(docno);
                        free(query);
                        mlparse_wrap_delete(parser);
                        return 0;
                    } else {
                        /* couldn't copy the docno */
                        fprintf(stderr, "docno ('%s') copy failed: %s\n", 
                          results[i].auxilliary, strerror(errno));
                        free(query);
                        free(results);
                        free(querynum);
                        mlparse_wrap_delete(parser);
                        return 0;
                    }
                }

                if (returned == 0 && args->dummy) {
                    /* no results, insert dummy result if requested */
                    fprintf(output, "%s\tQ0\t%s\t%u\t%f\t%s\n", querynum,    
                      "XXXX-XXX-XXXXXXX", 1, 0.0, args->run_id);
                }
            } else {
                /* error searching */
                fprintf(stderr, "error searching index\n");
                free(query);
                mlparse_wrap_delete(parser);
                return 0;
            }

            free(query);
            querynum[0] = '\0';
        }

        if (!feof(fp)) {
            fprintf(stderr, "parser or read error\n");
            free(results);
            free(querynum);
            mlparse_wrap_delete(parser);
            return 0;
        }
        free(results);
        free(querynum);

        gettimeofday(&topic_now, NULL);

        if (args->timing) {
            fprintf(stderr, "topic processed in %lu microseconds\n", 
              (unsigned long int) topic_now.tv_usec - topic_then.tv_usec 
                + (topic_now.tv_sec - topic_then.tv_sec) * 1000000);
        }

        mlparse_wrap_delete(parser);
        return 1;
    } else {
        if (parser) {
            if (results) {
                free(results);
            }
            mlparse_wrap_delete(parser);
        }
    }

    return 0;
}
Esempio n. 24
0
/* internal function to parse the topic file and extract a query and
 * querynum from it */
static char *get_next_query(struct mlparse_wrap *parser, char *querynum, 
  unsigned int querynum_len, int title, int descr, int narr, 
  unsigned int *words, struct args *args) {
    int innum = 0,                       /* parsing the topic number */
        intitle = 0,                     /* whether we're parsing the title */
        indescr = 0,                     /* whether we're parsing description */
        innarr = 0,                      /* whether we're parsing narrative */
        firstword = 0;                   /* whether its the first word of a 
                                          * field */
    enum mlparse_ret ret;                /* return value from parser */
    char *buf = NULL,                    /* query buffer */
         word[TERMLEN_MAX + 1];          /* last word parsed */
    unsigned int buflen = 0,             /* length of the query */
                 bufcapacity = 0,        /* capacity of the query buffer */
                 wordlen;                /* length of the last word parsed */

    *words = 0;

    do {
        ret = mlparse_wrap_parse(parser, word, &wordlen, 0);
    } while (ret != MLPARSE_TAG && ret != MLPARSE_ERR && ret != MLPARSE_EOF);

    /* check that we got a 'top' tag */
    if (ret == MLPARSE_TAG && str_casecmp(word, "top")) {
        fprintf(stderr, "expected to parse 'top' tag from topic file\n");
        return NULL;
    } else if (ret == MLPARSE_ERR) {
        fprintf(stderr, "error parsing topic file\n");
        return NULL;
    } else if (ret == MLPARSE_EOF) {
        return NULL;
    } else {
        assert(ret == MLPARSE_TAG);
    }

    *querynum = 0;

    /* set up phrase if requested by user */
    if (args->phrase) {
        APPEND(buf, buflen, bufcapacity, "\"", 1);
    }

    /* parse the rest of the top entry */
    while ((ret = mlparse_wrap_parse(parser, word, &wordlen, 0)) 
      != MLPARSE_ERR) {
        switch (ret) {
        case MLPARSE_TAG:
            if (!str_casecmp(word, "num")) {
                /* query number */
                innum = 1;
                intitle = 0;
                indescr = 0;
                innarr = 0;
                firstword = 1;
            } else if (!str_casecmp(word, "title")) {
                /* query title */
                if (title) {
                    intitle = 1;
                } else {
                    intitle = 0;
                }
                indescr = 0;
                innarr = 0;
                innum = 0;
                firstword = 1;
            } else if (!str_casecmp(word, "desc")) {
                /* query description */
                if (descr) {
                    indescr = 1;
                } else {
                    indescr = 0;
                }
                intitle = 0;
                innarr = 0;
                innum = 0;
                firstword = 1;
            } else if (!str_casecmp(word, "narr")) {
                /* query narrative */
                if (narr) {
                    innarr = 1;
                } else {
                    innarr = 0;
                }
                indescr = 0;
                intitle = 0;
                innum = 0;
                firstword = 1;
            } else if (!str_casecmp(word, "/top")) {
                /* finished this topic, return the query */
                if (*querynum) {
                    if (buf) {
                        /* optionally terminate phrase */
                        if (args->phrase) {
#define TMPBUFLEN 100
                            char tmpbuf[TMPBUFLEN + 1];
                            unsigned int n;

                            APPEND(buf, buflen, bufcapacity, "\"", 1);
                            if (args->sloppiness) {

                                n = snprintf(tmpbuf, TMPBUFLEN, " [sloppy:%u] ",
                                    args->sloppiness);
                                assert(n < TMPBUFLEN);
                                APPEND(buf, buflen, bufcapacity, tmpbuf, n);

                                /* ensure sloppy directive is processed */
                                (*words)++; 
                            }
                            if (args->cutoff) {
                                n = snprintf(tmpbuf, TMPBUFLEN, " [cutoff:%u] ",
                                    args->cutoff);
                                assert(n < TMPBUFLEN);
                                APPEND(buf, buflen, bufcapacity, tmpbuf, n);

                                /* ensure cutoff directive is processed */
                                (*words)++; 
                            }
#undef TMPBUFLEN
                        }

                        /* terminate string and return it */
                        APPEND(buf, buflen, bufcapacity, "\0", 1);
                        return buf;
                    } else {
                        APPEND(buf, buflen, bufcapacity, "\0", 1);
                        return buf;
                    }
                } else {
                    fprintf(stderr, 
                      "didn't find topic number in topic file\n");
                    return NULL;
                }
            } else {
                /* unexpected tag, ignore it */
                innum = 0;
                innarr = 0;
                indescr = 0;
                intitle = 0;
            }
            break;

        case MLPARSE_EOF:
            if (*querynum || buf) {
                fprintf(stderr, "unexpected eof while parsing\n");
            }
            return NULL;

        /* ignore this stuff */
        case MLPARSE_PARAM:
        case MLPARSE_CONT | MLPARSE_PARAM:
        case MLPARSE_PARAMVAL:
        case MLPARSE_CONT | MLPARSE_PARAMVAL:
        case MLPARSE_CDATA:
        case MLPARSE_END | MLPARSE_CDATA:
        case MLPARSE_WHITESPACE:
            break;

        /* XXX: comments shouldn't just be ignored (as control flow, the stuff
         * inside comments should be ignored) */
        case MLPARSE_COMMENT | MLPARSE_END:
        case MLPARSE_COMMENT:
            break;

        case MLPARSE_WORD:
        case MLPARSE_END | MLPARSE_WORD:
            /* include everything in tags indicated by arguments, except
             * that TREC topic files often start the topic with 'Topic:',
             * the description with 'Description:' and narrative with
             * 'Narrative:' :o( */
            if ((intitle && (!firstword 
                || str_nncmp(word, wordlen, "Topic:", str_len("Topic:"))))
              || (indescr && (!firstword 
                  || str_nncmp(word, wordlen, "Description:", 
                      str_len("Description:"))))
              || (innarr && (!firstword 
                  || str_nncmp(word, wordlen, "Narrative:", 
                      str_len("Narrative:"))))) {

                /* we have to add the word to the buffer */
                (*words)++;
                APPEND(buf, buflen, bufcapacity, word, wordlen);
                APPEND(buf, buflen, bufcapacity, " ", 1);
            } else if (innum 
              && (!firstword 
                || str_nncmp(word, wordlen, "Number:", str_len("Number:")))) {

                if (wordlen < querynum_len) {
                    str_ncpy(querynum, word, wordlen);
                    querynum[wordlen] = '\0';
                    str_toupper(querynum);
                } else {
                    fprintf(stderr, "querynum '%s' too long\n", word);
                    return NULL;
                } 
            }
            firstword = 0;
            break;

        case MLPARSE_CONT | MLPARSE_WORD:
        case MLPARSE_CONT | MLPARSE_TAG:
            /* ignore (XXX: should also ignore subsequent word as well) */
            break;

        default:
            /* not expecting anything else */
            if (buf) {
                free(buf);
            }
            fprintf(stderr, "error parsing topic file\n");
            return NULL;
            break;
        }
    }

    /* must have received an error */
    if (buf) {
        free(buf);
    }
    fprintf(stderr, "error parsing topic file\n");
    return NULL;
}
Esempio n. 25
0
void 
pocl_init_devices()
{
  static unsigned int init_done = 0;
  static unsigned int init_in_progress = 0;
  static pocl_lock_t pocl_init_lock = POCL_LOCK_INITIALIZER;

  unsigned i, j, dev_index;
  char env_name[1024];
  char dev_name[MAX_DEV_NAME_LEN] = {0};
  unsigned int device_count[POCL_NUM_DEVICE_TYPES];

  /* This is a workaround to a nasty problem with libhwloc: When
     initializing basic, it calls libhwloc to query device info.
     In case libhwloc has the OpenCL plugin installed, it initializes
     it and it leads to initializing pocl again which leads to an
     infinite loop. */

  if (init_in_progress)
      return;
  init_in_progress = 1;

  if (init_done == 0)
    POCL_INIT_LOCK(pocl_init_lock);
  POCL_LOCK(pocl_init_lock);
  if (init_done) 
    {
      POCL_UNLOCK(pocl_init_lock);
      return;
    }

  /* Set a global debug flag, so we don't have to call pocl_get_bool_option
   * everytime we use the debug macros */
#ifdef POCL_DEBUG_MESSAGES
  pocl_debug_messages = pocl_get_bool_option("POCL_DEBUG", 0);
#endif

  pocl_cache_init_topdir();

  pocl_init_queue_list();

  /* Init operations */
  for (i = 0; i < POCL_NUM_DEVICE_TYPES; ++i)
    {
      pocl_devices_init_ops[i](&pocl_device_ops[i]);
      assert(pocl_device_ops[i].device_name != NULL);

      /* Probe and add the result to the number of probbed devices */
      assert(pocl_device_ops[i].probe);
      device_count[i] = pocl_device_ops[i].probe(&pocl_device_ops[i]);
      pocl_num_devices += device_count[i];
    }

  assert(pocl_num_devices > 0);
  pocl_devices = (struct _cl_device_id*) calloc(pocl_num_devices, sizeof(struct _cl_device_id));
  if (pocl_devices == NULL)
    POCL_ABORT("Can not allocate memory for devices\n");

  dev_index = 0;
  /* Init infos for each probed devices */
  for (i = 0; i < POCL_NUM_DEVICE_TYPES; ++i)
    {
      assert(pocl_device_ops[i].init);
      for (j = 0; j < device_count[i]; ++j)
        {
          pocl_devices[dev_index].ops = &pocl_device_ops[i];
          pocl_devices[dev_index].dev_id = dev_index;
          /* The default value for the global memory space identifier is
             the same as the device id. The device instance can then override 
             it to point to some other device's global memory id in case of
             a shared global memory. */
          pocl_devices[dev_index].global_mem_id = dev_index;
          
          pocl_device_ops[i].init_device_infos(&pocl_devices[dev_index]);

          pocl_device_common_init(&pocl_devices[dev_index]);

          str_toupper(dev_name, pocl_device_ops[i].device_name);
          /* Check if there are device-specific parameters set in the
             POCL_DEVICEn_PARAMETERS env. */
          if (snprintf (env_name, 1024, "POCL_%s%d_PARAMETERS", dev_name, j) < 0)
            POCL_ABORT("Unable to generate the env string.");

          pocl_devices[dev_index].ops->init(&pocl_devices[dev_index], getenv(env_name));

          if (dev_index == 0)
            pocl_devices[dev_index].type |= CL_DEVICE_TYPE_DEFAULT;

          pocl_devices[dev_index].cache_dir_name = strdup(pocl_devices[dev_index].long_name);
          pocl_string_to_dirname(pocl_devices[dev_index].cache_dir_name);
          
          ++dev_index;
        }
    }

  init_done = 1;
  POCL_UNLOCK(pocl_init_lock);
}
Esempio n. 26
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");
    }
Esempio n. 27
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");
    }