Esempio n. 1
0
i32_t substr(const i8_p pstr, const i8_p pstr_end, const i8_p prev, const i8_p post, i8_p pdata, i32_t data_size)
{
	i8_p pb;
	i8_p pe;
	i32_t len;
	i32_t prev_len;

	find_str(pstr, pstr_end, prev, &pb);
	if (pb == NULL) {
		return 0;
	}

	prev_len = strlen(prev);
	find_str(pb+prev_len, pstr_end, post, &pe);
	if (NULL == pe) {
		pe = pstr_end;
	}

	len = pe-pb-prev_len;
	if (len > data_size) {
		return 0;
	}
	
	memcpy(pdata, pb+prev_len, len);

	return len;
}
BTree *find_str(BTree *tree, char *str)
{
	if (tree == NULL)
		return (NULL);
	if (strcmp(str, tree->str) == 0)
		return (tree);
	else if (strcmp(str, tree->str) < 0)
		return (find_str(tree->left, str));
	else
		return (find_str(tree->right, str));
}
Esempio n. 3
0
void print_polozka(int num,TITEM *t)
  {
  if (pr_number) printf("%3d³",num);
  if (pr_name) printf("%-32s³",t->jmeno);
  if (pr_type) printf("%-20s³",find_str(_typy_veci,t->druh+1,sizeof(_typy_veci)));
  if (pr_umist) printf("%-20s³",find_str(_umisteni_veci,t->umisteni+1,sizeof(_umisteni_veci)));
  if (pr_zbran) printf("%-10s³",isweapon(t->druh)?find_str(_typy_zbrani,t->typ_zbrane+1,sizeof(_typy_zbrani)):" ");
  if (pr_hmotn) printf("%6d³",t->hmotnost);
  if (pr_cena) printf("%6d³",t->cena);
  if (pr_sound) printf("%-12s³",find_str(sound,t->sound,listsize));
  if (pr_popis) printf("%s",t->popis);
  puts("");
  }
Esempio n. 4
0
/* Extract any control sequences that are ment only for run_erl
 * and should not be forwarded to the pty.
 */
int erts_run_erl_extract_ctrl_seq(char* buf, int len)
{
    static const char prefix[] = "\033_";
    static const char suffix[] = "\033\\";
    char* bufend = buf + len;
    char* start = buf;
    char* command;
    char* end;

    for (;;) {
	start = find_str(start, bufend-start, prefix);
	if (!start) break;

	command = start + strlen(prefix);
	end = find_str(command, bufend-command, suffix);
	if (end) {
	    unsigned col, row;
	    if (sscanf(command,"version=%u", &PROTOCOL_VER)==1) {
		/*fprintf(stderr,"to_erl v%u\n", protocol_ver);*/
	    }
	    else if (sscanf(command,"winsize=%u,%u", &col, &row)==2) {
#ifdef TIOCSWINSZ
	      struct winsize ws;
	      ws.ws_col = col;
	      ws.ws_row = row;
	      if (ioctl(MFD, TIOCSWINSZ, &ws) < 0) {
		ERRNO_ERR0(LOG_ERR,"Failed to set window size");
	      }
#endif
	    }
	    else {
		ERROR2(LOG_ERR, "Ignoring unknown ctrl command '%.*s'\n",
		       (int)(end-command), command);
	    }

	    /* Remove ctrl sequence from buf */
	    end += strlen(suffix);
	    memmove(start, end, bufend-end);
	    bufend -= end - start;
	}
	else {
	    ERROR2(LOG_ERR, "Missing suffix in ctrl sequence '%.*s'\n",
		   (int)(bufend-start), start);
	    break;
	}
    }
    return bufend - buf;
}
BTree *btree_find(BTree *tree, char *str)
{
	if (tree == NULL || str NULL)
		return (NULL);
	else
		return (find_str(tree, str));
}
Esempio n. 6
0
int main()
{
    char src[MAX];
    char head[MAX];
    char tail[MAX];
    char *aim_str = NULL;

    printf("please input a string(no blank):\n");
    scanf("%s",src);    /* 输入源字符串 */

    printf("please input the head string(no blank):\n");
    scanf("%s",head);   /* 输入头字符串 */

    printf("please input the tail string(no blank):\n");
    scanf("%s",tail);   /* 输入尾字符串 */

    if((aim_str = find_str(src,head,tail)) == NULL)   /* 函数调用 */
    {
        printf("function opporate error!\n");
	exit(FUNCTION_ERROR);
    }

    printf("the aim_str is %s.\n",aim_str);

    return 0;
}
Esempio n. 7
0
string
JSONConfiguration::GetString(IN const string &name)
{

    return find_str(_rootValue.get_obj(),name);

}
Esempio n. 8
0
int main(int argc, char** argv)
{
	char* a = NULL;
	char* buf[100] = {0};
	char str[100] = "ab";
	int k = 0;
	int total = 0;
	int nline = 0;
	int i = 0;

	do{
		a = getline();
		buf[nline] = a;
		nline++;
	}while(a != NULL);
	nline--;

	for (i = 0; i < nline; i++)
	{
		total = total + find_str(buf[i], str, i);
	}
	printf("the total time :%d\n", total);
	
	return 0;
		
}
Esempio n. 9
0
/*
 * Checks whether a word is a stopwords
 */
int is_stopword(char *word) {
    if (!stopwords) {
        load_stopwords();
    }

    return find_str(stopwords, sizeof(char *), word, 0, nr_stopwords - 1) != -1;
}
Esempio n. 10
0
int TIME_PRO::process()
{
	u8 item_count = 0;
	u8 bd_info_item_seek = 0;
	u16 seek = 0;
	u8 ret = 0;
	u8 *p_cmd = NULL;
	int flag;
	//这个bug隐藏的太深了
	no_interrupts();
	flag = (cmd_check_dog() == -1) && (cmd_num > 0);
	interrupts();
	if( flag == 1 )

	{
		
		memset(&date_time_string,0x00,sizeof(date_time_string));//清除结构体	
		ret = find_str(buf,(u8 *)"$dmyhms",seek);
		if(ret == 0)
		{
			p_cmd = buf + seek;
			do
			{
				p_cmd++;
				switch(*p_cmd)
				{
					case ',':
						item_count++;
						bd_info_item_seek = 0;
						break;
					default :
						switch(item_count)
						{
							case 0:break;
							case 1:date_time_string[bd_info_item_seek]		= *p_cmd;break;
							default:break;								
						}		
						bd_info_item_seek++;						
						break;				
				}				
			}while(*p_cmd!='*');
		}
		//date_time[12] = 0;
		char_count = 0;
		cmd_num = 0;
		
		uart1.printf((char *)buf);
		if(buf[1] != 'd')
			uart1.printf("flag = %d,cmd = %d",flag,cmd_num);
		uart1.printf("\r\n");
		memset(&buf,0x00,1024);//清除结构体	

		return 1;
	}
	return 0;
}
Esempio n. 11
0
void print_option(mini_t *ini)
{
	if(directives && !find_str(directives, ini->key)) { return; }
	if(verbose || !ini->value) { fputs(ini->key, stdout); }
	if(ini->value) {
		if(verbose) fputs(" = ", stdout);
		fputs(ini->value, stdout);
	}
	fputc(sep, stdout);
}
Esempio n. 12
0
/*
 * Binary search an array for a string
 *  obj: pointer to an array of pointers to strings
         or array of fixed length structs containing a pointer to a string (in this case the obj pointer should point to the string pointer in the first struct)
 *  struct_len: length of one object in the array in bytes
 *  str: search string
 *  min: minimal index to search
 *  max: maximal index to search
 */
int find_str(void *objs, int struct_len, char *str, int min, int max) {
    int middle = (min + max) / 2;
    int cmp = strcmp(*((char **) (((char *) objs) + middle * struct_len)), str);

    if (!cmp) {
        // string found
        return middle;
    } else if (min != max) {
        if (cmp > 0 && min != middle) {
            // continue search in left half
            return find_str(objs, struct_len, str, min, middle - 1);
        } else if (max != middle) {
            // continue search in right half
            return find_str(objs, struct_len, str, middle + 1, max);
        }
    }

    // finished searching
    return -1;
}
Esempio n. 13
0
uint16_t get_str(char *source, const char *begin, uint16_t count1, const char *end, uint16_t count2, char *out)
{
    uint16_t i;
    uint16_t len1;
    uint16_t len2;
    uint16_t index1 = 0;
    uint16_t index2 = 0;
    uint16_t length = 0;
    len1 = find_str((uint8_t *)source, (uint8_t *)begin, count1, index1);
    len2 = find_str((uint8_t *)source, (uint8_t *)end, count2, index2);
    length = index2 - index1 - len1;
    if((len1 != 0) && (len2 != 0))
    {
        for( i = 0; i < index2 - index1 - len1; i++)
            out[i] = source[index1 + len1 + i];
        out[i] = '\0';
    }
    return length;

}
Esempio n. 14
0
void make_get(char *dest, char *src){
   int i;

   if(dest && src){
      memset(dest, '\0', MAX_SIZE);
      strcat(dest, "GET ");
      i = find_str(src, "twitter.com/");
      strcat(dest, src + i);
      strcat(dest, " HTTP/1.1\n");
   }
}
Esempio n. 15
0
/* Extract any control sequences that are ment only for run_erl
 * and should not be forwarded to the pty.
 */
static int extract_ctrl_seq(char* buf, int len)
{
    static const char prefix[] = "\033_";
    static const char suffix[] = "\033\\";
    char* bufend = buf + len;
    char* start = buf;
    char* command;
    char* end;
    
    for (;;) {
	start = find_str(start, bufend-start, prefix);
	if (!start) break;
	
	command = start + strlen(prefix);
	end = find_str(command, bufend-command, suffix);
	if (end) {
	    unsigned col, row;
	    if (sscanf(command,"version=%u", &protocol_ver)==1) {
		/*fprintf(stderr,"to_erl v%u\n", protocol_ver);*/
	    }
	    else if (sscanf(command,"winsize=%u,%u", &col, &row)==2) {
		set_window_size(col,row);
	    }
	    else {
		ERROR2(LOG_ERR, "Ignoring unknown ctrl command '%.*s'\n",
		       (int)(end-command), command);
	    }
	  
	    /* Remove ctrl sequence from buf */
	    end += strlen(suffix);
	    memmove(start, end, bufend-end);
	    bufend -= end - start;
	}
	else {
	    ERROR2(LOG_ERR, "Missing suffix in ctrl sequence '%.*s'\n",
		   (int)(bufend-start), start);
	    break;
	}
    }
    return bufend - buf;
}
Esempio n. 16
0
uint16_t get_str(char *source, const char *begin, uint16_t count, uint16_t length, char *out)
{
    uint16_t i = 0;
    uint16_t len1 = 0;
    uint16_t index1 = 0;
    len1 = find_str((uint8_t *)source, (uint8_t *)begin, count, index1);
    if(len1 != 0)
    {
        for(i = 0; i < length; i++)
            out[i] = source[index1 + len1 + i];
        out[i] = '\0';
    }
    return length;
}
Esempio n. 17
0
int main(void) {
    char buf[MAX_LEN];

    fputs("Search: ", stdout);
    
    if (fgets(buf, MAX_LEN, stdin) == NULL) {
        fprintf(stderr, "Err. when working with string %s\n", buf);
        exit(EXIT_FAILURE);
    }

    remove_newline(buf);
    find_str(buf);

    return(EXIT_SUCCESS);
}
Esempio n. 18
0
void *find_dtb(void *dtbs, const char *compat)
{
	struct fdt_header *d = (struct fdt_header *)dtbs;

	while (d->magic == be_to_cpu(FDT_MAGIC)) {
		if (find_str((char *)d, be_to_cpu(d->totalsize), compat) == 1)
			return d;

		d = (struct fdt_header *)((char *)d + be_to_cpu(d->totalsize));

		/* align to 4-bytes */
		d = (struct fdt_header *)((((unsigned int)d + 0x3) & ~0x3));

	}

	return NULL;
}
Esempio n. 19
0
File: 50.c Progetto: tengben/yyy
int main(void)
{
	char str1[1024];
	char str2[1024];
	char *p;

	printf("please input str1:\n");

	fgets(str1,1024,stdin);

	printf("please input str2:\n");

	fgets(str2,1024,stdin);


	p = find_str(str1,str2);

	printf("the all chars is :%s\n",p);

	return 0;
}
Esempio n. 20
0
File: to_erl.c Progetto: cabrero/otp
/*   to_erl                     run_erl
 *     |                           |
 *     |---------- '\022' -------->| (session start)
 *     |                           |
 *     |<---- "[run_erl v1-0]" ----| (version interval)
 *     |                           |
 *     |--- Esc_"version=1"Esc\ -->| (common version)
 *     |                           |
 */
static int version_handshake(char* buf, int len, int wfd)
{
    unsigned re_high=0, re_low;
    char *end = find_str(buf,len,"]\n");
    
    if (end && sscanf(buf,"[run_erl v%u-%u",&re_high,&re_low)==2) {
	char wbuf[30];
	int wlen;

	if (re_low > RUN_ERL_HI_VER || re_high < RUN_ERL_LO_VER) {
	    fprintf(stderr,"Incompatible versions: to_erl=v%u-%u run_erl=v%u-%u\n",
		    RUN_ERL_HI_VER, RUN_ERL_LO_VER, re_high, re_low);
	    return -1;
	}
	/* Choose highest common version */
	protocol_ver = re_high < RUN_ERL_HI_VER ? re_high : RUN_ERL_HI_VER;

	wlen = sn_printf(wbuf, sizeof(wbuf), "\033_version=%u\033\\",
			 protocol_ver);
	if (write_all(wfd, wbuf, wlen) < 0) {
	    fprintf(stderr,"Failed to send version handshake\n");
	    return -1;
	}
	end += 2;
	len -= (end-buf);
	memmove(buf,end,len);

    }
    else {  /* we assume old run_erl without version handshake */
	protocol_ver = 0;
    }

    if (re_high != RUN_ERL_HI_VER) {
	fprintf(stderr,"run_erl has different version, "
		"using common protocol level %u\n", protocol_ver);
    }

    return len;
}
Esempio n. 21
0
/* Main program */
int
main (int argc, char **argv)
{
  char *opt, *needle = NULL;
  int ret = 0;
  TCHAR lpMessage[4096];

  int invert_search = 0;		/* flag to invert the search */
  int count_lines = 0;			/* flag to whether/not count lines */
  int number_output = 0;		/* flag to print line numbers */
  int ignore_case = 0;			/* flag to be case insensitive */
  int at_start = 0;				/* flag to Match if at the beginning of a line. */
  int at_end = 0;	        	/* flag to Match if at the beginning of a line. */
  int reg_express = 0;		   /* flag to use/not use regular expressions */
  int exact_match = 0;			/* flag to be exact match */
  int sub_dirs= 0;				/* this and all subdirectories */
  int only_fname= 0;			/* print only the name of the file*/
  int literal_search=0;

  FILE *pfile;				/* file pointer */
  int hfind;				/* search handle */
  struct _finddata_t finddata;		/* _findfirst, filenext block */

  /* Scan the command line */
  while ((--argc) && (needle == NULL))
    {
      if (*(opt = *++argv) == '/')
        {
          switch (opt[1])
	    {
	      case 'b':
	      case 'B':		/* Matches pattern if at the beginning of a line */
	        at_start = 1;
	        break;
			
	      //case 'c':
	      //case 'C':		/* Literal? */
	      //  literal_search = 1;
	      //  break;

	      case 'e':
	      case 'E':		/* matches pattern if at end of line */
	        at_end = 1;
	        break;
			
	      case 'i':
	      case 'I':		/* Ignore */
	        ignore_case = 1;
	        break;

	      case 'm':
	      case 'M':		/* only filename */
	        only_fname = 1;
	        break;			
			
	      case 'n':
	      case 'N':		/* Number */
	        number_output = 1;
	        break;
			
	      case 'r':
	      case 'R':		/* search strings as regular expressions */
	        reg_express = 1;
	        break;	

	      case 's':
	      case 'S':		/* search files in child directory too*/
	        sub_dirs = 1;
	        break;				

	      case 'v':
	      case 'V':		/* Not with */
	        invert_search = 1;
	        break;

	      case 'x':
	      case 'X':		/* exact match */
	        exact_match = 1;
	        break;			
			
	      default:
	        usage ();
	        exit (2);		/* syntax error .. return error 2 */
	        break;
	    }
        }
      else
        {
          /* Get the string */
	  if (needle == NULL)
	    {
              /* Assign the string to find */
              needle = *argv;
	    }
	}
    }

  /* Check for search string */
  if (needle == NULL)
    {
      /* No string? */
      usage ();
      exit (1);
    }

  /* Scan the files for the string */
  if (argc == 0)
    {
      ret = find_str (needle, stdin, invert_search, count_lines,
                      number_output, ignore_case, at_start, literal_search, at_end, reg_express, exact_match,
					  sub_dirs, only_fname);
    }

  while (--argc >= 0)
    {
      hfind = _findfirst (*++argv, &finddata);
      if (hfind < 0)
	{
	  /* We were not able to find a file. Display a message and
	     set the exit status. */
	  LoadString( GetModuleHandle(NULL), IDS_NO_SUCH_FILE, (LPTSTR)lpMessage, 4096);
	  CharToOem(lpMessage, lpMessage);
	  fprintf (stderr, lpMessage, *argv);//
	}
      else
        {
          /* repeat find next file to match the filemask */
	  do
            {
              /* We have found a file, so try to open it */
	      if ((pfile = fopen (finddata.name, "r")) != NULL)
	        {
	          printf ("---------------- %s\n", finddata.name);
	          ret = find_str (needle, pfile, invert_search, count_lines,
                      number_output, ignore_case, at_start, literal_search, at_end, reg_express, exact_match,
					  sub_dirs, only_fname);
	          fclose (pfile);
	        }
 	      else
	        {
	          LoadString(GetModuleHandle(NULL), IDS_CANNOT_OPEN, (LPTSTR)lpMessage, 4096);
	          CharToOem(lpMessage, lpMessage);
	          fprintf (stderr, lpMessage,
		           finddata.name);
                }
	    }
          while (_findnext(hfind, &finddata) > 0);
        }
      _findclose(hfind);
    } /* for each argv */

 /* RETURN: If the string was found at least once, returns 0.
  * If the string was not found at all, returns 1.
  * (Note that find_str.c returns the exact opposite values.)
  */
  exit ( (ret ? 0 : 1) );
}
Esempio n. 22
0
t_tweet *parse_mem(char *mem){
   t_tweet *parsed = NULL;
   char *s;
   char *p;
   char tmp[MAX_SIZE];
   int i, j, k, t;

   if(mem){
      s = mem;
      /* commence the parsing */
      i = find_str(s, "{\"results\":[");
      j = find_char(s, ']');
      if((i < 0) || (i + 1) == j){
         /*{"results":[]*/
         /* We're reading bat_sig2 and 
          * there is nothing to see here */
         parsed = NULL;
      } 
      else {
         parsed = (t_tweet *)xmalloc(sizeof(t_tweet));
         memset(tmp, '\0', MAX_SIZE);
         p = s + i + 1;
         p = strncpy(tmp, p, j - i);

         /* Grab the date */
         i = find_str(tmp, "\"created_at\":\"");
         k = find_char(tmp + i + 1, '"');
         parsed->date = (char *)xmalloc((k + 1) * sizeof(char));
         memset(parsed->date, '\0', k + 1);
         parsed->date = strncpy(parsed->date, tmp + i + 1, k);

         /* Grab the id_str to create the URL for the user */
         i = find_str(tmp, "\"id_str\":\"");
         k = find_char(tmp + i + 1, '"');
         t = strlen("https://twitter.com/adamcurry/statuses/");
         p = (char *)xmalloc((t + k + 1) * sizeof(char));
         memset(p, '\0', t + k + 1);
         (void)strcat(p, "https://twitter.com/adamcurry/statuses/");
         (void)strncat(p, tmp + i + 1, k);
         parsed->tweet_url = p;

         /* Now grab the actual tweet */
         i = find_str(tmp, "\"text\":\"");
         k = find_char(tmp + i + 1, '"');
         parsed->text = (char *)xmalloc((k + 1) * sizeof(char));
         memset(parsed->text, '\0', k + 1);
         parsed->text = strncpy(parsed->text, tmp + i + 1, k);

         /* Finally grab the refresh url */
         i = find_str(s + j, "\"refresh_url\":\"");
         t = find_char(s + j + i + 1, '"');
         k = strlen("https://search.twitter.com/search.json");
         p = (char *)xmalloc((k + t + 1) * sizeof(char));
         memset(p, '\0', k + t + 1);
         (void)strcat(p, "https://search.twitter.com/search.json");
         (void)strncat(p, s + j + i + 1, t);
         parsed->refresh = p;
      }
   }
   return parsed;
}
Esempio n. 23
0
bool StringFindReplacer::DoSimpleSearch(const wchar_t* pinput, int startOffset, const wchar_t* pfind_what, size_t flags, int& pos, int& matchLen)
{
#if wxVERSION_NUMBER >= 2900
    std::wstring input    (pinput);
    std::wstring find_what(pfind_what);

    int from = startOffset;
    if (from < 0) {
        from = 0;
    }
    std::wstring str;
    bool search_up = flags & wxSD_SEARCH_BACKWARD;
    if ( !search_up ) {

        if (from >= (int)input.length()) {
            str.clear();
            return false;
        }
        str = input.substr((size_t)from);

    } else {
        if (from >= (int)input.length() ) {
            from = (int)input.length();
        }
        str = input.substr(0, (size_t)from);
    }
#else
    wxString input(pinput);
    wxString find_what(pfind_what);
    std::wstring str = GetString(pinput, startOffset, flags & wxSD_SEARCH_BACKWARD ? true : false).c_str();
#endif

    size_t init_size = str.length();

    if (str.empty()) {
        return false;
    }

    std::wstring find_str(find_what);
    size_t offset(0);

    // incase we are scanning backwared, revert the strings
    if ( flags & wxSD_SEARCH_BACKWARD ) {
        find_str = Reverse(find_str);
        str = Reverse(str);
    } else {
        offset = startOffset;
    }

    bool matchCase = flags & wxSD_MATCHCASE ? true : false;
    if ( !matchCase ) {
        std::transform(find_str.begin(), find_str.end(), find_str.begin(), towlower);
        std::transform(str.begin(), str.end(), str.begin(), towlower);
    }

    size_t upos = str.find(find_str);

    while ( upos != std::wstring::npos ) {
        if (flags & wxSD_MATCHWHOLEWORD) {
            // full word match
            // test that the characeter at upos - 1 & the character at upos + find_str.Len() are not
            // valid word char [a-zA-Z0-9_]
            if (upos > 0) {
                if(isalpha(str[upos-1]) || isdigit(str[upos-1]) || (int)str[upos-1] == (int)'_') {
                    // remove the part that already been scanned
                    // and search again
                    str = str.substr(upos+find_what.length());
                    offset += upos+find_what.length();
                    upos = str.find(find_str);
                    continue;
                }
            }
            int charAfterOff = upos + find_str.length();
            if (charAfterOff < (int)str.length()) {
                if(isalpha(str[charAfterOff]) || isdigit(str[charAfterOff]) || (int)str[charAfterOff] == (int)'_') {
                    // remove the part that already been scanned
                    // and search again
                    str = str.substr(upos+find_what.length());
                    offset += upos+find_what.length();
                    upos = str.find(find_str);
                    continue;
                }
            }

            matchLen = (int)find_str.length();
            // mirror the result as well
            if (flags & wxSD_SEARCH_BACKWARD) {
                upos = (init_size - (upos + offset + matchLen));
            } else {
                upos += offset;
            }
            pos = (int)upos;
            return true;
        } else {
            // we got a match
            matchLen = (int)find_str.length();
            if (flags & wxSD_SEARCH_BACKWARD) {
                upos = (init_size - (upos + offset + matchLen));
            } else {
                upos += offset;
            }
            pos = (int)upos;
            return true;
        }
    }
    return false;
}
Esempio n. 24
0
int main(int argc, void *argv) {
    load_stopwords();
    index_p index = load_index();

    int exit = 0;
    while (!exit) {
        printf(" > ");
        char *command = read_line(stdin);

        if (!strcmp(command, "exit")) {
            // exit command
            exit = 1;
            printf("Exit requested..\n");

		} else if (!strcmp(command, "rebuild index")) {
            // rebuild index command
            rebuild_index(index);
		} else if (starts_with(command, "search for ")) {
            // search for <search_query> command
            char *query = (char *) malloc(strlen(command) - 10);
            memcpy(query, command+11, strlen(command) - 10);

            index_p result = search_index(&index, query);

            printf("Results (showing no more than 10, there might be more):\n");
            if (result) {
                // print result
                int count = 0;
                indexed_word_p w = result->words;
                if (!w) {
                    printf("No documents found for search term %s\n", query);
                }

                while (w) {
                    printf("Documents containing %s:\n", w->stem);

                    int i;
                    for (i = 0; i < w->nr_docs; i++, count++) {
                        printf(" [%d] %s\n", count, result->documents[w->documents[i].id].name);
                    }

                    w = w->next;
                }

                close_index(result);
            } else {
                printf("No documents found for search term %s\n", query);
            }

            free(query);

        } else if (starts_with(command, "add file ")) {
            // add file <file> command
            char *file = (char*) malloc(strlen(command) - 8);
            memcpy(file, command+9, strlen(command) - 8);

			index = add_file(index, file);
            free(file);

        } else if (starts_with(command, "remove file ")) {
            // remove file <file> command
            char *file = (char*) malloc(strlen(command) - 11);
            memcpy(file, command+12, strlen(command) - 11);

            // obtain document id a.k.a. index in filebase
            int doc_id = find_str(&index->documents[0].name, sizeof(indexed_document_t), file, 0, index->nr_docs - 1);

            if (doc_id < 0) {
                printf("Error: %s is not in the filebase!\n", file);
            } else {
                remove_file(index, doc_id);
            }

            free(file);
        }

        free(command);
    }

    // release memory
    release_stopwords();
    close_index(index);

    return 0;
}
Esempio n. 25
0
static int config_set(int key, GVariant *data, const struct sr_dev_inst *sdi,
		const struct sr_channel_group *cg)
{
	struct dev_context *devc;
	struct sr_channel *ch;
	gdouble dval;
	int channel, ret, ival;
	const char *sval;
	gboolean bval;

	if (sdi->status != SR_ST_ACTIVE)
		return SR_ERR_DEV_CLOSED;

	ret = SR_OK;
	devc = sdi->priv;
	if (!cg) {
		/* No channel group: global options. */
		switch (key) {
		case SR_CONF_OUTPUT_CHANNEL:
			sval = g_variant_get_string(data, NULL);
			if ((ival = find_str(sval, channel_modes,
							ARRAY_SIZE(channel_modes))) == -1) {
				ret = SR_ERR_ARG;
				break;
			}
			if (devc->model->channel_modes && (1 << ival) == 0) {
				/* Not supported on this model. */
				ret = SR_ERR_ARG;
			}
			if (ival == devc->channel_mode_set)
				/* Nothing to do. */
				break;
			devc->channel_mode_set = ival;
			devc->config_dirty = TRUE;
			break;
		case SR_CONF_OVER_CURRENT_PROTECTION:
			bval = g_variant_get_boolean(data);
			if (bval == devc->over_current_protection_set)
				/* Nothing to do. */
				break;
			devc->over_current_protection_set = bval;
			devc->config_dirty = TRUE;
			break;
		default:
			return SR_ERR_NA;
		}
	} else {
		/* Channel group specified: per-channel options. */
		/* We only ever have one channel per channel group in this driver. */
		ch = cg->channels->data;
		channel = ch->index;

		switch (key) {
		case SR_CONF_OUTPUT_VOLTAGE_MAX:
			dval = g_variant_get_double(data);
			if (dval < 0 || dval > devc->model->channels[channel].voltage[1])
				ret = SR_ERR_ARG;
			devc->config[channel].output_voltage_max = dval;
			devc->config_dirty = TRUE;
			break;
		case SR_CONF_OUTPUT_CURRENT_MAX:
			dval = g_variant_get_double(data);
			if (dval < 0 || dval > devc->model->channels[channel].current[1])
				ret = SR_ERR_ARG;
			devc->config[channel].output_current_max = dval;
			devc->config_dirty = TRUE;
			break;
		case SR_CONF_OUTPUT_ENABLED:
			bval = g_variant_get_boolean(data);
			if (bval == devc->config[channel].output_enabled_set)
				/* Nothing to do. */
				break;
			devc->config[channel].output_enabled_set = bval;
			devc->config_dirty = TRUE;
			break;
		default:
			ret = SR_ERR_NA;
		}
	}


	return ret;
}
Esempio n. 26
0
/*
 * Parses a file and adds its words to the index
 */
void parse_file_for_index(index_p index, char *file) {
    // open file or print error message
    FILE *f = fopen(file, "r");
    if (!f) {
        printf("Cannot open %s!\nIndex not updated.\n", file);
        return;
    }

    // document id = index of document in list of all documents in filebase (alphabetically ordered)
    int doc_id = find_str(&index->documents[0].name, sizeof(indexed_document_t), file, 0, index->nr_docs-1);

    if (doc_id < 0) {
        printf("Error: %s is not in the filebase!\n", file);
        return;
    }

    char *l;
    while ((l = read_line(f))) {
        // turn non alpha characters into spaces
        nonalpha_to_space(l);

        char *word = strtok(l, " ");
        while (word) {
            // ignore stopwords
            if (is_stopword(word)) {
                word = strtok(NULL, " ");
                continue;
            }

            char *word_stem = stem(word);

            if (!strlen(word_stem)) {
                word = strtok(NULL, " ");
                continue;
            }

            // insert document into index / add new stem to index
            indexed_word_p w = index->words;    // current word
            indexed_word_p p = NULL;            // previous word
            int flag = 0;
            while (w && !flag) {
                int cmp = strcmp(w->stem, word_stem);
                if (!cmp) {
                    // stem is already indexed
                    flag = 1;
                    break;
                } else if (0 < cmp) {
                    // stem not indexed yet
                    flag = 2;
                    break;
                }

                p = w;
                w = w->next;
            }

            if (flag == 1) {
                // stem indexed, add document to list
                int i;
                for (i = 0; i < w->nr_docs; i++) {
                    if (w->documents[i].id == doc_id) {
                        // document is already indexed for this stem
                        flag = 0;
                        break;
                    } else if (w->documents[i].id > doc_id) {
                        break;
                    }
                }

                // only add document to list if it's not already in the list
                if (flag) {
                    w = (indexed_word_p) realloc(w, sizeof(indexed_word_t) + sizeof(doc_t) * (w->nr_docs + 1));

                    // update pointer to this group (needed after realloc)
                    if (!p) {
                        index->words = w;
                    } else {
                        p->next = w;
                    }

                    // insert document in list
                    memmove(&w->documents[i+1], &w->documents[i], sizeof(doc_t) * (w->nr_docs - i));
                    w->documents[i].id = doc_id;
                    w->documents[i].tf = 1;
                    w->nr_docs++;
                } else {
                    // increase counter for number of occurances of this word in this document
                    w->documents[i].tf++;
                }

                free(word_stem);
            } else {
                // stem is not indexed, add it to index
                w = (indexed_word_p) malloc(sizeof(indexed_word_t) + sizeof(doc_t));
                w->stem = word_stem;
                w->nr_docs = 1;
                w->documents[0].id = doc_id;
                w->documents[0].tf = 1;

                index->nr_words++;

                // insert this word in linked list
                if (!p) {
                    w->next = index->words;
                    index->words = w;
                } else {
                    w->next = p->next;
                    p->next = w;
                }
            }

            // increase counter for total number of words in this document
            index->documents[doc_id].nr_words++;

            // get next word
            word = strtok(NULL, " ");
        }

        free(l);
    }

    fclose(f);

    // finalize computation of TF
    indexed_word_p w = index->words;
    while (w) {

        int i = find_int(&w->documents[0].id, sizeof(doc_t), doc_id, 0, w->nr_docs - 1);

        if (i >= 0) {
            w->documents[i].tf /= index->documents[doc_id].nr_words;
        }

        w = w->next;
    }
}
Esempio n. 27
0
// Check location information
static int check_datapool_location(FILE *ifp, char **header_line, int *n)
{
  dbf_header_t *dbf;
  int ii, nCols;
  char *header = (char *) MALLOC(sizeof(char)*1024);
  fgets(header, 1024, ifp);
  strip_end_whitesp(header);
  int nColumns = get_number_columns(header);

  // Read configuration file
  read_header_config("DATAPOOL", &dbf, &nCols);

  // ensure we have the columns we need
  int granule_col = find_str(header, "Granule Name");
  int near_start_lat_col = find_str(header, "Near Start Lat");
  int near_start_lon_col = find_str(header, "Near Start Lon");
  int far_start_lat_col = find_str(header, "Far Start Lat");
  int far_start_lon_col = find_str(header, "Far Start Lon");
  int near_end_lat_col = find_str(header, "Near End Lat");
  int near_end_lon_col = find_str(header, "Near End Lon");
  int far_end_lat_col = find_str(header, "Far End Lat");
  int far_end_lon_col = find_str(header, "Far End Lon");

  // Check whether all visible columns are actually available in the file
  for (ii=0; ii<nCols; ii++) {
    if (find_str(header, dbf[ii].header) < 0)
      dbf[ii].visible = FALSE;
  }

  int all_ok=TRUE;
  if (granule_col < 0) {
    printf("Missing: Granule Name\n");
    all_ok=FALSE;
  }
  if (near_start_lat_col < 0) {
    printf("Missing: Near Start Lat\n");
    all_ok=FALSE;
  }
  if (near_start_lon_col < 0) {
    printf("Missing: Near Start Lon\n");
    all_ok=FALSE;
  }
  if (far_start_lat_col < 0) {
    printf("Missing: Far Start Lat\n");
    all_ok=FALSE;
  }
  if (far_start_lon_col < 0) {
    printf("Missing: Far Start Lon\n");
    all_ok=FALSE;
  }
  if (near_end_lat_col < 0) {
    printf("Missing: Near End Lat\n");
    all_ok=FALSE;
  }
  if (near_end_lon_col < 0) {
    printf("Missing: Near End Lon\n");
    all_ok=FALSE;
  }
  if (far_end_lat_col < 0) {
    printf("Missing: Far End Lat\n");
    all_ok=FALSE;
  }
  if (far_end_lon_col < 0) {
    printf("Missing: Far End Lon\n");
    all_ok=FALSE;
  }
  if (!all_ok) {
    printf("Required data columns missing, cannot process this file.\n");
    return 0;
  }
  *header_line = header;
  *n = nColumns;

  return 1;
}
Esempio n. 28
0
static int
pline(char *ib, nms_t *list)
{
	char	*rpt;
	char	*bpt;
	nms_t	*entry;
	int	rv = 0;
	int	done;
	int	len;
	char	*v;
	/*
	 * Skip over any stuff at the beginning of the line before a leading
	 * '/' If we don't find a '/', the line is malformed and we just skip
	 * it.
	 */
	while (*ib) {
		if (*ib != '/')
			ib++;
		else
			break;
	}
	if (!(*ib))
		goto done;

	/*
	 * Find the trailing '"' in the line. If not found, we just
	 * skip the line.
	 */

	rpt = strchr(ib, (int)'""');
	if (rpt != NULL)
		rpt = strchr(rpt, (int)'""');

	/*
	 * Find a matching entry in the list of names from /dev/dsk.
	 * If no match, we're not interested.
	 */
	if (!rpt)
		goto done;

	*rpt = '\0';


	if ((entry = find_str(ib, list)) == (nms_t *)NULL)
		goto done;

	bpt = rpt;
	/*
	 * Extract the device number at the end of
	 * the line. We expect whitespace followed by
	 * the beginning of the currently numeric
	 * device id string;
	 */
	rpt++;
	done = 0;
	while (!done) {
		if (*rpt) {
			if (*rpt != '\n') {
				if (isspace((int)*rpt))
					rpt++;
				else
					done++;
			} else
				done++;
		} else
			done++;
	}
	/*
	 * Should now be at the beginning of the
	 * device number. Point entry->dn at the
	 * string.
	 */
	if (*rpt) {
		v = rpt;
		len = 0;
		while (v) {
			if (*v != '\n') {
				v++;
				len++;
			} else {
				*v = '\0';
				v = (char *)NULL;
			}
		}
		if (len) {
			entry->dnum = atoi(rpt);
			while (bpt > ib) {
				if (*bpt != '@')
					bpt--;
				else
					break;
			}
			if (bpt > ib) {
				*bpt-- = '\0';
				len = 0;
				while (bpt > ib) {
					if (*bpt != '/') {
						bpt--;
						len++;
					} else
						break;
				}
				if (bpt > ib) {
					bpt++;
					len++;
					entry->dty = (char *)malloc(len);
					if (entry->dty) {
						(void) strcpy(entry->dty, bpt);
						rv++;
					}
				}
			}
		}
	}
done:
	return (rv);
}
Esempio n. 29
0
/* 
   Read the RC file and configure the corresponding variables 
*/
void rcfile_read(void)
{
	FILE *txt;
	char buffer[256];
	char *p;
	int l=0;

	rcfile_get_path(&rc_file);

	txt=fopen(rc_file, "rt");
	g_free(rc_file);
	if(txt == NULL) {
		tiemu_info(_("Configuration file not found, use default values. You can create one by the 'File|Save config' command menu."));
		return;
	}

	while(!feof(txt)) {
		if (!fgets(buffer, 256, txt))
			break;
		l++;
		buffer[strlen(buffer)-1]='\0';

	if(!strcmp(buffer, "RC_END")) {
	  fclose(txt);
	  return;
	}

	if(buffer[0]=='#' || !strlen(buffer)) continue;
      
	/* Common part with TiLP: hardware section */
	if ((p = find_str(buffer, "cable_model="))) 
	{
		linkp.cable_model = ticables_string_to_model(p);
		continue;
	}
	
	if ((p = find_str(buffer, "cable_port="))) 
	{
		linkp.cable_port = ticables_string_to_port(p);
		continue;
	}
	
	if ((p = find_str(buffer, "cable_timeout="))) 
	{
		sscanf(p, "%i", &(linkp.cable_timeout));
		continue;
	}
	
	if ((p = find_str(buffer, "cable_delay="))) {
		sscanf(p, "%i", &(linkp.cable_delay));
		continue;
	}

	if( (p=find_str(buffer, "qs_file=")) ) 
	{
	  g_free(options.qs_file);
	  options.qs_file = g_strdup(p);
	  continue;
	}

	if( (p=find_str(buffer, "qs_enabled=")) ) 
	{
	  sscanf(p, "%i", &(options.qs_enabled));
	  continue;
	}

      /* GtkTiEmu specific part: emulator section */
	if( (p=find_str(buffer, "rom_file=")) ) 
	{
	  g_free(params.rom_file);
	  params.rom_file = g_strdup(p);
	  continue;
	}

	if( (p=find_str(buffer, "img_file=")) ) 
	{
	  g_free(params.rom_file);
	  params.rom_file = g_strdup(p);
	  continue;
	}

	if( (p=find_str(buffer, "tib_file=")) )
	{
	  g_free(params.tib_file);
	  params.tib_file = g_strdup(p);
	  continue;
	}

    if( (p=find_str(buffer, "sav_file=")) )
	{
	  g_free(params.sav_file);
	  params.sav_file = g_strdup(p);
	  continue;
	}

	if( (p=find_str(buffer, "skin=")) ) 
	{
	  sscanf(p, "%i", &(options.skin));
	  continue;
	}

	if( (p=find_str(buffer, "view_mode=")) )
	{
	  if(!strcmp(p, "normal")) options.view = VIEW_NORMAL;
	  else if(!strcmp(p, "large")) options.view = VIEW_LARGE;
	  else if(!strcmp(p, "full")) options.view = VIEW_FULL;
	  else if(!strncmp(p, "custom", strlen("custom"))) 
	  {
		  //char *q;
		  options.view = VIEW_CUSTOM;
		  p=find_str(buffer, "view_mode=custom");
		  /*q = strchr(p, ',');
		  if(q) *q = '.';*/
		  sscanf(p, " (%f)", &(options.scale));
		  if(options.scale < 0.01)
			  options.scale = 1.0;
	  }
	  else stop(l);
	  continue;
	}

	if( (p=find_str(buffer, "cpu_rate=")) )
	{
	  sscanf(p, "%u", &(params.cpu_rate));
	  continue;
	}

	if( (p=find_str(buffer, "hw_rate=")) )
	{
	  sscanf(p, "%u", &(params.hw_rate));
	  continue;
	}

	if( (p=find_str(buffer, "lcd_rate=")) )
	{
	  sscanf(p, "%i", &(params.lcd_rate));
	  continue;
	}

	if( (p=find_str(buffer, "hw_protect=")) )
	{
	  sscanf(p, "%i", &(params.hw_protect));
	  continue;
	}

	if( (p=find_str(buffer, "img_format=")) )
	{
	  if(!strcmp(p, "jpg")) options2.format=IMG_JPG;
	  else if(!strcmp(p, "png")) options2.format=IMG_PNG;
	  else if(!strcmp(p, "ico")) options2.format=IMG_ICO;
	  else if(!strcmp(p, "eps")) options2.format=IMG_EPS;
	  else if(!strcmp(p, "pdf")) options2.format=IMG_PDF;
	  else if(!strcmp(p, "bmp")) options2.format=IMG_BMP;
	  else stop(l);
	  continue;
	}
      
	if( (p=find_str(buffer, "img_type=")) )
	{
	  if(!strcmp(p, "bw")) options2.type = IMG_BW;
	  else if(!strcmp(p, "color")) options2.type = IMG_COL;
	  else stop(l);
	  continue;
	}
      
	if( (p=find_str(buffer, "img_size=")) )
	{
	  if(!strcmp(p, "lcd")) options2.size = IMG_LCD;
	  else if(!strcmp(p, "skin")) options2.size = IMG_SKIN;
	  else stop(l);
	  continue;
	}

	if( (p=find_str(buffer, "screen_folder=")) )
	{
	  g_free(options2.folder);
	  options2.folder = g_strdup(p);
	  continue;
	}
      
	if( (p=find_str(buffer, "screen_file=")) )
	{
	  g_free(options2.file);
	  options2.file = g_strdup(p);
	  continue;
	}
      
	if( (p=find_str(buffer, "screen_counter=")) )
	{
	  sscanf(p, "%i", &(options2.counter));
	  continue;
	}

	if( (p=find_str(buffer, "screen_shots=")) )
	{
	  sscanf(p, "%i", &(options2.shots));
	  continue;
	}

	if( (p=find_str(buffer, "screen_skips=")) )
	{
	  sscanf(p, "%i", &(options2.skips));
	  continue;
	}

	if( (p=find_str(buffer, "clipboard=")) )
	{
	  if(!strcmp(p, "no")) options2.clipboard = 0;
	  else if(!strcmp(p, "yes")) options2.clipboard = 1;

	  continue;
	}
	
	if( (p=find_str(buffer, "console=")) )
	{
	  if(!strcmp(p, "no")) options.console = 0;
	  else if(!strcmp(p, "yes")) options.console = 1;
	  else if(!strcmp(p, "boot")) options.console = 2;
	  else stop(l);
	  continue;
	}

	if( (p=find_str(buffer, "kbd_dbg=")) )
	{
	  if(!strcmp(p, "no")) options.kbd_dbg = 0;
	  else if(!strcmp(p, "yes")) options.kbd_dbg = 1;
	}

	if( (p=find_str(buffer, "fs_type=")) )
	{
	  if(!strcmp(p, "old")) options.fs_type = 0;
	  else if(!strcmp(p, "new")) options.fs_type = 1;
	  else if(!strcmp(p, "native") || !strcmp(p, "win32")) options.fs_type = 2;
	  else if(!strcmp(p, "kde")) options.fs_type = 3;
	}
	
	if( (p=find_str(buffer, "skin_file=")) )
	{
	  g_free(options.skin_file);
	  options.skin_file = g_strdup(p);
	  continue;
	}

    if( (p=find_str(buffer, "keys_file=")) )
	{
	  g_free(options.keys_file);
	  options.keys_file = g_strdup(p);
	  continue;
	}

	if( (p=find_str(buffer, "calc_wnd=")) )
	{
	  sscanf(p, "(%i;%i;%i;%i;%i;%i)", 
		  &(options3.calc.rect.x), &(options3.calc.rect.y), 
		  &(options3.calc.rect.w), &(options3.calc.rect.h),
		  &(options3.calc.minimized), &(options3.calc.closed)
		  );
	  continue;
	}

	if( (p=find_str(buffer, "bkpts_wnd=")) )
	{
	  sscanf(p, "(%i;%i;%i;%i;%i;%i)", 
		  &(options3.bkpts.rect.x), &(options3.bkpts.rect.y), 
		  &(options3.bkpts.rect.w), &(options3.bkpts.rect.h),
		  &(options3.bkpts.minimized), &(options3.bkpts.closed)
		  );
	  continue;
	}
	if( (p=find_str(buffer, "code_wnd=")) )
	{
	  sscanf(p, "(%i;%i;%i;%i;%i;%i)", 
		  &(options3.code.rect.x), &(options3.code.rect.y), 
		  &(options3.code.rect.w), &(options3.code.rect.h),
		  &(options3.code.minimized), &(options3.code.closed));
	  continue;
	}
	if( (p=find_str(buffer, "mem_wnd=")) )
	{
	  sscanf(p, "(%i;%i;%i;%i;%i;%i)", 
		  &(options3.mem.rect.x), &(options3.mem.rect.y), 
		  &(options3.mem.rect.w), &(options3.mem.rect.h),
		  &(options3.mem.minimized), &(options3.mem.closed));
	  continue;
	}
	if( (p=find_str(buffer, "regs_wnd=")) )
	{
	  sscanf(p, "(%i;%i;%i;%i;%i;%i)", 
		  &(options3.regs.rect.x), &(options3.regs.rect.y), 
		  &(options3.regs.rect.w), &(options3.regs.rect.h),
		  &(options3.regs.minimized), &(options3.regs.closed));
	  continue;
	}
	if( (p=find_str(buffer, "pclog_wnd=")) )
	{
	  sscanf(p, "(%i;%i;%i;%i;%i;%i)", 
		  &(options3.pclog.rect.x), &(options3.pclog.rect.y), 
		  &(options3.pclog.rect.w), &(options3.pclog.rect.h),
		  &(options3.pclog.minimized), &(options3.pclog.closed));
	  continue;
	}
	if( (p=find_str(buffer, "stack_wnd=")) )
	{
	  sscanf(p, "(%i;%i;%i;%i;%i;%i)", 
		  &(options3.stack.rect.x), &(options3.stack.rect.y), 
		  &(options3.stack.rect.w), &(options3.stack.rect.h),
		  &(options3.stack.minimized), &(options3.stack.closed));
	  continue;
	}
	if( (p=find_str(buffer, "heap_wnd=")) )
	{
	  sscanf(p, "(%i;%i;%i;%i;%i;%i)", 
		  &(options3.heap.rect.x), &(options3.heap.rect.y), 
		  &(options3.heap.rect.w), &(options3.heap.rect.h),
		  &(options3.heap.minimized), &(options3.heap.closed));
	  continue;
	}	
	if( (p=find_str(buffer, "iop_wnd=")) )
	{
	  sscanf(p, "(%i;%i;%i;%i;%i;%i)", 
		  &(options3.iop.rect.x), &(options3.iop.rect.y), 
		  &(options3.iop.rect.w), &(options3.iop.rect.h),
		  &(options3.iop.minimized), &(options3.iop.closed));
	  continue;
	}
	if( (p=find_str(buffer, "dock_wnd=")) )
	{
	  sscanf(p, "(%i;%i;%i;%i;%i;%i)", 
		  &(options3.dock.rect.x), &(options3.dock.rect.y), 
		  &(options3.dock.rect.w), &(options3.dock.rect.h),
		  &(options3.dock.minimized), &(options3.dock.closed));
	  continue;
	}
	if( (p=find_str(buffer, "wnd_transient=")) )
	{
	  if(!strcmp(p, "no")) options3.transient = 0;
	  else if(!strcmp(p, "yes")) options3.transient = 1;
	  else stop(l);
	  continue;
	}

	if( (p=find_str(buffer, "dbg_font_type=")) )
	{
	  if(!strcmp(p, "default")) options3.dbg_font_type = 0;
	  else if(!strcmp(p, "custom")) options3.dbg_font_type = 1;
	  else stop(l);
	  continue;
	}
	if( (p=find_str(buffer, "dbg_font_name=")) )
	{
		g_free(options3.dbg_font_name);
		options3.dbg_font_name = g_strdup(p);
		continue;
	}

	if( (p=find_str(buffer, "dbg_dock=")) )
	{
	  if(!strcmp(p, "no")) options3.dbg_dock = 0;
	  else if(!strcmp(p, "yes")) options3.dbg_dock = 1;
	  else stop(l);
	  continue;
	}

    }
  fclose(txt);

  return;
}
Esempio n. 30
0
int to_erl(int argc, char **argv)
{
    char  FIFO1[FILENAME_MAX], FIFO2[FILENAME_MAX];
    int i, len, wfd, rfd;
    char pipename[FILENAME_MAX];
    int pipeIx = 1;
    int force_lock = 0;
    int got_some = 0;

#ifdef __OSE__
    struct aiocb stdin_read_req, pipe_read_req;
    FmHandle stdin_fh, pipe_fh;
    char *stdin_buf, *pipe_buf;
    char *buf;
    union SIGNAL *sig;
#else /* __UNIX__ */
    char buf[BUFSIZ];
    fd_set readfds;
#endif

    if (argc >= 2 && argv[1][0]=='-') {
	switch (argv[1][1]) {
	case 'h':
	    usage(argv[0]);
	    exit(1);
	case 'F':
	    force_lock = 1;
	    break;
	default:
	    fprintf(stderr,"Invalid option '%s'\n",argv[1]);
	    exit(1);
	}
	pipeIx = 2;
    }

#ifdef DEBUG
    fprintf(stderr, "%s: pid is : %d\n", argv[0],(int)
#ifdef __OSE__
	    current_process()
#else /* __UNIX__ */
	    getpid()
#endif
	    );
#endif

    strn_cpy(pipename, sizeof(pipename),
	     (argv[pipeIx] ? argv[pipeIx] : PIPE_DIR));

    if(*pipename && pipename[strlen(pipename)-1] == '/') {
	/* The user wishes us to find a pipe name in the specified */
	/* directory */
	int highest_pipe_num = 0;
	DIR *dirp;
	struct dirent *direntp;

	dirp = opendir(pipename);
	if(!dirp) {
	    fprintf(stderr, "Can't access pipe directory %s: %s\n", pipename, strerror(errno));
	    exit(1);
	}

	/* Check the directory for existing pipes */

	while((direntp=readdir(dirp)) != NULL) {
	    if(strncmp(direntp->d_name,PIPE_STUBNAME,PIPE_STUBLEN)==0) {
		int num = atoi(direntp->d_name+PIPE_STUBLEN+1);
		if(num > highest_pipe_num)
		    highest_pipe_num = num;
	    }
	}
	closedir(dirp);
	strn_catf(pipename, sizeof(pipename), (highest_pipe_num?"%s.%d":"%s"),
		  PIPE_STUBNAME, highest_pipe_num);
    } /* if */

    /* read FIFO */
    sn_printf(FIFO1,sizeof(FIFO1),"%s.r",pipename);
    /* write FIFO */
    sn_printf(FIFO2,sizeof(FIFO2),"%s.w",pipename);

#ifndef __OSE__
    /* Check that nobody is running to_erl on this pipe already */
    if ((wfd = open (FIFO1, O_WRONLY|DONT_BLOCK_PLEASE, 0)) >= 0) {
	/* Open as server succeeded -- to_erl is already running! */
	close(wfd);
	fprintf(stderr, "Another to_erl process already attached to pipe "
			"%s.\n", pipename);
	if (force_lock) {
	    fprintf(stderr, "But we proceed anyway by force (-F).\n");
	}
	else {
	    exit(1);
	}
    }
#endif

    if ((rfd = open (FIFO1, O_RDONLY|DONT_BLOCK_PLEASE, 0)) < 0) {
#ifdef DEBUG
	fprintf(stderr, "Could not open FIFO %s for reading.\n", FIFO1);
#endif
	fprintf(stderr, "No running Erlang on pipe %s: %s\n", pipename, strerror(errno));
	exit(1);
    }
#ifdef DEBUG
    fprintf(stderr, "to_erl: %s opened for reading\n", FIFO1);
#endif

    if ((wfd = open (FIFO2, O_WRONLY|DONT_BLOCK_PLEASE, 0)) < 0) {
#ifdef DEBUG
	fprintf(stderr, "Could not open FIFO %s for writing.\n", FIFO2);
#endif
	fprintf(stderr, "No running Erlang on pipe %s: %s\n", pipename, strerror(errno));
	close(rfd);
	exit(1);
    }
#ifdef DEBUG
    fprintf(stderr, "to_erl: %s opened for writing\n", FIFO2);
#endif

#ifndef __OSE__
    fprintf(stderr, "Attaching to %s (^D to exit)\n\n", pipename);
#else
    fprintf(stderr, "Attaching to %s (^C to exit)\n\n", pipename);
#endif

#ifndef __OSE__
    /* Set break handler to our handler */
    signal(SIGINT,handle_ctrlc);

    /*
     * Save the current state of the terminal, and set raw mode.
     */
    if (tcgetattr(0, &tty_rmode) , 0) {
	fprintf(stderr, "Cannot get terminals current mode\n");
	exit(-1);
    }
    tty_smode = tty_rmode;
    tty_eof = '\004'; /* Ctrl+D to exit */
#ifdef DEBUG
    show_terminal_settings(&tty_rmode);
#endif
    tty_smode.c_iflag =
	1*BRKINT |/*Signal interrupt on break.*/
	    1*IGNPAR |/*Ignore characters with parity errors.*/
		1*ISTRIP |/*Strip character.*/
		    0;

#if 0
0*IGNBRK |/*Ignore break condition.*/
0*PARMRK |/*Mark parity errors.*/
0*INPCK  |/*Enable input parity check.*/
0*INLCR  |/*Map NL to CR on input.*/
0*IGNCR  |/*Ignore CR.*/
0*ICRNL  |/*Map CR to NL on input.*/
0*IUCLC  |/*Map upper-case to lower-case on input.*/
0*IXON   |/*Enable start/stop output control.*/
0*IXANY  |/*Enable any character to restart output.*/
0*IXOFF  |/*Enable start/stop input control.*/
0*IMAXBEL|/*Echo BEL on input line too long.*/
#endif

    tty_smode.c_oflag =
	1*OPOST  |/*Post-process output.*/
	    1*ONLCR  |/*Map NL to CR-NL on output.*/
#ifdef XTABS
		1*XTABS  |/*Expand tabs to spaces. (Linux)*/
#endif
#ifdef OXTABS
		    1*OXTABS  |/*Expand tabs to spaces. (FreeBSD)*/
#endif
#ifdef NL0
			1*NL0    |/*Select newline delays*/
#endif
#ifdef CR0
			    1*CR0    |/*Select carriage-return delays*/
#endif
#ifdef TAB0
				1*TAB0   |/*Select horizontal tab delays*/
#endif
#ifdef BS0
				    1*BS0    |/*Select backspace delays*/
#endif
#ifdef VT0
					1*VT0    |/*Select vertical tab delays*/
#endif
#ifdef FF0
					    1*FF0    |/*Select form feed delays*/
#endif
											    0;

#if 0
0*OLCUC  |/*Map lower case to upper on output.*/
0*OCRNL  |/*Map CR to NL on output.*/
0*ONOCR  |/*No CR output at column 0.*/
0*ONLRET |/*NL performs CR function.*/
0*OFILL  |/*Use fill characters for delay.*/
0*OFDEL  |/*Fill is DEL, else NULL.*/
0*NL1    |
0*CR1    |
0*CR2    |
0*CR3    |
0*TAB1   |
0*TAB2   |
0*TAB3   |/*Expand tabs to spaces.*/
0*BS1    |
0*VT1    |
0*FF1    |
#endif

    /* JALI: removed setting the tty_smode.c_cflag flags, since this is not */
    /* advisable if this is a *real* terminal, such as the console. In fact */
    /* this may hang the entire machine, deep, deep down (signalling break */
    /* or toggling the abort switch doesn't help) */

    tty_smode.c_lflag =
									0;

#if 0
0*ISIG   |/*Enable signals.*/
0*ICANON |/*Canonical input (erase and kill processing).*/
0*XCASE  |/*Canonical upper/lower presentation.*/
0*ECHO   |/*Enable echo.*/
0*ECHOE  |/*Echo erase character as BS-SP-BS.*/
0*ECHOK  |/*Echo NL after kill character.*/
0*ECHONL |/*Echo NL.*/
0*NOFLSH |/*Disable flush after interrupt or quit.*/
0*TOSTOP |/*Send SIGTTOU for background output.*/
0*ECHOCTL|/*Echo control characters as ^char, delete as ^?.*/
0*ECHOPRT|/*Echo erase character as character erased.*/
0*ECHOKE |/*BS-SP-BS erase entire line on line kill.*/
0*FLUSHO |/*Output is being flushed.*/
0*PENDIN |/*Retype pending input at next read or input character.*/
0*IEXTEN |/*Enable extended (implementation-defined) functions.*/
#endif

    tty_smode.c_cc[VMIN]      =0;/* Note that VMIN is the same as VEOF! */
    tty_smode.c_cc[VTIME]     =0;/* Note that VTIME is the same as VEOL! */
    tty_smode.c_cc[VINTR]     =3;

    tcsetattr(0, TCSADRAIN, &tty_smode);

#ifdef DEBUG
    show_terminal_settings(&tty_smode);
#endif

#endif /* !__OSE__ */
    /*
     * 	 "Write a ^L to the FIFO which causes the other end to redisplay
     *    the input line."
     * This does not seem to work as was intended in old comment above.
     * However, this control character is now (R12B-3) used by run_erl
     * to trigger the version handshaking between to_erl and run_erl
     * at the start of every new to_erl-session.
     */

    if (write(wfd, "\014", 1) < 0) {
	fprintf(stderr, "Error in writing ^L to FIFO.\n");
    }

#ifdef __OSE__
    /* we have a tiny stack so we malloc the buffers */
    stdin_buf = malloc(sizeof(char) * BUFSIZ);
    pipe_buf = malloc(sizeof(char) * BUFSIZ);

    efs_examine_fd(rfd,FLIB_FD_HANDLE,&pipe_fh);
    efs_examine_fd(0,FLIB_FD_HANDLE,&stdin_fh);
    READ_AIO(stdin_read_req,0,BUFSIZ,stdin_buf);
    READ_AIO(pipe_read_req,rfd,BUFSIZ,pipe_buf);
#endif

    /*
     * read and write
     */
    while (1) {
#ifndef __OSE__
	FD_ZERO(&readfds);
	FD_SET(0, &readfds);
	FD_SET(rfd, &readfds);
	if (select(rfd + 1, &readfds, NULL, NULL, NULL) < 0) {
	    if (recv_sig) {
		FD_ZERO(&readfds);
	    }
	    else {
		fprintf(stderr, "Error in select.\n");
		break;
	    }
	}
	len = 0;

	/*
	 * Read from terminal and write to FIFO
         */
	if (recv_sig) {
	    switch (recv_sig) {
	    case SIGINT:
		fprintf(stderr, "[Break]\n\r");
		buf[0] = '\003';
		len = 1;
		break;
	    case SIGWINCH:
		len = window_size_seq(buf,sizeof(buf));
		break;
	    default:
		fprintf(stderr,"Unexpected signal: %u\n",recv_sig);
	    }
	    recv_sig = 0;
	}
	else
#else /* __OSE__ */
	SIGSELECT sigsel[] = {0};
	sig = receive(sigsel);
	len = 0;
#endif
#ifndef __OSE__
	  if (FD_ISSET(0,&readfds)) {
	    len = read(0, buf, sizeof(buf));
#else /* __OSE__ */
	  if (sig->signo == FM_READ_PTR_REPLY &&
	      sig->fm_read_ptr.handle == stdin_fh) {
	    len = sig->fm_read_ptr.status == EFS_SUCCESS ? sig->fm_read_ptr.actual : -1;
	    buf = sig->fm_read_ptr.buffer;
#endif
	    if (len <= 0) {
		close(rfd);
		close(wfd);
		if (len < 0) {
		    fprintf(stderr, "Error in reading from stdin.\n");
		} else {
		    fprintf(stderr, "[EOF]\n\r");
		}
		break;
	    }
	    /* check if there is an eof character in input */
	    for (i = 0; i < len-1 && buf[i] != tty_eof; i++);
	    if (buf[i] == tty_eof) {
		fprintf(stderr, "[Quit]\n\r");
		break;
	    }
	}

	if (len) {
#ifdef DEBUG
	    if(write(1, buf, len));
#endif
	    if (write_all(wfd, buf, len) != len) {
		fprintf(stderr, "Error in writing to FIFO.\n");
		close(rfd);
		close(wfd);
		break;
	    }
	    STATUS("\" OK\r\n");
#ifdef __OSE__
	    aio_dispatch(sig);
	    READ_AIO(stdin_read_req, 0, BUFSIZ, stdin_buf);
#endif
	}

	/*
	 * Read from FIFO, write to terminal.
	 */
#ifndef __OSE__
	if (FD_ISSET(rfd, &readfds)) {
	    STATUS("FIFO read: ");
	    len = read(rfd, buf, BUFSIZ);
#else /* __OSE__ */
        if (sig->signo == FM_READ_PTR_REPLY &&
	    sig->fm_read_ptr.handle == pipe_fh) {
	    len = sig->fm_read_ptr.status == EFS_SUCCESS ? sig->fm_read_ptr.actual : -1;
	    buf = sig->fm_read_ptr.buffer;
#endif
	    if (len < 0 && errno == EAGAIN) {
		/*
		 * No data this time, but the writing end of the FIFO is still open.
		 * Do nothing.
		 */
		;
	    } else if (len <= 0) {
		/*
		 * Either an error or end of file. In either case, break out
		 * of the loop.
		 */
		close(rfd);
		close(wfd);
		if (len < 0) {
		    fprintf(stderr, "Error in reading from FIFO.\n");
		} else
		    fprintf(stderr, "[End]\n\r");
		break;
	    } else {
		if (!got_some) {
		    if ((len=version_handshake(buf,len,wfd)) < 0) {
			close(rfd);
			close(wfd);
			break;
		    }
#ifndef __OSE__
		    if (protocol_ver >= 1) {
			/* Tell run_erl size of terminal window */
			signal(SIGWINCH, handle_sigwinch);
			raise(SIGWINCH);
		    }
#endif
		    got_some = 1;
		}

		/*
		 * We successfully read at least one character. Write what we got.
		 */
		STATUS("Terminal write: \"");
		if (write_all(1, buf, len) != len) {
		    fprintf(stderr, "Error in writing to terminal.\n");
		    close(rfd);
		    close(wfd);
		    break;
		}
		STATUS("\" OK\r\n");
#ifdef __OSE__
		aio_dispatch(sig);
		READ_AIO(pipe_read_req, rfd, BUFSIZ, pipe_buf);
#endif
	    }
	}
    }

#ifndef __OSE__
    /*
     * Reset terminal characterstics
     * XXX
     */
    tcsetattr(0, TCSADRAIN, &tty_rmode);
#endif
    return 0;
}

/* Call write() until entire buffer has been written or error.
 * Return len or -1.
 */
static int write_all(int fd, const char* buf, int len)
{
    int left = len;
    int written;
    while (left) {
	written = write(fd,buf,left);
	if (written < 0) {
	    return -1;
	}
	left -= written;
	buf += written;
    }
    return len;
}

#ifndef __OSE__
static int window_size_seq(char* buf, size_t bufsz)
{
#ifdef TIOCGWINSZ
    struct winsize ws;
    static const char prefix[] = "\033_";
    static const char suffix[] = "\033\\";
    /* This Esc sequence is called "Application Program Command"
       and seems suitable to use for our own customized stuff. */

    if (ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == 0) {
	int len = sn_printf(buf, bufsz, "%swinsize=%u,%u%s",
			    prefix, ws.ws_col, ws.ws_row, suffix);
	return len;
    }
#endif /* TIOCGWINSZ */
    return 0;
}
#endif /* !__OSE__ */

/*   to_erl                     run_erl
 *     |                           |
 *     |---------- '\014' -------->| (session start)
 *     |                           |
 *     |<---- "[run_erl v1-0]" ----| (version interval)
 *     |                           |
 *     |--- Esc_"version=1"Esc\ -->| (common version)
 *     |                           |
 */
static int version_handshake(char* buf, int len, int wfd)
{
    unsigned re_high=0, re_low;
    char *end = find_str(buf,len,"]\n");

    if (end && sscanf(buf,"[run_erl v%u-%u",&re_high,&re_low)==2) {
	char wbuf[30];
	int wlen;

	if (re_low > RUN_ERL_HI_VER || re_high < RUN_ERL_LO_VER) {
	    fprintf(stderr,"Incompatible versions: to_erl=v%u-%u run_erl=v%u-%u\n",
		    RUN_ERL_HI_VER, RUN_ERL_LO_VER, re_high, re_low);
	    return -1;
	}
	/* Choose highest common version */
	protocol_ver = re_high < RUN_ERL_HI_VER ? re_high : RUN_ERL_HI_VER;

	wlen = sn_printf(wbuf, sizeof(wbuf), "\033_version=%u\033\\",
			 protocol_ver);
	if (write_all(wfd, wbuf, wlen) < 0) {
	    fprintf(stderr,"Failed to send version handshake\n");
	    return -1;
	}
	end += 2;
	len -= (end-buf);
	memmove(buf,end,len);

    }
    else {  /* we assume old run_erl without version handshake */
	protocol_ver = 0;
    }

    if (re_high != RUN_ERL_HI_VER) {
	fprintf(stderr,"run_erl has different version, "
		"using common protocol level %u\n", protocol_ver);
    }

    return len;
}