Пример #1
0
//          <6
const char * zstring::ucase()
{ 	unsigned int i;for(i=0;i<=mem_data.mem_length;i++)mem_data.mem_string[i]=toupper(mem_data.mem_string[i]);	
return mem_data.mem_string;
}
Пример #2
0
_CRTIMP wchar_t towupper(wchar_t c)
#endif
{
	return (wchar_t)toupper(c & 0xff);
}
Пример #3
0
/*
 * Display a dialog box with a list of options that can be turned on or off
 * The `flag' parameter is used to select between radiolist and checklist.
 */
int
dialog_checklist (const char *title, const char *prompt, int height, int width,
                  int list_height, int item_no, const char * const * items, int flag)

{
    int i, x, y, box_x, box_y;
    int key = 0, button = 0, choice = 0, scroll = 0, max_choice, *status;
    WINDOW *dialog, *list;

    checkflag = flag;

    /* Allocate space for storing item on/off status */
    if ((status = malloc (sizeof (int) * item_no)) == NULL) {
        endwin ();
        fprintf (stderr,
                 "\nCan't allocate memory in dialog_checklist().\n");
        exit (-1);
    }

    /* Initializes status */
    for (i = 0; i < item_no; i++) {
        status[i] = !strcasecmp (items[i * 3 + 2], "on");
        if ((!choice && status[i]) || !strcasecmp (items[i * 3 + 2], "selected"))
            choice = i + 1;
    }
    if (choice)
        choice--;

    max_choice = MIN (list_height, item_no);

    /* center dialog box on screen */
    x = (COLS - width) / 2;
    y = (LINES - height) / 2;

    draw_shadow (stdscr, y, x, height, width);

    dialog = newwin (height, width, y, x);
    keypad (dialog, TRUE);

    draw_box (dialog, 0, 0, height, width, dialog_attr, border_attr);
    wattrset (dialog, border_attr);
    mvwaddch (dialog, height-3, 0, ACS_LTEE);
    for (i = 0; i < width - 2; i++)
        waddch (dialog, ACS_HLINE);
    wattrset (dialog, dialog_attr);
    waddch (dialog, ACS_RTEE);

    if (title != NULL && strlen(title) >= width-2 ) {
        /* truncate long title -- mec */
        char * title2 = malloc(width-2+1);
        memcpy( title2, title, width-2 );
        title2[width-2] = '\0';
        title = title2;
    }

    if (title != NULL) {
        wattrset (dialog, title_attr);
        mvwaddch (dialog, 0, (width - strlen(title))/2 - 1, ' ');
        waddstr (dialog, (char *)title);
        waddch (dialog, ' ');
    }

    wattrset (dialog, dialog_attr);
    print_autowrap (dialog, prompt, width - 2, 1, 3);

    list_width = width - 6;
    box_y = height - list_height - 5;
    box_x = (width - list_width) / 2 - 1;

    /* create new window for the list */
    list = subwin (dialog, list_height, list_width, y+box_y+1, x+box_x+1);

    keypad (list, TRUE);

    /* draw a box around the list items */
    draw_box (dialog, box_y, box_x, list_height + 2, list_width + 2,
              menubox_border_attr, menubox_attr);

    /* Find length of longest item in order to center checklist */
    check_x = 0;
    for (i = 0; i < item_no; i++)
        check_x = MAX (check_x, + strlen (items[i * 3 + 1]) + 4);

    check_x = (list_width - check_x) / 2;
    item_x = check_x + 4;

    if (choice >= list_height) {
        scroll = choice - list_height + 1;
        choice -= scroll;
    }

    /* Print the list */
    for (i = 0; i < max_choice; i++) {
        print_item (list, items[(scroll+i) * 3 + 1],
                    status[i+scroll], i, i == choice);
    }

    print_arrows(dialog, choice, item_no, scroll,
                 box_y, box_x + check_x + 5, list_height);

    print_buttons(dialog, height, width, 0);

    wnoutrefresh (list);
    wnoutrefresh (dialog);
    doupdate ();

    while (key != ESC) {
        key = wgetch (dialog);

        for (i = 0; i < max_choice; i++)
            if (toupper(key) == toupper(items[(scroll+i)*3+1][0]))
                break;


        if ( i < max_choice || key == KEY_UP || key == KEY_DOWN ||
                key == '+' || key == '-' ) {
            if (key == KEY_UP || key == '-') {
                if (!choice) {
                    if (!scroll)
                        continue;
                    /* Scroll list down */
                    if (list_height > 1) {
                        /* De-highlight current first item */
                        print_item (list, items[scroll * 3 + 1],
                                    status[scroll], 0, FALSE);
                        scrollok (list, TRUE);
                        wscrl (list, -1);
                        scrollok (list, FALSE);
                    }
                    scroll--;
                    print_item (list, items[scroll * 3 + 1],
                                status[scroll], 0, TRUE);
                    wnoutrefresh (list);

                    print_arrows(dialog, choice, item_no, scroll,
                                 box_y, box_x + check_x + 5, list_height);

                    wrefresh (dialog);

                    continue;	/* wait for another key press */
                } else
                    i = choice - 1;
            } else if (key == KEY_DOWN || key == '+') {
                if (choice == max_choice - 1) {
                    if (scroll + choice >= item_no - 1)
                        continue;
                    /* Scroll list up */
                    if (list_height > 1) {
                        /* De-highlight current last item before scrolling up */
                        print_item (list, items[(scroll + max_choice - 1) * 3 + 1],
                                    status[scroll + max_choice - 1],
                                    max_choice - 1, FALSE);
                        scrollok (list, TRUE);
                        wscrl (list, 1);
                        scrollok (list, FALSE);
                    }
                    scroll++;
                    print_item (list, items[(scroll + max_choice - 1) * 3 + 1],
                                status[scroll + max_choice - 1],
                                max_choice - 1, TRUE);
                    wnoutrefresh (list);

                    print_arrows(dialog, choice, item_no, scroll,
                                 box_y, box_x + check_x + 5, list_height);

                    wrefresh (dialog);

                    continue;	/* wait for another key press */
                } else
                    i = choice + 1;
            }
            if (i != choice) {
                /* De-highlight current item */
                print_item (list, items[(scroll + choice) * 3 + 1],
                            status[scroll + choice], choice, FALSE);
                /* Highlight new item */
                choice = i;
                print_item (list, items[(scroll + choice) * 3 + 1],
                            status[scroll + choice], choice, TRUE);
                wnoutrefresh (list);
                wrefresh (dialog);
            }
            continue;		/* wait for another key press */
        }
        switch (key) {
        case 'H':
        case 'h':
        case '?':
            fprintf (stderr, "%s", items[(scroll + choice) * 3]);
            delwin (dialog);
            free (status);
            return 1;
        case TAB:
        case KEY_LEFT:
        case KEY_RIGHT:
            button = ((key == KEY_LEFT ? --button : ++button) < 0)
                     ? 1 : (button > 1 ? 0 : button);

            print_buttons(dialog, height, width, button);
            wrefresh (dialog);
            break;
        case 'S':
        case 's':
        case ' ':
        case '\n':
            if (!button) {
                if (flag == FLAG_CHECK) {
                    status[scroll + choice] = !status[scroll + choice];
                    wmove (list, choice, check_x);
                    wattrset (list, check_selected_attr);
                    wprintw (list, "[%c]", status[scroll + choice] ? 'X' : ' ');
                } else {
                    if (!status[scroll + choice]) {
                        for (i = 0; i < item_no; i++)
                            status[i] = 0;
                        status[scroll + choice] = 1;
                        for (i = 0; i < max_choice; i++)
                            print_item (list, items[(scroll + i) * 3 + 1],
                                        status[scroll + i], i, i == choice);
                    }
                }
                wnoutrefresh (list);
                wrefresh (dialog);

                for (i = 0; i < item_no; i++) {
                    if (status[i]) {
                        if (flag == FLAG_CHECK) {
                            fprintf (stderr, "\"%s\" ", items[i * 3]);
                        } else {
                            fprintf (stderr, "%s", items[i * 3]);
                        }

                    }
                }
            } else
                fprintf (stderr, "%s", items[(scroll + choice) * 3]);
            delwin (dialog);
            free (status);
            return button;
        case 'X':
        case 'x':
            key = ESC;
        case ESC:
            break;
        }

        /* Now, update everything... */
        doupdate ();
    }


    delwin (dialog);
    free (status);
    return -1;			/* ESC pressed */
}
static int
makelite(struct distress *dist, char *pm)
{
    struct player *sender;
    struct player *j;
    struct planet *l;
    char    c;
    W_Color lcol;

    sender = &players[dist->sender];

    if (!(*pm)) {
	return (0);
    }
    /* first step is to substitute variables */
    while (*pm) {
	if (*pm == '/') {
	    pm++;

	    if (!pm)
		continue;

	    if (F_beeplite_flags & LITE_COLOR) {
		/* color lite -JR */
		switch (toupper(*(pm + 1))) {
		case 'G':
		    lcol = W_Green;
		    break;
		case 'Y':
		    lcol = W_Yellow;
		    break;
		case 'R':
		    lcol = W_Red;
		    break;
		case 'C':
		    lcol = W_Cyan;
		    break;
		case 'E':
		    lcol = W_Grey;
		    break;
		case 'W':
		default:
		    lcol = W_White;
		    break;
		}
	    } else
		lcol = W_White;

	    switch (c = *(pm++)) {

	    case 'P':		/* push player id into buf */
	    case 'G':		/* push friendly player id into buf */
	    case 'H':		/* push enemy target player id into buf */

	    case 'p':		/* push player id into buf */
	    case 'g':		/* push friendly player id into buf */
	    case 'h':		/* push enemy target player id into buf */

		switch (c) {
		case 'p':
		    j = &players[dist->tclose_j];
		    break;
		case 'g':
		    j = &players[dist->tclose_fr];
		    break;
		case 'h':
		    j = &players[dist->tclose_en];
		    break;
		case 'P':
		    j = &players[dist->close_j];
		    break;
		case 'G':
		    j = &players[dist->close_fr];
		    break;
		default:
		    j = &players[dist->close_en];
		    break;
		}
		liteplayer(j, lcol);
		break;

	    case 'B':		/* highlites planet nearest sender */
	    case 'b':
		l = &planets[dist->close_pl];
		liteplanet(l, lcol);
		break;
	    case 'L':		/* highlites planet nearest pointer */
	    case 'l':
		l = &planets[dist->tclose_pl];
		liteplanet(l, lcol);
		break;
	    case 'U':		/* highlites enemy nearest pointer */
	    case 'u':
		j = &players[dist->tclose_en];
		liteplayer(j, lcol);
		break;
	    case 'c':		/* highlites sender */
	    case 'I':
	    case 'i':
		liteplayer(sender, lcol);
		break;
	    case 'M':		/* highlites me */
	    case 'm':
		liteplayer(me, lcol);
		break;
	    case '0':
		if (F_beeplite_flags & LITE_SOUNDS)
		    W_Beep();
		break;
	    default:
/* try to continue
** bad macro character is skipped entirely,
** the message will be parsed without whatever argument has occurred. - jn
*/
		warning("Bad Macro character in distress!");
		fprintf(stderr, "Unrecognizable special character in "
		                "distress pass 1: %c\n", *(pm - 1));
		break;
	    }
	} else {
	    pm++;
	}

    }


    return (1);
}
Пример #5
0
int VDScriptInterpreter::Token() {
	static char hexdig[]="0123456789ABCDEF";
	char *s,c;

	if (tokhold) {
		int t = tokhold;
		tokhold = 0;
		return t;
	}

	do {
		c=*tokstr++;
	} while(c && isspace((unsigned char)c));

	if (!c) {
		--tokstr;

		return 0;
	}

	// C++ style comment?

	if (c=='/')
		if (tokstr[0]=='/') {
			while(*tokstr) ++tokstr;

			return 0;		// C++ comment
		} else
			return '/';

	// string?

	if (c=='"') {
		const char *s = tokstr;
		char *t;
		long len_adjust=0;

		while((c=*tokstr++) && c!='"') {
			if (c=='\\') {
				c = *tokstr++;
				if (!c) SCRIPT_ERROR(PARSE_ERROR);
				else {
					if (c=='x') {
						if (!isxdigit((unsigned char)tokstr[0]) || !isxdigit((unsigned char)tokstr[1]))
							SCRIPT_ERROR(PARSE_ERROR);
						tokstr+=2;
						len_adjust += 2;
					}
					++len_adjust;
				}
			}
		}

		tokslit = strheap.Allocate(tokstr - s - 1 - len_adjust);
		t = *tokslit;
		while(s<tokstr-1) {
			int val;

			c = *s++;

			if (c=='\\')
				switch(c=*s++) {
				case 'a': *t++='\a'; break;
				case 'b': *t++='\b'; break;
				case 'f': *t++='\f'; break;
				case 'n': *t++='\n'; break;
				case 'r': *t++='\r'; break;
				case 't': *t++='\t'; break;
				case 'v': *t++='\v'; break;
				case 'x':
					val = strchr(hexdig,toupper(s[0]))-hexdig;
					val = (val<<4) | (strchr(hexdig,toupper(s[1]))-hexdig);
					*t++ = val;
					s += 2;
					break;
				default:
					*t++ = c;
				}
			else
				*t++ = c;
		}
		*t=0;

		if (!c) --tokstr;

		return TOK_STRING;
	}

	// unescaped string?
	if ((c=='u' || c=='U') && *tokstr == '"') {
		const char *s = ++tokstr;

		while((c=*tokstr++) && c != '"')
			;

		if (!c) {
			--tokstr;
			SCRIPT_ERROR(PARSE_ERROR);
		}

		size_t len = tokstr - s - 1;

		const VDStringA strA(VDTextWToU8(VDTextAToW(s, len)));

		len = strA.size();

		tokslit = strheap.Allocate(len);
		memcpy(*tokslit, strA.data(), len);
		(*tokslit)[len] = 0;

		return TOK_STRING;
	}

	// look for variable/keyword

	if (isIdentFirstChar(c)) {
		s = szIdent;

		*s++ = c;
		while(isIdentNextChar(c = *tokstr++)) {
			if (s>=szIdent + MAX_IDENT_CHARS)
				SCRIPT_ERROR(IDENT_TOO_LONG);

			*s++ = c;
		}

		--tokstr;
		*s=0;

		if (!strcmp(szIdent, "declare"))
			return TOK_DECLARE;
		else if (!strcmp(szIdent, "true"))
			return TOK_TRUE;
		else if (!strcmp(szIdent, "false"))
			return TOK_FALSE;
		else if (!strcmp(szIdent, "int"))
			return TOK_INT;
		else if (!strcmp(szIdent, "long"))
			return TOK_LONG;
		else if (!strcmp(szIdent, "double"))
			return TOK_DOUBLE;

		return TOK_IDENT;
	}

	// test for number: decimal (123), octal (0123), or hexadecimal (0x123)

	if (isdigit((unsigned char)c)) {
		sint64 v = 0;

		if (c=='0' && tokstr[0] == 'x') {

			// hex (base 16)
			++tokstr;

			while(isxdigit((unsigned char)(c = *tokstr++))) {
				v = v*16 + (strchr(hexdig, toupper(c))-hexdig);
			}

		} else if (c=='0' && isdigit((unsigned char)tokstr[0])) {
			// octal (base 8)
			while((c=*tokstr++)>='0' && c<='7')
				v = v*8 + (c-'0');
		} else {
			// check for float
			const char *s = tokstr;
			while(*s) {
				if (*s == '.' || *s == 'e' || *s == 'E') {
					// It's a float -- parse and return.

					--tokstr;
					tokdval = strtod(tokstr, (char **)&tokstr);
					return TOK_DBLVAL;
				}

				if (!isdigit((unsigned char)*s))
					break;
				++s;
			}

			// decimal
			v = (c-'0');
			while(isdigit((unsigned char)(c=*tokstr++)))
				v = v*10 + (c-'0');
		}
		--tokstr;

		if (v > 0x7FFFFFFF) {
			toklval = v;
			return TOK_LONGVAL;
		} else {
			tokival = (int)v;
			return TOK_INTVAL;
		}
	}

	// test for symbols:
	//
	//	charset:	+-*/<>=!&|^[]~;%(),
	//	solitary:	+-*/<>=!&|^[]~;%(),
	//	extra:		!= <= >= == && ||
	//
	//	the '/' is handled above for comment handling

	if (c=='!')
		if (tokstr[0] == '=') { ++tokstr; return TOK_NOTEQ;  } else return '!';

	if (c=='<')
		if (tokstr[0] == '=') { ++tokstr; return TOK_LESSEQ; } else return '<';

	if (c=='>')
		if (tokstr[0] == '=') { ++tokstr; return TOK_GRTREQ; } else return '>';

	if (c=='=')
		if (tokstr[0] == '=') { ++tokstr; return TOK_EQUALS; } else return '=';

	if (c=='&')
		if (tokstr[0] == '&') { ++tokstr; return TOK_AND;    } else return '&';

	if (c=='|')
		if (tokstr[0] == '|') { ++tokstr; return TOK_OR;     } else return '|';

	if (strchr("+-*^[]~;%(),.",c))
		return c;

	SCRIPT_ERROR(PARSE_ERROR);
}
Пример #6
0
void
AsUppercaseTokens (
    char                    *Buffer,
    char                    *PrefixString)
{
    char                    *SubBuffer;
    char                    *TokenEnd;
    char                    *SubString;
    int                     i;
    UINT32                  Length;


    SubBuffer = Buffer;

    while (SubBuffer)
    {
        SubBuffer = strstr (SubBuffer, PrefixString);
        if (SubBuffer)
        {
            TokenEnd = SubBuffer;
            while ((isalnum ((int) *TokenEnd)) || (*TokenEnd == '_'))
            {
                TokenEnd++;
            }

            for (i = 0; i < (TokenEnd - SubBuffer); i++)
            {
                if ((islower ((int) SubBuffer[i])) &&
                    (isupper ((int) SubBuffer[i+1])))
                {

                    SubString = TokenEnd;
                    Length = 0;

                    while (*SubString != '\n')
                    {
                        if ((SubString[0] == ' ') &&
                            (SubString[1] == ' '))
                        {
                            Length = SubString - &SubBuffer[i] - 2;
                            break;
                        }

                        SubString++;
                    }

                    if (!Length)
                    {
                        Length = strlen (&SubBuffer[i+1]);
                    }

                    memmove (&SubBuffer[i+2], &SubBuffer[i+1], (Length+1));
                    SubBuffer[i+1] = '_';
                    i +=2;
                    TokenEnd++;
                }
            }

            for (i = 0; i < (TokenEnd - SubBuffer); i++)
            {
                SubBuffer[i] = (char) toupper ((int) SubBuffer[i]);
            }

            SubBuffer = TokenEnd;
        }
    }
}
Пример #7
0
char * strToUpper(char *str)
{
     while(*str=toupper(*str))
        str++;
}
Пример #8
0
void input_poll(void)
{
SDL_Event evt;
int ino, key;

#ifdef __native_client__
	{
		/* Process all waiting events without blocking */
		PSEvent* event = NULL;
		while ((event = PSEventTryAcquire()) != NULL) {
			ProcessEvent(event);
			PSEventRelease(event);
		}
	}

#endif
	
	while(SDL_PollEvent(&evt))
	{
		switch(evt.type)
		{
			case SDL_KEYDOWN:
			case SDL_KEYUP:
			{
				key = evt.key.keysym.sym;
				
				#ifndef __SDLSHIM__
				static uint8_t shiftstates = 0;
				extern bool freezeframe;
				
				if (console.IsVisible() && !IsNonConsoleKey(key))
				{
					if (key == SDLK_LSHIFT)
					{
						if (evt.type == SDL_KEYDOWN)
							shiftstates |= LEFTMASK;
						else
							shiftstates &= ~LEFTMASK;
					}
					else if (key == SDLK_RSHIFT)
					{
						if (evt.type == SDL_KEYDOWN)
							shiftstates |= RIGHTMASK;
						else
							shiftstates &= ~RIGHTMASK;
					}
					else
					{
						int ch = key;
						if (shiftstates != 0)
						{
							ch = toupper(ch);
							if (ch == '.') ch = '>';
							if (ch == '-') ch = '_';
							if (ch == '/') ch = '?';
							if (ch == '1') ch = '!';
						}
						
						if (evt.type == SDL_KEYDOWN)
							console.HandleKey(ch);
						else
							console.HandleKeyRelease(ch);
					}
				}
				else
				#endif	// __SDLSHIM__
				{
					ino = mappings[key];
					if (ino != 0xff)
						inputs[ino] = (evt.type == SDL_KEYDOWN);
					
					if (evt.type == SDL_KEYDOWN)
					{
						if (Replay::IsPlaying() && ino <= LASTCONTROLKEY)
						{
							stat("user interrupt - stopping playback of replay");
							Replay::end_playback();
							memset(inputs, 0, sizeof(inputs));
							inputs[ino] = true;
						}
						
						#ifndef __SDLSHIM__
						if (key == '`')		// bring up console
						{
							if (!freezeframe)
							{
								sound(SND_SWITCH_WEAPON);
								console.SetVisible(true);
							}
						}
						else
						#endif
						{
							last_sdl_key = key;
						}
					}
				}
			}
			break;
			
			case SDL_QUIT:
			{
				inputs[ESCKEY] = true;
				game.running = false;
			}
			break;
		}
	}
}
Пример #9
0
PTABDEF OEMDEF::GetXdef(PGLOBAL g)
  {
  typedef PTABDEF (__stdcall *XGETDEF) (PGLOBAL, void *);
  char    c, getname[40] = "Get";
  PTABDEF xdefp;
  XGETDEF getdef = NULL;
  PCATLG  cat = Cat;

#if defined(WIN32)
  // Is the DLL already loaded?
  if (!Hdll && !(Hdll = GetModuleHandle(Module)))
    // No, load the Dll implementing the function
    if (!(Hdll = LoadLibrary(Module))) {
      char  buf[256];
      DWORD rc = GetLastError();

      sprintf(g->Message, MSG(DLL_LOAD_ERROR), rc, Module);
      FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
                    FORMAT_MESSAGE_IGNORE_INSERTS, NULL, rc, 0,
                    (LPTSTR)buf, sizeof(buf), NULL);
      strcat(strcat(g->Message, ": "), buf);
      return NULL;
      } // endif hDll

  // The exported name is always in uppercase
  for (int i = 0; ; i++) {
    c = Subtype[i];
    getname[i + 3] = toupper(c);
    if (!c) break;
    } // endfor i

  // Get the function returning an instance of the external DEF class
  if (!(getdef = (XGETDEF)GetProcAddress((HINSTANCE)Hdll, getname))) {
    sprintf(g->Message, MSG(PROCADD_ERROR), GetLastError(), getname);
    FreeLibrary((HMODULE)Hdll);
    return NULL;
    } // endif getdef
#else   // !WIN32
  const char *error = NULL;
  // Is the library already loaded?
//  if (!Hdll && !(Hdll = ???))
  // Load the desired shared library
  if (!(Hdll = dlopen(Module, RTLD_LAZY))) {
    error = dlerror();
    sprintf(g->Message, MSG(SHARED_LIB_ERR), Module, SVP(error));
    return NULL;
    } // endif Hdll

  // The exported name is always in uppercase
  for (int i = 0; ; i++) {
    c = Subtype[i];
    getname[i + 3] = toupper(c);
    if (!c) break;
    } // endfor i

  // Get the function returning an instance of the external DEF class
  if (!(getdef = (XGETDEF)dlsym(Hdll, getname))) {
    error = dlerror();
    sprintf(g->Message, MSG(GET_FUNC_ERR), getname, SVP(error));
    dlclose(Hdll);
    return NULL;
    } // endif getdef
#endif  // !WIN32

  // Just in case the external Get function does not set error messages
  sprintf(g->Message, MSG(DEF_ALLOC_ERROR), Subtype);

  // Get the table definition block
  if (!(xdefp = getdef(g, NULL)))
    return NULL;

  // Have the external class do its complete definition
  if (!cat->Cbuf) {
    // Suballocate a temporary buffer for the entire column section
    cat->Cblen = cat->GetSizeCatInfo("Colsize", "8K");
    cat->Cbuf = (char*)PlugSubAlloc(g, NULL, cat->Cblen);
    } // endif Cbuf

  // Here "OEM" should be replace by a more useful value
  if (xdefp->Define(g, cat, Name, "OEM"))
    return NULL;

  // Ok, return external block
  return xdefp;
  } // end of GetXdef
Пример #10
0
/**********************************************************************
 *  Function  repeats_menu()
 *                                                                    
 *  Parameter:                                                       
 *   
 *                                                              
 *  This function prompts user to choose an algorithm to compute
 *  repeats and similar things.
 *  The utilities menu is also available from this menu.
 *                                                                   
 **********************************************************************/
void repeats_menu()
{
  static int smax_percent = 0;
  static int smax_minlen = 0;
  int status, num_lines;
  char ch;
  STRING *text;

  while (1) {
    num_lines = 20;

    printf("\n**   Repeats Menu    **\n\n");
    printf("1)  Find primitive tandem repeats (Crochemore's algorithm)\n");
    printf("2)  Find supermaximals and near supermaximals of a string\n");
    printf("3)  Find nonoverlapping maximals of a string"
           " (Crochemore variant)\n");
    printf("4)  Find nonoverlapping maximals of a string"
           " (big path algorithm)\n");
    printf("5)  Find tandem repeats/tandem arrays using the suffix tree\n");
    printf("6)  Find vocabulary of tandem repeats (and more) using\n");
    printf("     a) Ziv-Lempel decomposition\n");
    printf("     b) nonoverlapping blocks decomposition (as in the book)\n");
    printf("7)  Find occurrences in linear time (without suffix tree) using\n");
    printf("     a) Ziv-Lempel decomposition\n");
    printf("     b) nonoverlapping blocks decomposition (as in the book)\n");
    printf("*)  String Utilites\n");
    printf("0)  Exit\n");
    printf("\nEnter Selection: ");
 
    while ((choice = my_getline(stdin, &ch_len)) == NULL) ;

    switch (choice[0]) {
    case '0':
      return;

    case '1':
      if (!(text = get_string("string")))
        continue;

      mstart(stdin, fpout, OK, OK, 5, NULL);
      mprintf("\nThe string:\n");
      terse_print_string(text);
      mputc('\n');

      status = map_sequences(text, NULL, NULL, 0);
      if (status != -1) {
        strmat_repeats_primitives(text, stats_flag);
        unmap_sequences(text, NULL, NULL, 0);
      }
      mend(num_lines);
      putchar('\n');
      break;

    case '2':
      if (!(text = get_string("text")))
        continue;

      smax_percent = get_bounded("Percent Supermaximal", 0, 100, smax_percent);
      printf("\n");
      if (smax_percent == -1)
        continue;

      smax_minlen = get_bounded("Supermax. Minimum Length", 0, text->length,
                                smax_minlen);
      printf("\n");
      if (smax_minlen == -1)
        continue;
                                         
      mstart(stdin, fpout, OK, OK, 5, NULL);
      mprintf("\nThe text:\n");
      terse_print_string(text);
      mputc('\n');

      status = map_sequences(text, NULL, NULL, 0);
      if (status != -1) {
        mprintf("Finding the supermaximals...\n\n");
        strmat_repeats_supermax(text, smax_percent, smax_minlen);
        unmap_sequences(text, NULL, NULL, 0);
      }
      mend(num_lines);
      putchar('\n');
      break;

    case '3':
      if (!(text = get_string("string")))
        continue;

      mstart(stdin, fpout, OK, OK, 5, NULL);
      mprintf("\nThe string:\n");
      terse_print_string(text);
      mputc('\n');

      status = map_sequences(text, NULL, NULL, 0);
      if (status != -1) {
        strmat_repeats_nonoverlapping(text, stats_flag);
        unmap_sequences(text, NULL, NULL, 0);
      }
      mend(num_lines);
      putchar('\n');
      break;

    case '4':
      if (!(text = get_string("string")))
        continue;

      mstart(stdin, fpout, OK, OK, 5, NULL);
      mprintf("\nThe string:\n");
      terse_print_string(text);
      mputc('\n');

      status = map_sequences(text, NULL, NULL, 0);
      if (status != -1) {
        strmat_repeats_bigpath(text, stree_build_policy, stree_build_threshold,
                               stats_flag);
        unmap_sequences(text, NULL, NULL, 0);
      }
      mend(num_lines);
      putchar('\n');
      break;

    case '5':
      if (!(text = get_string("string")))
        continue;

      mstart(stdin, fpout, OK, OK, 5, NULL);
      mprintf("\nThe string:\n");
      terse_print_string(text);
      mputc('\n');

      status = map_sequences(text, NULL, NULL, 0);
      if (status != -1) {
        strmat_repeats_tandem(text, stree_build_policy, stree_build_threshold,
                              stats_flag);
        unmap_sequences(text, NULL, NULL, 0);
      }
      mend(num_lines);
      putchar('\n');
      break;

    case '6':
      ch = toupper(choice[1]);
      if (ch!='A' && ch!='B') {
        printf("\nYou must specify which type of decomposition to use"
               "(as in '6a' or '6b').\n");
        continue;
      }

      if (!(text = get_string("string")))
        continue;

      mstart(stdin, fpout, OK, OK, 5, NULL);
      mprintf("\nThe string:\n");
      terse_print_string(text);
      mputc('\n');

      status = map_sequences(text, NULL, NULL, 0);
      if (status != -1) {
        strmat_repeats_vocabulary(text, stree_build_policy,
                                  stree_build_threshold, stats_flag,ch);
        unmap_sequences(text, NULL, NULL, 0);
      }
      mend(num_lines);
      putchar('\n');
      break;

    case '7':
      ch = toupper(choice[1]);
      if (ch!='A' && ch!='B') {
        printf("\nYou must specify which type of decomposition to use"
               "(as in '7a' or '7b').\n");
        continue;
      }

      if (!(text = get_string("string")))
        continue;

      mstart(stdin, fpout, OK, OK, 5, NULL);
      mprintf("\nThe string:\n");
      terse_print_string(text);
      mputc('\n');

      status = map_sequences(text, NULL, NULL, 0);
      if (status != -1) {
        strmat_repeats_linear_occs(text, stree_build_policy,
                                   stree_build_threshold, stats_flag,ch);
        unmap_sequences(text, NULL, NULL, 0);
      }
      mend(num_lines);
      putchar('\n');
      break;

    case '*':
      util_menu();
      break;
   
    default:
      printf("\nThat is not a choice.\n");
    }
  }
}
Пример #11
0
int main() {

  int listenSocket[2], connectSocket, status, i;
  unsigned short int msgLength;
  struct addrinfo hints, *servinfo, *p;
  struct sockaddr_storage clientAddress;
  socklen_t clientAddressLength = sizeof clientAddress;
  void *addr;
  char msg[MSG_ARRAY_SIZE], listenPort[PORT_ARRAY_SIZE], ipstr[INET6_ADDRSTRLEN];
  int optval = 1; // socket double et IPV6_V6ONLY à 1
  bool sockSuccess = false;
  struct timeval timeVal;
  fd_set readSet[2];

  listenSocket[v4] = listenSocket[v6] = -1;

  memset(listenPort, 0, sizeof listenPort);  // Mise à zéro du tampon
  puts("Entrez le numéro de port utilisé en écoute (entre 1500 et 65000) : ");
  scanf("%"xstr(MAX_PORT)"s", listenPort);

  memset(&hints, 0, sizeof hints);
  hints.ai_family = AF_UNSPEC; // IPv6 et IPv4
  hints.ai_socktype = SOCK_STREAM;
  hints.ai_flags = AI_PASSIVE; // use my IP

  if ((status = getaddrinfo(NULL, listenPort, &hints, &servinfo)) != 0) {
    fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(status));
    return 1;
  }

  // Scrutation des résultats et création de socket
  // Sortie après création d'une «prise» IPv4 et d'une «prise» IPv6
  p = servinfo;
  while ((p != NULL) && !sockSuccess) {

    // Identification de l'adresse courante
    if (p->ai_family == AF_INET) { // IPv4
      struct sockaddr_in *ipv4 = (struct sockaddr_in *)p->ai_addr;
      addr = &(ipv4->sin_addr);
      // conversion de l'adresse IP en une chaîne de caractères
      inet_ntop(p->ai_family, addr, ipstr, sizeof ipstr);
      printf(" IPv4: %s\n", ipstr);

      if ((listenSocket[v4] = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
        perror("socket:"); // Echec ouverture socket
      }

      else if (bind(listenSocket[v4], p->ai_addr, p->ai_addrlen) == -1) {
        close(listenSocket[v4]);
        perror("bind:");
	listenSocket[v4] = -1; // Echec socket en écoute
      }
    }
    else { // IPv6
      struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)p->ai_addr;
      addr = &(ipv6->sin6_addr);
      // conversion de l'adresse IP en une chaîne de caractères
      inet_ntop(p->ai_family, addr, ipstr, sizeof ipstr);
      printf(" IPv6: %s\n", ipstr);

      if ((listenSocket[v6] = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
        perror("socket:"); // Echec ouverture socket
      }

      else if (setsockopt(listenSocket[v6], IPPROTO_IPV6, IPV6_V6ONLY, &optval, sizeof optval) == -1) {
        perror("setsockopt:");
	listenSocket[v6] = -1; // Echec option bindv6only=1
      }

      else if (bind(listenSocket[v6], p->ai_addr, p->ai_addrlen) == -1) {
        close(listenSocket[v6]);
        perror("bind:");
	listenSocket[v6] = -1; // Echec socket en écoute
      }
    }

    if ((listenSocket[v4] != -1) && (listenSocket[v6] != -1)) // deux prises ouvertes
      sockSuccess = true;
    else
      p = p->ai_next; // Enregistrement d'adresse suivant
  }

  if (p == NULL) {
    fputs("Création de socket impossible\n", stderr);
    exit(EXIT_FAILURE);
  }

  // Libération de la mémoire occupée par les enregistrements
  freeaddrinfo(servinfo);

  printf("Attente de requête sur le port %s\n", listenPort);

  // Utilisation de select en mode scrutation
  timeVal.tv_sec = 0;
  timeVal.tv_usec = 0;

  // Attente des requêtes des clients.
  // Appel non bloquant et passage en mode passif
  // Demandes d'ouverture de connexion traitées par accept
  if (listen(listenSocket[v4], BACKLOG) == -1) {
    perror("listen");
    exit(EXIT_FAILURE);
  }

  if (listen(listenSocket[v6], BACKLOG) == -1) {
    perror("listen:");
    exit(EXIT_FAILURE);
  }

  while (1) {

    FD_ZERO(&readSet[v4]);
    FD_SET(listenSocket[v4], &readSet[v4]);
    FD_ZERO(&readSet[v6]);
    FD_SET(listenSocket[v6], &readSet[v6]);

    if (select(listenSocket[v4]+1, &readSet[v4], NULL, NULL, &timeVal) == -1) { // IPv4
      perror("select:");
      exit(EXIT_FAILURE);
    }

    if (select(listenSocket[v6]+1, &readSet[v6], NULL, NULL, &timeVal) == -1) { // IPv6
      perror("select:");
      exit(EXIT_FAILURE);
    }

    if (FD_ISSET(listenSocket[v4], &readSet[v4])) { // IPv4
      // Appel bloquant en attente d'une nouvelle connexion
      // connectSocket est la nouvelle prise utilisée pour la connexion active
      if ((connectSocket = accept(listenSocket[v4], (struct sockaddr *) &clientAddress,
				  &clientAddressLength)) == -1) {
        perror("accept:");
        close(listenSocket[v4]);
        exit(EXIT_FAILURE);
      }

      // Affichage de l'adresse IP du client.
      inet_ntop(clientAddress.ss_family, get_in_addr((struct sockaddr *)&clientAddress),
                ipstr, sizeof ipstr);
      printf(">>  connecté à [%s]:", ipstr);

      // Affichage du numéro de port du client.
      printf("%hu\n", ntohs(get_in_port((struct sockaddr *)&clientAddress)));

      // Mise à zéro du tampon de façon à connaître le délimiteur
      // de fin de chaîne.
      memset(msg, 0, sizeof msg);
      while (recv(connectSocket, msg, sizeof msg, 0) > 0) 
        if ((msgLength = strlen(msg)) > 0) {
          printf("  --  %s\n", msg);
          // Conversion de cette ligne en majuscules.
          for (i = 0; i < msgLength; i++)
            msg[i] = toupper(msg[i]);

          // Renvoi de la ligne convertie au client.
          if (send(connectSocket, msg, msgLength, 0) == -1) {
            perror("send:");
            close(listenSocket[v4]);
            exit(EXIT_FAILURE);
          }

          memset(msg, 0, sizeof msg);  // Mise à zéro du tampon
        }
    }

    if (FD_ISSET(listenSocket[v6], &readSet[v6])) { // IPv6
      // Appel bloquant en attente d'une nouvelle connexion
      // connectSocket est la nouvelle prise utilisée pour la connexion active
      if ((connectSocket = accept(listenSocket[v6], (struct sockaddr *) &clientAddress,
				  &clientAddressLength)) == -1) {
        perror("accept:");
        close(listenSocket[v6]);
        exit(EXIT_FAILURE);
      }

      // Affichage de l'adresse IP du client.
      inet_ntop(clientAddress.ss_family, get_in_addr((struct sockaddr *)&clientAddress),
                ipstr, sizeof ipstr);
      printf(">>  connecté à [%s]:", ipstr);

      // Affichage du numéro de port du client.
      printf("%hu\n", ntohs(get_in_port((struct sockaddr *)&clientAddress)));

      // Mise à zéro du tampon de façon à connaître le délimiteur
      // de fin de chaîne.
      memset(msg, 0, sizeof msg);
      while (recv(connectSocket, msg, sizeof msg, 0) > 0) 
        if ((msgLength = strlen(msg)) > 0) {
          printf("  --  %s\n", msg);
          // Conversion de cette ligne en majuscules.
          for (i = 0; i < msgLength; i++)
            msg[i] = toupper(msg[i]);

          // Renvoi de la ligne convertie au client.
          if (send(connectSocket, msg, msgLength, 0) == -1) {
            perror("send:");
            close(listenSocket[v6]);
            exit(EXIT_FAILURE);
          }

          memset(msg, 0, sizeof msg);  // Mise à zéro du tampon
        }
    }

  }

  // jamais atteint
  return 0;
}
Пример #12
0
/**********************************************************************
 *  Function  suf_tree_menu()
 *                                                                    
 *  Parameter:                                                       
 *   
 *                                                              
 *  This function prompts user to choose an algorithm to create 
 *  a suffix tree and use it.  
 *  The utilities menu is also available from this menu.
 *                                                                   
 **********************************************************************/
void suf_tree_menu()
{
  int i, status, num_lines, num_strings;
  char ch;
  STRING *pattern, **strings, *text;

  while (1) {
    num_lines = 18;

    printf("\n**   Suffix Tree Menu    **\n\n");
    printf("1)  Build a suffix tree using Ukkonen's algorithm\n");
    printf("2)  Build a suffix tree using Weiner's algorithm\n");
    printf("3)  Exact matching using a suffix tree for the text\n");
    printf("4)  Walk around a suffix tree\n");
    printf("5)  Compute the LCA values for a suffix tree\n");
    printf("     a) using the naive LCA algorithm\n");
    printf("     b) using the constant time LCA algorithm\n");
    printf("6)  Compute Lempel-Ziv decomposition\n");
    printf("     a) original version (f-factorization)\n");
    printf("     b) nonoverlapping blocks (as in the book)\n");
    printf("8)  Set suffix tree build policy (current: ");
    switch(stree_build_policy)  {
    case LINKED_LIST:      printf("linked list)\n");  break;
    case SORTED_LIST:      printf("sorted list)\n");  break;
    case LIST_THEN_ARRAY:  printf("list then array, threshold %d)\n",
                                  stree_build_threshold);  break;
    case COMPLETE_ARRAY:   printf("complete array)\n");  break;
    }
    printf("9)  Suffix tree print toggle (current: %s)\n",
           (stree_print_flag == ON ? "on" : "off"));
    printf("*)  String Utilites\n");
    printf("0)  Exit\n");
    printf("\nEnter Selection: ");
 
    while ((choice = my_getline(stdin, &ch_len)) == NULL) ;

    switch (choice[0]) {
    case '0':
      return;

    case '1':
      strings = get_string_ary("list of sequences", &num_strings);
      if (strings == NULL)
        continue;

      mstart(stdin, fpout, OK, OK, 5, NULL);
      mprintf("\nThe sequences:\n");
      for (i=0; i < num_strings; i++) {
        mprintf("%2d)", i + 1);
        terse_print_string(strings[i]);
      }
      mputc('\n');

      status = map_sequences(NULL, NULL, strings, num_strings);
      if (status != -1) {
        mprintf("Executing Ukkonen's Algorithm...\n\n");
        strmat_ukkonen_build(strings, num_strings, stree_build_policy,
                             stree_build_threshold, stats_flag,
                             stree_print_flag);
        unmap_sequences(NULL, NULL, strings, num_strings);
      }
      mend(num_lines);
      putchar('\n');

      free(strings);
      break;

    case '2':
      strings = get_string_ary("list of sequences", &num_strings);
      if (strings == NULL)
        continue;

      mstart(stdin, fpout, OK, OK, 5, NULL);
      mprintf("\nThe sequences:\n");
      for (i=0; i < num_strings; i++) {
        mprintf("%2d)", i + 1);
        terse_print_string(strings[i]);
      }
      mputc('\n');

      status = map_sequences(NULL, NULL, strings, num_strings);
      if (status != -1) {
        mprintf("Executing Weiner's Algorithm...\n\n");
        strmat_weiner_build(strings, num_strings, stree_build_policy,
                            stree_build_threshold, stats_flag,
                            stree_print_flag);
        unmap_sequences(NULL, NULL, strings, num_strings);
      }
      mend(num_lines);
      putchar('\n');

      free(strings);
      break;

    case '3':
      if (!(pattern = get_string("pattern")) ||
          !(strings = get_string_ary("list of sequences", &num_strings)))
        continue;

      mstart(stdin, fpout, OK, OK, 5, NULL);
      mprintf("\nThe pattern:\n");
      terse_print_string(pattern);
      mprintf("\nThe texts:\n");
      for (i=0; i < num_strings; i++) {
        mprintf("%2d)", i + 1);
        terse_print_string(strings[i]);
      }
      mputc('\n');

      status = map_sequences(NULL, pattern, strings, num_strings);
      if (status != -1) {
        mprintf("Executing exact matching with a suffix tree...\n\n");
        strmat_stree_match(pattern, strings, num_strings, stree_build_policy,
                           stree_build_threshold, stats_flag);
        unmap_sequences(NULL, pattern, strings, num_strings);
      }
      mend(num_lines);
      putchar('\n');

      free(strings);
      break;
        
    case '4':
      strings = get_string_ary("list of sequences", &num_strings);
      if (strings == NULL)
        continue;

      status = map_sequences(NULL, NULL, strings, num_strings);
      if (status != -1) {
        strmat_stree_walkaround(strings, num_strings, stree_build_policy,
                                stree_build_threshold);
        unmap_sequences(NULL, NULL, strings, num_strings);
      }
      putchar('\n');

      free(strings);
      break;

    case '5':
      ch = toupper(choice[1]);
      if (ch != 'A' && ch != 'B') {
        printf("\nYou must specify which type of LCA algorithm to use "
               "(as in '3a' or '3b').\n");
        continue;
      }

      strings = get_string_ary("list of sequences", &num_strings);
      if (strings == NULL)
        continue;

      status = map_sequences(NULL, NULL, strings, num_strings);
      if (status != -1) {
        if (ch == 'A')
          strmat_stree_naive_lca(strings, num_strings, stree_build_policy,
                                 stree_build_threshold, stats_flag);
        else
          strmat_stree_lca(strings, num_strings, stree_build_policy,
                           stree_build_threshold, stats_flag);
        unmap_sequences(NULL, NULL, strings, num_strings);
      }
      putchar('\n');

      free(strings);
      break;

    case '6':
      ch = toupper(choice[1]);
      if (ch!='A' && ch!='B') {
        printf("\nYou must specify which type of decomposition to compute "
               "(as in '6a' or '6b').\n");
        continue;
      }

      if (!(text = get_string("string")))
        continue;

      mstart(stdin, fpout, OK, OK, 0, NULL);
      mprintf("\nThe string:\n");
      terse_print_string(text);
      mputc('\n');

      status = map_sequences(text, NULL, NULL, 0);
      if(status != -1) {
        strmat_stree_lempel_ziv(text, stree_build_policy,
                                stree_build_threshold, stats_flag,ch);
        unmap_sequences(text, NULL, NULL, 0);
      }
      mend(num_lines);
      putchar('\n');
      break;

    case '8':
      choice = "0";
      while (choice[0] != '1' && choice[0] != '2' &&
             choice[0] != '3' && choice[0] != '4') {
        printf("\n**  Suffix Tree Build Policies **\n");
        printf("\n(1 - linked list, 2 - sorted list, 3 - linked list/array,"
               " 4 - complete array)\n");
        printf("Enter Build Policy [%d]: ",
               (stree_build_policy == LINKED_LIST ? 1
                  : (stree_build_policy == SORTED_LIST ? 2
                       : (stree_build_policy == LIST_THEN_ARRAY ? 3 : 4))));

        if ((choice = my_getline(stdin, &ch_len)) == NULL || choice[0] == '\0')
          break;
      
        switch (choice[0]) {
        case '1':
          stree_build_policy = LINKED_LIST;
          break;

        case '2':
          stree_build_policy = SORTED_LIST;
          break;
        case '3':
          stree_build_policy = LIST_THEN_ARRAY;
          break;

        case '4':
          stree_build_policy = COMPLETE_ARRAY;
          break;

        default:
          printf("\nThat is not a choice.\n");
        }
      }
      if (stree_build_policy == LIST_THEN_ARRAY) {
        printf("\nEnter Build Threshold [%d]: ", stree_build_threshold);
        if ((choice = my_getline(stdin, &ch_len)) != NULL)
          sscanf(choice, "%d", &stree_build_threshold);
      }
      putchar('\n');
      break;

    case '9':
      if (stree_print_flag == ON)
        stree_print_flag = OFF;
      else
        stree_print_flag = ON;
      break;

    case '*':
      util_menu();
      break;
   
    default:
      printf("\nThat is not a choice.\n");
    }
  }
}
Пример #13
0
/**********************************************************************
 *  Function  z_alg_menu();
 *                                                                    
 *  Parameter:                                                       
 *   
 *                                                              
 *  This function prompts user to create and utilize the Z values 
 *  for a string.  The utilities menu is also available from this menu.
 *                                                                   
 **********************************************************************/
void z_alg_menu()
{
  int status, num_lines;
  char ch;
  STRING *text, *pattern;

  while (1) {
    num_lines = 12;
    printf("\n**   Z-value Algorithm Menu    **\n\n");
    printf("1)  Build Z values for a sequence\n");
    printf("2)  Exact matching using Z values\n");
    printf("3)  Knuth-Morris-Pratt  (Z-values preprocessing)\n");
    printf("     a) using sp values\n");
    printf("     b) using sp' values\n");
    printf("*)  String Utilites\n");
    printf("0)  Exit\n");
    printf("\nEnter Selection: ");
  
    while ((choice = my_getline(stdin, &ch_len)) == NULL) ;
    switch (choice[0]) {
    case '0':
      return;

    case '1':
      if (!(text = get_string("text")))
        continue;

      mstart(stdin, fpout, OK, OK, 5, NULL);
      mputs("The string:\n");
      terse_print_string(text);

      status = map_sequences(text, NULL, NULL, 0);
      if (status != -1) {
        mputs("Building Z values...\n\n");
        strmat_z_build(text, stats_flag);
        unmap_sequences(text, NULL, NULL, 0);
      }
      mend(num_lines);
      putchar('\n');
      break;

    case '2':
      if (!(pattern = get_string("pattern")) || !(text = get_string("text")))
        continue;

      mstart(stdin, fpout, OK, OK, 5, NULL);
      mputs("\nThe pattern:\n");
      terse_print_string(pattern);
      mputs("\nThe text:\n");
      terse_print_string(text);
      mputc('\n');

      status = map_sequences(text, pattern, NULL, 0);
      if (status != -1) {
        mputs("Executing exact matching with Z values algorithm...\n\n");
        strmat_z_match(pattern, text, stats_flag);
        unmap_sequences(text, pattern, NULL, 0);
      }
      mend(num_lines);
      putchar('\n');
      break;

    case '3':
      ch = choice[1];
      if (toupper(ch) != 'A' && toupper(ch) != 'B') {
        printf("\nYou must specify the KMP variation (as in '3a' or '3b').\n");
        continue;
      }

      if (!(pattern = get_string("pattern")) || !(text = get_string("text")))
        continue;

      mstart(stdin, fpout, OK, OK, 5, NULL);
      mprintf("\nThe pattern:\n");
      terse_print_string(pattern);
      mprintf("\nThe text:\n");
      terse_print_string(text);
      mputc('\n');
        
      status = map_sequences(text, pattern, NULL, 0);
      if (status != -1) {
        if (toupper(ch) == 'A') {
          mprintf ("Executing KMP with sp values...\n\n");
          strmat_kmp_sp_z_match(pattern, text, stats_flag);
        }
        else {
          mprintf ("Executing KMP with sp' values...\n\n");
          strmat_kmp_spprime_z_match(pattern, text, stats_flag);
        }
        unmap_sequences(text, pattern, NULL, 0);
      }
      mend(num_lines);
      putchar('\n');
      break;

    case '*':
      util_menu();
      break;

    default:
      printf("\nThat is not a choice.\n");
    }
  }
}
Пример #14
0
/**********************************************************************
 *  Function  basic_alg_menu();
 *                                                                    
 *  Parameter:                                                       
 *   
 *                                                              
 *  This function prompts user to choose a basic algorithm to execute
 *  such as Boyer-Moore.  The utilities menu is also available from
 *  this menu.
 *                                                                   
 **********************************************************************/
void basic_alg_menu()
{
  int i, status, num_lines, alpha_size, num_patterns;
  char ch;
  STRING *text, *pattern, **patterns;

  alpha_size = 0;
  while (1)  {
    num_lines = 22;
    printf("\n**   Basic Search Algorithm Menu    **\n\n");
    printf("1)  Naive Algorithm\n");
    printf("2)  Boyer-Moore Variations\n");
    printf("     a) Bad character rule\n");
    printf("     b) Extended bad character rule\n");
    printf("     c) Good suffix & bad character rules\n");
    printf("     d) Good suffix & extended bad character rules\n");
    printf("3)  Knuth-Morris-Pratt (original preprocessing)\n");
    printf("     a) using sp values\n");
    printf("     b) using sp' values\n");
    printf("4)  Aho-Corasick Set Matching\n");
    printf("5)  Boyer-Moore Set Matching\n");
    printf("     a) Bad character rule only\n");
    printf("     b) Good suffix rule using keyword and suffix trees\n");
    printf("     c) Good suffix rule using suffix tree only\n");
    printf("     d) using original Boyer-Moore (1c) on each pattern\n");
    printf("*)  String Utilites\n");
    printf("0)  Exit\n");
    printf("\nEnter Selection: ");
  
    while ((choice = my_getline(stdin, &ch_len)) == NULL) ;
    switch (choice[0]) {
    case '0':
      return;

    case '1':
      if (!(pattern = get_string("pattern")) || !(text = get_string("text")))
        continue;

      mstart(stdin, fpout, OK, OK, 5, NULL);
      mprintf("\nThe pattern:\n");
      terse_print_string(pattern);
      mprintf("\nThe text:\n");
      terse_print_string(text);
      mputc('\n');
        
      status = map_sequences(text, pattern, NULL, 0);
      if (status != -1) {
        mprintf ("Executing naive search algorithm...\n\n");
        strmat_naive_match(pattern, text, stats_flag);
        unmap_sequences(text, pattern, NULL, 0);
      }
      mend(num_lines);
      putchar('\n');
      break;

    case '2':
      ch = choice[1];
      if (toupper(ch) != 'A' && toupper(ch) != 'B' &&
          toupper(ch) != 'C' && toupper(ch) != 'D') {
        printf("\nYou must specify the Boyer-Moore variation"
               " (as in '2a' or '2c').\n");
        continue;
      }

      if (!(pattern = get_string("pattern")) || !(text = get_string("text")))
        continue;

      mstart(stdin, fpout, OK, OK, 5, NULL);
      mprintf("\nThe pattern:\n");
      terse_print_string(pattern);
      mprintf("\nThe text:\n");
      terse_print_string(text);
      mputc('\n');

      status = map_sequences(text, pattern, NULL, 0);
      if (status != -1) {
        mprintf("Executing Boyer-Moore algorithm...\n\n");
        switch (toupper(ch)) {
        case 'A':  strmat_bmbad_match(pattern, text, stats_flag);  break;
        case 'B':  strmat_bmext_match(pattern, text, stats_flag);  break;
        case 'C':  strmat_bmgood_match(pattern, text, stats_flag);  break;
        case 'D':  strmat_bmextgood_match(pattern, text, stats_flag);  break;
        }
        unmap_sequences(text, pattern, NULL, 0);
      }
      mend(num_lines);
      putchar('\n');
      break;

    case '3':
      ch = choice[1];
      if (toupper(ch) != 'A' && toupper(ch) != 'B') {
        printf("\nYou must specify the KMP variation (as in '3a' or '3b').\n");
        continue;
      }

      if (!(pattern = get_string("pattern")) || !(text = get_string("text")))
        continue;

      mstart(stdin, fpout, OK, OK, 5, NULL);
      mprintf("\nThe pattern:\n");
      terse_print_string(pattern);
      mprintf("\nThe text:\n");
      terse_print_string(text);
      mputc('\n');
        
      status = map_sequences(text, pattern, NULL, 0);
      if (status != -1) {
        if (toupper(ch) == 'A') {
          mprintf ("Executing KMP with sp values...\n\n");
          strmat_kmp_sp_orig_match(pattern, text, stats_flag);
        }
        else {
          mprintf ("Executing KMP with sp' values...\n\n");
          strmat_kmp_spprime_orig_match(pattern, text, stats_flag);
        }
        unmap_sequences(text, pattern, NULL, 0);
      }
      mend(num_lines);
      putchar('\n');
      break;

    case '4':
      if (!(patterns = get_string_ary("list of patterns", &num_patterns)))
        continue;
      if (!(text = get_string("text"))) {
        free(patterns);
        continue;
      }

      mstart(stdin, fpout, OK, OK, 5, NULL);
      mprintf("\nThe patterns:\n");
      for (i=0; i < num_patterns; i++) {
        mprintf("%2d)", i + 1);
        terse_print_string(patterns[i]);
      }
      mprintf("\nThe text:\n");
      terse_print_string(text);
      mputc('\n');

      status = map_sequences(text, NULL, patterns, num_patterns);
      if (status != -1) {
        mprintf("Executing Aho-Corasick algorithm...\n\n");
        strmat_ac_match(patterns, num_patterns, text, stats_flag);
        unmap_sequences(text, NULL, patterns, num_patterns);
      }
      mend(num_lines);
      putchar('\n');

      free(patterns);
      break;

    case '5':
      ch = toupper(choice[1]);
      if (ch != 'A' && ch != 'B' && ch != 'C' && ch != 'D') {
        printf("\nYou must specify the set Boyer-Moore variation"
               " (as in '5a' or '5c').\n");
        continue;
      }

      if (!(patterns = get_string_ary("list of patterns", &num_patterns)))
        continue;
      if (!(text = get_string("text"))) {
        free(patterns);
        continue;
      }

      mstart(stdin, fpout, OK, OK, 5, NULL);
      mprintf("\nThe patterns:\n");
      for (i=0; i < num_patterns; i++) {
        mprintf("%2d)", i + 1);
        terse_print_string(patterns[i]);
      }
      mprintf("\nThe text:\n");
      terse_print_string(text);
      mputc('\n');

      status = map_sequences(text, NULL, patterns, num_patterns);
      if (status != -1) {
        mprintf("Executing Boyer-Moore set matching algorithm...\n\n");
        switch (toupper(ch)) {
        case 'A':  strmat_bmset_badonly_match(patterns, num_patterns,
                                              text, stats_flag);       break;
        case 'B':  strmat_bmset_2trees_match(patterns, num_patterns,
                                             text, stats_flag);        break;
        case 'C':  strmat_bmset_1tree_match(patterns, num_patterns,
                                            text, stats_flag);         break;
        case 'D':  strmat_bmset_naive_match(patterns, num_patterns,
                                            text, stats_flag);         break;
        }
        unmap_sequences(text, NULL, patterns, num_patterns);
      }
      mend(num_lines);
      putchar('\n');

      free(patterns);
      break;

    case '*':
      util_menu();
      break;

    default:
      printf("\nThat is not a choice.\n");
    }
  }
}
Пример #15
0
	std::string julian_short_month_name(unsigned month) {
		auto s = julian_month_name(month).substr(0, 3);
		s[1] = (char)toupper(s[1]);
		s[2] = (char)toupper(s[2]);
		return s;
	}
Пример #16
0
void R_InitSkins (void)
{
	char sndname[128];
	int sndlumps[8];
	char key[10];
	int intname;
	size_t i;
	int j, k, base;
	int stop;
	char *def;

	key[9] = 0;

	for (i = 1; i < numskins; i++)
	{
		for (j = 0; j < 8; j++)
			sndlumps[j] = -1;
		base = W_CheckNumForName ("S_SKIN", skins[i].namespc);
		// The player sprite has 23 frames. This means that the S_SKIN
		// marker needs a minimum of 23 lumps after it (probably more).
		if (base + 23 >= (int)numlumps || base == -1)
			continue;
		def = (char *)W_CacheLumpNum (base, PU_CACHE);
		intname = 0;

		// Data is stored as "key = data".
		while ( (def = COM_Parse (def)) )
		{
			strncpy (key, com_token, 9);
			def = COM_Parse (def);
			if (com_token[0] != '=')
			{
				Printf (PRINT_HIGH, "Bad format for skin %d: %s %s", i, key, com_token);
				break;
			}
			def = COM_Parse (def);
			if (!stricmp (key, "name")) {
				strncpy (skins[i].name, com_token, 16);
			} else if (!stricmp (key, "sprite")) {
				for (j = 3; j >= 0; j--)
					com_token[j] = toupper (com_token[j]);
				intname = *((int *)com_token);
			} else if (!stricmp (key, "face")) {
				for (j = 2; j >= 0; j--)
					skins[i].face[j] = toupper (com_token[j]);
			} else {
				for (j = 0; j < 8; j++) {
					if (!stricmp (key, skinsoundnames[j][0])) {
						// Can't use W_CheckNumForName because skin sounds
						// haven't been assigned a namespace yet.
						for (k = base + 1; k < (int)numlumps &&
										   lumpinfo[k].handle == lumpinfo[base].handle; k++) {
							if (!strnicmp (com_token, lumpinfo[k].name, 8)) {
								//W_SetLumpNamespace (k, skins[i].namespc);
								sndlumps[j] = k;
								break;
							}
						}
						if (sndlumps[j] == -1) {
							// Replacement not found, try finding it in the global namespace
							sndlumps[j] = W_CheckNumForName (com_token);
						}
						break;
					}
				}
				//if (j == 8)
				//	Printf (PRINT_HIGH, "Funny info for skin %i: %s = %s\n", i, key, com_token);
			}
		}

		if (skins[i].name[0] == 0)
			sprintf (skins[i].name, "skin%d", (unsigned)i);

		// Register any sounds this skin provides
		for (j = 0; j < 8; j++) {
			if (sndlumps[j] != -1) {
				if (j > 1) {
					sprintf (sndname, "player/%s/%s", skins[i].name, skinsoundnames[j][1]);
					S_AddSoundLump (sndname, sndlumps[j]);
				} else if (j == 1) {
					int r;

					for (r = 1; r <= 4; r++) {
						sprintf (sndname, "player/%s/death%d", skins[i].name, r);
						S_AddSoundLump (sndname, sndlumps[j]);
					}
				} else {	// j == 0
					int l, r;

					for (l =  1; l <= 4; l++)
						for (r = 1; r <= 2; r++) {
							sprintf (sndname, "player/%s/pain%d_%d", skins[i].name, l*25, r);
							S_AddSoundLump (sndname, sndlumps[j]);
						}
				}
			}
		}

		// Now collect the sprite frames for this skin. If the sprite name was not
		// specified, use whatever immediately follows the specifier lump.
		if (intname == 0) {
			intname = *(int *)(lumpinfo[base+1].name);
			for (stop = base + 2; stop < (int)numlumps &&
								  lumpinfo[stop].handle == lumpinfo[base].handle &&
								  *(int *)lumpinfo[stop].name == intname; stop++)
				;
		} else {
			stop = numlumps;
		}

		memset (sprtemp, -1, sizeof(sprtemp));
		maxframe = -1;

		for (k = base + 1;
			 k < stop && lumpinfo[k].handle == lumpinfo[base].handle;
			 k++) {
			if (*(int *)lumpinfo[k].name == intname)
			{
				R_InstallSpriteLump (k,
									 lumpinfo[k].name[4] - 'A', // denis - fixme - security
									 lumpinfo[k].name[5] - '0',
									 false);

				if (lumpinfo[k].name[6])
					R_InstallSpriteLump (k,
									 lumpinfo[k].name[6] - 'A',
									 lumpinfo[k].name[7] - '0',
									 true);

				//W_SetLumpNamespace (k, skins[i].namespc);
			}
		}
		R_InstallSprite ((char *)&intname, (skins[i].sprite = (spritenum_t)(numsprites - numskins + i)));

		// Now go back and check for face graphics (if necessary)
		if (skins[i].face[0] == 0 || skins[i].face[1] == 0 || skins[i].face[2] == 0) {
			// No face name specified, so this skin doesn't replace it
			skins[i].face[0] = 0;
		} else {
			// Need to go through and find all face graphics for the skin
			// and assign them to the skin's namespace.
			for (j = 0; j < 8; j++)
				strncpy (facenames[j], skins[i].face, 3);

			for (k = base + 1;
				 k < (int)numlumps && lumpinfo[k].handle == lumpinfo[base].handle;
				 k++) {
				for (j = 0; j < 8; j++)
					if (!strncmp (facenames[j], lumpinfo[k].name, facelens[j])) {
						//W_SetLumpNamespace (k, skins[i].namespc);
						break;
					}
			}
		}
	}
	// Grrk. May have changed sound table. Fix it.
	if (numskins > 1)
		S_HashSounds ();
}
Пример #17
0
//*****************************************************************************
// unescape( orig) - Return a string with escaped character sequences replaced 
// by the actual characters that the escape codes refer to.
char* unescape( char *orig)
{
  // Loop: Examine pointers to successive words of the string
  char c, *cp, *result = orig;
  int i;
  for( cp = orig; (*orig = *cp); cp++, orig++) {

    // If this is not an escape sequence, keep going
    if (*cp != '\\') continue;

    // Check for different escape sequences
    switch (*++cp) {
    case 'a':  /* alert (bell) */
      *orig = '\a';
      continue;
    case 'b':  /* backspace */
      *orig = '\b';
      continue;
    case 'e':  /* escape */
      *orig = '\e';
      continue;
    case 'f':  /* formfeed */
      *orig = '\f';
      continue;
    case 'n':  /* newline */
      *orig = '\n';
      continue;
    case 'r':  /* carriage return */
      *orig = '\r';
      continue;
    case 't':  /* horizontal tab */
      *orig = '\t';
      continue;
    case 'v':  /* vertical tab */
      *orig = '\v';
      continue;
    case '\\':  /* backslash */
      *orig = '\\';
      continue;
    case '\'':  /* single quote */
      *orig = '\'';
      continue;
    case '\"':  /* double quote */
      *orig = '"';
      continue;
    case '0':
    case '1':
    case '2':
    case '3':  /* octal */
    case '4':
    case '5':
    case '6':
    case '7':  /* number */
      for( i = 0, c = 0;
           ISODIGIT((unsigned char)*cp) && i < 3;
           i++, cp++) {
        c <<= 3;
        c |= (*cp - '0');
      }
      *orig = c;
      continue;
    case 'x':  /* hexidecimal number */
      cp++;  /* skip 'x' */
      for (i = 0, c = 0;
           isxdigit((unsigned char)*cp) && i < 2;
           i++, cp++) {
        c <<= 4;
        if (isdigit((unsigned char)*cp))
          c |= (*cp - '0');
        else
          c |= ((toupper((unsigned char)*cp) -
              'A') + 10);
      }
      *orig = c;
      continue;
    default:
      --cp;
      break;
    }
  }

  // Return result and quit
  return (result);
}
Пример #18
0
int main()
{
    OUTPUT *final_w=NULL, *current_pointer=NULL, *last_pointer = NULL, *control=NULL;
    FILE *fboard=NULL, *fdict=NULL, *output=NULL;
    int *array_x=NULL, *array_y=NULL;
    int nwords=0, len=0, find_word=0, inserted=0, limit_words=0, name_len=0, len_board=0, found=0, final_score=0;
    int v=0, i=0, j=0, x=0, y=0;
    int matrixPnt[4][4];
    int matrixBns[4][4];
    char pntboard[4][4];
    char bonusboard[4][4];
    char word[MAX_LNGTH+1];
    char cboard[4][4];
    char *name_board=NULL, *name_dict=NULL;

    printf("Input board file name: ");
    name_board = (char*)malloc(20*sizeof(char));
    if(name_board == NULL)
    {
        printf("\nMemory allocation error\n");
        system("pause");
        exit(EXIT_FAILURE);
    }

    scanf("%s", name_board);
    len_board = strlen(name_board);
    name_board = (char*) realloc(name_board, len_board + 1);
    if(name_board == NULL)
    {
        printf("\nMemory allocation error\n");
        system("pause");
        exit(EXIT_FAILURE);
    }

    fboard=fopen(name_board,"r");
    if(fboard==NULL)
    {
        printf("\nError opening file %s\n","board.txt");
        system("pause");
        exit(EXIT_FAILURE);
    }

    printf("Input dictionary file name: ");
    name_dict = (char*)malloc(20*sizeof(char));
    if(name_dict == NULL)
    {
        printf("\nMemory allocation error\n");
        system("pause");
        exit(EXIT_FAILURE);
    }
    scanf("%s", name_dict);
    len_board = strlen(name_dict);
    name_dict = (char*) realloc(name_dict, len_board + 1);
    if(name_dict == NULL)
    {
        printf("\nMemory allocation error\n");
        system("pause");
        exit(EXIT_FAILURE);
    }

    fdict = fopen(name_dict,"r");
    if(fdict == NULL)
    {
        printf("Uploaded file was not found. It uses the default file.\n");
        system("pause");
        fdict = fopen("dict.txt","r");
    }
    else
    {
        for(i=0; i<4; i++)
            fscanf(fboard, "%c%c%c%c\n", &cboard[i][0], &cboard[i][1], &cboard[i][2], &cboard[i][3]);

        for(i=0; i<4; i++)
            fscanf(fboard, "%c%c%c%c\n", &pntboard[i][0], &pntboard[i][1], &pntboard[i][2], &pntboard[i][3]);

        for(i = 0; i < 4; i++)
        {
            for(j = 0; j<4 ; j++)
            {
                matrixPnt[i][j] = ((int)pntboard[i][j])-((int)('0'));
            }
        }

        for(i=0; i<4; i++)
            fscanf(fboard, "%c%c%c%c\n", &bonusboard[i][0], &bonusboard[i][1], &bonusboard[i][2], &bonusboard[i][3]);

        for(i = 0; i < 4; i++)
        {
            for(j = 0; j<4 ; j++)
            {
                matrixBns[i][j] = ((int)bonusboard[i][j])-((int)('0'));
            }
        }
    }

    printf("Input words to be found (default type 0): ");
    scanf("%d", &nwords);
    if(nwords == 0)
        nwords = default_nwords;

    if(fdict==NULL)
    {
        printf("\nError opening file: %s\n","dict.txt");
        system("pause");
        exit(EXIT_FAILURE);
    }
    else
    {
        while( fgets(word, 1024, fdict)!= NULL )
        {
            v = isalpha(word[0]); /*commento dict*/
            if(v > 0)
            {
                len=0;
                while((word[len] != '/') && (word[len] != '\n'))
                {
                    if(word[len] == '\'') /*apostrofo*/
                    {
                        len=TRUE;
                        word[len] = '\n';
                    }
                    else
                    len++;
                }
                word[len] = '\0';
                len = strlen(word);
                if( (len <= 16) && (len > 1) )
                {
                    accent_c(word);
                    array_x = (int*) malloc(len*sizeof(int));
                    if(array_x == NULL)
                    {
                        printf("\nMemory allocation error\n");
                        system("pause");
                        exit(EXIT_FAILURE);
                    }

                    array_y = (int*) malloc(len*sizeof(int));
                    if(array_y == NULL)
                    {
                        printf("\nMemory allocation error\n");
                        system("pause");
                        exit(EXIT_FAILURE);
                    }

                    for(i=0; i<len; i++)
                    {
                        array_x[i] = 0;
                        array_y[i] = 0;
                        word[i] = toupper(word[i]);
                    }

                    control = controller(word, cboard, array_x, array_y, matrixPnt, matrixBns, len);

                    if(control != NULL)
                    {
                        find_word++;

                        control->array_x = (int*) malloc(len*sizeof(int));
                        if( (control->array_x) == NULL)
                        {
                            printf("\nMemory allocation error\n");
                            system("pause");
                            exit(EXIT_FAILURE);
                        }

                        control->array_y = (int*) malloc(len*sizeof(int));
                        if( (control->array_y) == NULL)
                        {
                            printf("\nMemory allocation error\n");
                            system("pause");
                            exit(EXIT_FAILURE);
                        }

                        for(i=0;i<len;i++)
                        {
                            control->array_x[i] = array_x[i];
                            control->array_y[i] = array_y[i];
                        }

                        if(final_w == NULL)
                        {
                            control->next = NULL;
                            final_w = control;
                        }
                        else
                        {
                            control->next = NULL;
                            current_pointer = final_w;
                            last_pointer = final_w;
                            inserted = FALSE;
                            while(current_pointer != NULL && inserted == FALSE)
                            {
                                if(current_pointer->pnt < control->pnt)
                                {
                                    if(current_pointer == last_pointer)
                                    {
                                        control->next = final_w;
                                        final_w = control;
                                        inserted = TRUE;
                                    }
                                    else
                                    {
                                        control->next = current_pointer;
                                        last_pointer->next = control;
                                        inserted = TRUE;
                                    }
                                }
                                last_pointer = current_pointer;
                                current_pointer = current_pointer->next;
                            }
                            if(inserted == FALSE)
                            {
                                last_pointer->next = control;
                            }
                        }
                    }
                }
            }
        }
    }

    current_pointer = final_w;

    name_len = (strlen(name_board)) - exe;
    name_board[name_len] = '\0';

    output = fopen(strcat(name_board, "_results.txt"), "w");

    final_score = 0;
    while( (current_pointer != NULL) && (limit_words < nwords) )
    {
        fprintf(output, "%s %d \n", current_pointer->word, current_pointer->pnt);
        final_score = final_score + current_pointer->pnt;
        for(i=0; i<4; i++)
        {
            for(j=0; j<4; j++)
            {
                found = FALSE;
                len = strlen(current_pointer->word);

                for(v=0;v<len;v++)
                {
                    x = current_pointer->array_x[v];
                    y = current_pointer->array_y[v];
                    if((y == i) && (x == j))
                    {
                        found = TRUE;
                    }
                }
                if(found == FALSE)
                {
                    fprintf(output, "%c", tolower(cboard[i][j]));
                }
                else
                {
                    fprintf(output, "%c", cboard[i][j]);
                }
            }
            fprintf(output, "\n");
        }
        fprintf(output, "\n");
        current_pointer = current_pointer->next;
        limit_words++;
    }
    fprintf(output, "\n");
    fprintf(output, "Final Score: %d\n", final_score);
    fprintf(output, "Total words: %d", find_word);

    if(limit_words == nwords)
    {
        free(name_dict);
        free(array_x);
        free(array_y);
        free(control);
        while(current_pointer != NULL)
        {
            last_pointer =current_pointer;
            current_pointer =current_pointer->next;
            free(last_pointer);
        }
    }

    fclose(fboard);
    fclose(fdict);

    system("pause");
    return 0;
}
Пример #19
0
int main(int argc, char **argv)
{
	if (argc != 3)
	{
		fprintf(stderr, "give 2 args\n");
		exit(-1);
	}
    pid2_t = mmap(NULL, sizeof(*pid2_t), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
    pid_t lpid1, lpid2;
	char file2[FILE_NAME_SIZE];
    strncpy(file2, argv[2], FILE_NAME_SIZE);
	char input[256];
    strncpy(file1, argv[1], FILE_NAME_SIZE);
	pipe(pipe1);
	pipe(pipe2);

	signal(SIGINT, terminate);
    
	if ((lpid1 = fork()) == 0)
	{
		int read_bytes = 0;
		char c;
        printf("1 process pid is %d\n", getpid());
		signal(SIGUSR1, switch_files);
		fd1 = open(file1, O_RDONLY);
		if (fd1 < 0)
		{
			fprintf(stderr, "error opening file %s\n", file1);
			return -1;
		}
		while(1)
		{
			read_bytes = read(fd1, &c, 1);
			if (read_bytes > 0)
			{ 
    		    fprintf(stdout, "%c\n", toupper(c));
			}
			usleep(500000);			
		}
		close(fd1);
		printf("fd1 closed\n");
		return 0;
	} else {
        pid1 = lpid1;
    }

	if ((lpid2 = fork()) == 0)
	{
		int read_bytes = 0;
		char c;
		printf("2 process pid is %d\n", getpid());
		signal(SIGUSR2, switch_files);
		fd2 = open(file2, O_RDONLY);
		if (fd2 < 0)
		{
			fprintf(stderr, "error opening file %s\n", file2);
			return -1;
		}
		while(1)
		{
			read_bytes = read(fd2, &c, 1);
			if (read_bytes > 0)
			{
    		    fprintf(stdout, "\t%c\n", tolower(c));
			}
			usleep(500000);
		}
		close(fd2);
		printf("fd2 closed\n");
		return 0;
	} else {
        *pid2_t = lpid2;
        pid2 = lpid2;
    }
    
    printf("%d %d\n", pid1, pid2);
	while(scanf("%s", input) > 0)
	{
		write(pipe1[1], input, strlen(input) + 1);
		kill(pid1, SIGUSR1);
	}

	waitpid(pid1, 0, 0);
	waitpid(pid2, 0, 0);
	printf("exit\n");
}
Пример #20
0
/* Parse the key and value from a memory buffer. */
char *hcfg_parse(char *buf, char **key, char **val)
{
    char *ptr = NULL;

    *key = NULL;
    *val = NULL;

    /* Skip leading key whitespace. */
    while (isspace(*buf) && *buf != '\n')
        ++buf;

    /* Skip empty lines and comments. */
    if (*buf == '\n' || *buf == '#')
        goto endline;

    if (!isalnum(*buf) && *buf != '_')
        return NULL;

    /* Force key strings to be uppercase. */
    *key = buf;
    while (isalnum(*buf) || *buf == '_') {
        *buf = toupper(*buf);
        ++buf;
    }

    /* Check that key string was valid. */
    ptr = buf;
    while (isspace(*buf) && *buf != '\n')
        ++buf;

    if (*(buf++) != '=')
        return NULL;

    while (isspace(*buf) && *buf != '\n')
        ++buf;

    /* Kill whitespace and separator between key and value. */
    while (ptr < buf)
        *(ptr++) = '\0';

    /* Unquote the value string. */
    *val = buf;
    ptr = buf;
    while (*buf && *buf != '\n') {
        if (*buf ==  '#') goto endline;
        if (*buf == '\\') ++buf;
        *(ptr++) = *(buf++);
    }

  endline:
    buf += strcspn(buf, "\n");
    if (*buf == '\n')
        ++buf;

    /* Kill trailing value whitespace. */
    if (ptr) {
        do *(ptr--) = '\0';
        while (isspace(*ptr));
    }
    return buf;
}
Пример #21
0
int CompleteSF_Info(T_SF_Info *SFI, int LblExact, int Set_f_stol_0)
{
  int          m;
  const char   *lt, *li;
  int          iSFT;
  T_SF_Tables  *SFT;


  if (SFI->SFT || SFI->CAA || SFI->f_stol_0 != -1.)
    InternalError("CompleteSF_Info(): SFI already set");

  SFT = SF_Tables;

  for (iSFT = 0; iSFT < nSF_Tables; iSFT++, SFT++)
  {
    if (str_icmp(SFT->Label, SFI->Lbl) == 0)
    {
      SFI->SFT = SFT;
      break;
    }
  }

  if (SFI->SFT == NULL && LblExact == 0)
  {
    SFT = SF_Tables;

    for (iSFT = 0; iSFT < nSF_Tables; iSFT++, SFT++)
    {
      m = 0;

      for (lt = SFT->Label, li = SFI->Lbl; isalpha(*lt); lt++, li++)
      {
        if (toupper(*lt) != toupper(*li))
        {
          m = 0;
          break;
        }

        m++;
      }

      if (m)
      {
        SFI->SFT = SFT;
        break;
      }
    }
  }

  if (SFI->SFT)
  {
    if (Set_f_stol_0)
    {
      if (SFI->SFT->Tab[0].stol != 0.)
      {
        char  buf[128];

        Sprintf(buf,
          "ScatteringFactor %.60s: missing entry for sinTovL = 0",
          SFI->SFT->Label);

        progerror(buf);
      }

      SFI->f_stol_0 = SFI->SFT->Tab[0].f;
    }
  }
  else
  {
    if (ModeScatteringFactorTable == 0)
    {
      SFI->CAA = FindSF_WK95_CAA(SFI->Lbl, LblExact);
      // printf("atom: %s -> using xray scattering factors from WK95\n", SFI->Lbl);
      if (NULL == SFI->CAA)
        return -1;
  
      if (Set_f_stol_0)
        SFI->f_stol_0 = CalcSF_WK95_CAA(SFI->CAA, 0.);
    }
 //   else if (ModeScatteringFactorTable == 1)
 //   {
 //     SFI->CAA = FindSF_IT92_CAA(SFI->Lbl, LblExact);
 //     printf("%s -> using scattering factors from IT92\n", SFI->Lbl);
 //     if (NULL == SFI->CAA)
 //       return -1;
 // 
 //     if (Set_f_stol_0)
 //       SFI->f_stol_0 = CalcSF_IT92_CAA(SFI->CAA, 0.);
 //   }
    else if (ModeScatteringFactorTable == 2)
    {
      SFI->CAA = FindSF_IT4322(SFI->Lbl, LblExact); // StefS 
      // printf("atom: %s -> using electron scattering factors from IT 4.3.2.2\n", SFI->Lbl); 
      if (NULL == SFI->CAA)
        return -1;
  
      if (Set_f_stol_0)
        SFI->f_stol_0 = CalcSF_IT4322(SFI->CAA, 0.);
    }
    else if (ModeScatteringFactorTable == 3)
    {
      SFI->CAA = FindSF_IT4323(SFI->Lbl, LblExact); // StefS 
      // printf("atom: %s -> using electron scattering factors from IT 4.3.2.3\n", SFI->Lbl); 
      if (NULL == SFI->CAA)
        return -1;
  
      if (Set_f_stol_0)
        SFI->f_stol_0 = CalcSF_IT4323(SFI->CAA, 0.);
    }
  }

  return 0;
}
Пример #22
0
// *************************************************************
//   Configuration helpers
// *************************************************************
int
run (int argc, ACE_TCHAR *argv[])
{
    int rc = 0;

    ProactorTask task1(cfg);

    RecvFactory r_factory;
    SendFactory s_factory;

    PSessionManager r_manager (task1, r_factory,"R_Manager");
    PSessionManager s_manager (task1, s_factory,"S_Manager");

    Acceptor  acceptor  (r_manager);
    Connector connector (s_manager);

    ACE_Time_Value time_begin = ACE_OS::gettimeofday ();
    ACE_Time_Value time_end = ACE_OS::gettimeofday ();
    ACE_Time_Value time_run;

    if (task1.start () == 0)
    {
        task1.enable_event_loop();

        ACE_Time_Value timeout (cfg.timeout(), 0);
        r_manager.set_timeout (timeout);
        s_manager.set_timeout (timeout);

        if (cfg.both() != 0 || cfg.connections () == 0) // Acceptor
        {
            if (acceptor.start (ACE_INET_Addr (cfg.listen_port())) == 0)
                rc = 1;
        }

        if (cfg.both() != 0 || cfg.connections () > 0) // Connector
        {
            ACE_INET_Addr addr;

            addr.set (cfg.connect_port(), cfg.connect_host());

            rc += connector.start (addr, cfg.connections ());
        }
    }

    time_begin = ACE_OS::gettimeofday ();

    if (rc > 0)
    {
        //task1.enable_event_loop();
        
        ACE_Time_Value  sleep_time (cfg.seconds());
        
        while ( sleep_time != ACE_Time_Value::zero)
        {
            ACE_Countdown_Time countdown ( & sleep_time );
            ACE_OS::sleep (sleep_time );
        }

        if (cfg.seconds () == 0)
        {
            bool flgExit = false;
            for (;!flgExit;)
            {
                char c;
                cout << "\nPress Q to stop=>" << flush;
                cin.clear ();
                cin >> c;
                switch (toupper (c))
                {
                case 'Q':
                    flgExit = true;
                    break;
                case 'P':
                    cout << "\n*** Connector: PendingConnects="
                        << connector.get_ref_cnt()
                        << " Senders="
                        << s_manager.get_number_connections ()
                        << "\n*** Acceptor: PendingAccepts="
                        << acceptor.get_ref_cnt()
                        << " Receivers="
                        << r_manager.get_number_connections ();
                break;
                }//switch
            }//for
        }//if cfg.seconds
Пример #23
0
void countCharWordsSentCase(char fileName[], char fileName2[], int* charCount, int* wordCount, int* sentenceCount)
{
	//char c;
	char ch;
	FILE *fp1, *fp2;
	int no_of_char = 0, no_of_words = 1, no_of_sent = 0;
	fp1= fopen(fileName,"r");
	if( fp1 == NULL )
	{
		perror("Error while opening the file.\n");
		exit(EXIT_FAILURE);
	}

	fp2 = fopen(fileName2,"w");
	if( fp2 == NULL )
	{
		perror("Error while opening the file.\n");
		exit(EXIT_FAILURE);
	}

	//upper to lower and viceversa
	while (!feof(fp1)) {
		no_of_char++;
		ch = fgetc(fp1);

		if (ch == ' ' || ch == '.' || ch == '\n' || ch == '\t')
		{
			if(ch == ' ' || ch == '\n' || ch == '\t')
			{
				fputc(ch,fp2);
				no_of_words++;
			}
			else
				if(ch == '.')
				{
					fputc(ch,fp2);
					no_of_sent++;
				}
		}

		else
			if (isalpha(ch))
			{
				if (isupper(ch))
				{
					fputc(tolower(ch),fp2);
				}
				else {
					fputc(toupper(ch),fp2);
				}
			}
			else
			{
				//fputc(' ',fp2);
			}
	}
	fclose(fp1);
	fclose(fp2);

	no_of_char--;
	*charCount = no_of_char;
	*wordCount = no_of_words;
	*sentenceCount = no_of_sent;

	return;

}
Пример #24
0
static int
load_dll(ClipMachine * ClipMachineMemory, const char *name, struct Coll *names, ClipVar * resp)
{
   void *hp;

   char buf[256], *s, *e;

   char uname[128];

   const char **spp;

   ClipModule *entry;

   ClipFunction **fpp;

   ClipNameEntry *np;

   ClipFile **cpp;

   struct DBFuncTable **dpp;

   int l, ret = 0, i;

   s = strrchr(name, '/');
   if (s)
      snprintf(buf, sizeof(buf), "%s", name);
   else
      snprintf(buf, sizeof(buf), "%s/lib/%s ", CLIPROOT, name);

   if (!loaded_dlls)
   {
      loaded_dlls = new_Coll(free, strcmp);
   }
   else
   {
      if (search_Coll(loaded_dlls, buf, 0))
	 return 0;
   }

#ifdef OS_MINGW
   hp = lt_dlopen(buf);
#else
   hp = dlopen(buf, RTLD_NOW);
#endif
   if (!hp)
   {
      _clip_trap_printf(ClipMachineMemory, __FILE__, __LINE__, "shared loading problem: %s: file %s", dlerror(), buf);
      return _clip_call_errblock(ClipMachineMemory, 1);
   }

   insert_Coll(loaded_dlls, strdup(buf));

/*
   path/name.ext -> name_module entry symbol
 */

   s = strrchr(name, '/');
   if (!s)
      s = (char *) name;
   else
      s = s + 1;
   e = strchr(s, '.');
   if (e)
      l = e - s;
   else
      l = strlen(s);
   if (l > sizeof(uname))
      l = sizeof(uname);

   for (i = 0; i < l; i++, s++)
   {
      if (*s == '-')
	 uname[i] = '_';
      else
	 uname[i] = toupper(*s);
   }
   uname[l] = 0;
   snprintf(buf, sizeof(buf), "clip__MODULE_%s", uname);

#ifdef OS_MINGW
   entry = (ClipModule *) lt_dlsym(hp, buf);
#else
   entry = (ClipModule *) dlsym(hp, buf);
#endif

   if (!entry)
   {
      _clip_trap_printf(ClipMachineMemory, __FILE__, __LINE__, "shared '%s' fetch name '%s' problem: %s", name, buf, dlerror());
      return _clip_call_errblock(ClipMachineMemory, 1);
   }

   for (np = entry->ClipNameEntry_cfunctions_of_ClipModule; np && np->ClipFunction_function_of_ClipNameEntry; ++np)
      _clip_register_hash(ClipMachineMemory, np->ClipFunction_function_of_ClipNameEntry, np->hash_of_ClipNameEntry);

   for (fpp = entry->ClipFunction_inits_of_ClipModule; fpp && *fpp; ++fpp)
      _clip_main_func(ClipMachineMemory, *fpp, _clip_argc, _clip_argv, _clip_envp);

   for (fpp = entry->ClipFunction_exits_of_ClipModule; fpp && *fpp; ++fpp)
   {
      ClipMachineMemory->cexits = (ClipFunction **) realloc(ClipMachineMemory->cexits, (ClipMachineMemory->ncexits + 1) * sizeof(ClipFunction *));
      ClipMachineMemory->cexits[ClipMachineMemory->ncexits] = *fpp;
      ++ClipMachineMemory->ncexits;
   }

   for (spp = entry->pfunctions_of_ClipModule; spp && *spp; ++spp)
      if (_clip_load(ClipMachineMemory, *spp, 0, 0))
	 ++ret;
/*
	if (entry->cpfile && _clip_register_file(ClipMachineMemory, entry->cpfile))
		++ret;
*/
   for (cpp = entry->cpfiles_of_ClipModule; cpp && *cpp; ++cpp)
      if (_clip_register_file(ClipMachineMemory, *cpp))
	 ++ret;

   for (dpp = entry->dbdrivers_of_ClipModule; dpp && *dpp; ++dpp)
      if (_clip_register_driver(ClipMachineMemory, *dpp))
	 ++ret;

   add_ClipVect(&ClipMachineMemory->dlls, hp);

   return ret;
}
Пример #25
0
static Variant HHVM_FUNCTION(dbase_create, const String& filename, const Variant& fields) {
  if (!fields.isArray()) {
    raise_warning("Expected array as second parameter");
    return false;
  }

  //if (php_check_open_basedir(Z_STRVAL_PP(filename) TSRMLS_CC)) {
  //  RETURN_FALSE;
  //}

  int fd;
  if ((fd = open(filename.c_str(), O_BINARY|O_RDWR|O_CREAT, 0644)) < 0) {
    raise_warning("Unable to create database (%d): %s", errno, strerror(errno));
    return false;
  }

  Array arr_fields = fields.toArray();
  ssize_t num_fields = arr_fields.size();
  if (num_fields <= 0) {
    raise_warning("Unable to create database without fields");
    close(fd);
    return false;
  }

  // have to use regular malloc() because this gets free()'d by
  // code in the dbase library.
  dbhead_t* dbh = (dbhead_t*)malloc(sizeof(dbhead_t));
  dbfield_t* dbf = (dbfield_t*)malloc(sizeof(dbfield_t) * num_fields);
  if ((dbh == nullptr) || (dbf == nullptr)) {
    raise_warning("Unable to allocate memory for header info");
    if (dbh != nullptr) {
      free(dbh);
    }
    if (dbf != nullptr) {
      free(dbf);
    }
    close(fd);
    return false;
  }

  // This will ensure close(fd) and free_dbf_head(dbh) on "return false".
  DBaseConnection dbc(dbh);

  // initialize the header structure
  dbh->db_fields = dbf;
  dbh->db_fd = fd;
  dbh->db_dbt = DBH_TYPE_NORMAL;
  strcpy(dbh->db_date, "19930818");
  dbh->db_records = 0;
  dbh->db_nfields = num_fields;
  dbh->db_hlen = sizeof(struct dbf_dhead) + 1 + num_fields * sizeof(struct dbf_dfield);

  int rlen = 1;
  // make sure that the db_format entries for all fields are set to NULL to ensure we
  // don't seg fault if there's and error and we need to call free_dbf_head() before all
  // fields have been defined.
  dbfield_t* cur_f = dbf;
  for (size_t i = 0; i < num_fields; i++, cur_f++) {
    cur_f->db_format = nullptr;
  }

  cur_f = dbf;
  int i = 0;
  for (ArrayIter arr_it(arr_fields); arr_it; ++arr_it, cur_f++, i++) {
    Array& field = arr_it.second().toArrRef();
    ArrayIter field_it(field);

    // field name
    if (!field_it) {
      raise_warning("expected field name as first element of list in field %d", i);
      return false;
    }
    const String& field_name = field_it.second().toCStrRef();
    if ((field_name.size() > 10) || (field_name.size() == 0)) {
      raise_warning("invalid field name '%s' (must be non-empty and less than or equal to 10 characters)", field_name.c_str());
      return false;
    }
    strncpy(cur_f->db_fname, field_name.c_str(), field_name.size()+1);

    // field type
    ++field_it;
    if (!field_it) {
      raise_warning("expected field type as second element of list in field %d", i);
      return false;
    }
    cur_f->db_type = toupper(field_it.second().toCStrRef().c_str()[0]);

    cur_f->db_fdc = 0;

    // verify the field length
    switch (cur_f->db_type) {
    case 'L':
      cur_f->db_flen = 1;
      break;
    case 'M':
      cur_f->db_flen = 10;
      dbh->db_dbt = DBH_TYPE_MEMO;
      // should create the memo file here, probably
      break;
    case 'D':
      cur_f->db_flen = 8;
      break;
    case 'F':
      cur_f->db_flen = 20;
      break;
    case 'N':
    case 'C':
      // field length
      ++field_it;
      if (!field_it) {
        raise_warning("expected field length as third element of list in field %d", i);
        return false;
      }
      cur_f->db_flen = field_it.second().toInt32();

      if (cur_f->db_type == 'N') {
        ++field_it;
        if (!field_it) {
          raise_warning("expected field precision as fourth element of list in field %d", i);
          return false;
        }
      }
      break;
    default:
      raise_warning("unknown field type '%c'", cur_f->db_type);
      return false;
    }
    cur_f->db_foffset = rlen;
    rlen += cur_f->db_flen;

    cur_f->db_format = get_dbf_f_fmt(cur_f);
  }

  dbh->db_rlen = rlen;
  put_dbf_info(dbh);

  // We need a copy of dbc here, because return will destroy original.
  open_dbases->insert(std::make_pair(dbh->db_fd, std::shared_ptr<DBaseConnection>(new DBaseConnection(dbc))));
  return Variant(dbh->db_fd);
}
Language *ReadLangModel(Vocab *vocab,char *filename,
                        float scale,float pen,float ngram)
{
  Language *lang;
  FILE *file;
  char buf[256],*ptr;
  int i,flags;

  lang=qalloc(sizeof(Language),1,"Language:ReadLanguage:lang");

  lang->type  = l_invalid;
  lang->vocab = vocab;
  lang->scale = scale;
  lang->pen   = pen;
  lang->name  = qalloc(1,strlen(filename)+1,"Language:ReadLanguage:lang->name");
  strcpy(lang->name,filename);

  LockSymTable(vocab->wdst);

  if ((file=fopen(filename,"r"))==NULL) 
    HError(LANG_ERR+1,"Cannot open file %s to read language",filename);

  fgets(buf,256,file);		/* Get string (max 256 chars) from file */

  for (ptr=buf;*ptr;*ptr++=toupper(*ptr)); /* Get LM identifier */
  while(isspace(*(--ptr))) *ptr=0;         /* Remove whitespaces */
  for (ptr=buf;isspace(*ptr);*ptr++=0);
  
  for (i=1;i<l_invalid;i++) {              /* Check to see which lm key the */
    if (!strcmp(ptr,lmIdentifier[i]))      /* string <ptr> corresponds to */
      lang->type=i;
  }

  if (lang->type==l_invalid)
    HError(LANG_ERR+1,"Do not recognise LM type %s",ptr);

  switch(lang->type)   /* Now call corresponding <Read> function */
    {
    case l_ngram:
      flags=ReadNGram(lang,file);
      break;
    case l_interpolate:
      flags=ReadInterpolate(lang,file);
      break;
    case l_mylm:
      flags=ReadMyLangModel(lang,file);
      break;

    /*  Add new LM types here  */
    /*  flags=Read????(lang,file); */

    case l_srilm:
      flags=ReadSriLM(lang,file);
      break;

    default:
      HError(LANG_ERR+2,"No read function for LM type %d",lang->type);
      break;
    }
  fclose(file);
  lang->flags=flags;
  return(lang);
}
Пример #27
0
void capitalize(char *str, int len) {
  int i;
  for (i = 0; i < len; i++) {
    str[i] = (char)toupper(str[i]);
  }
}
Пример #28
0
void sdstoupper(sds s) {
    int len = sdslen(s), j;

    for (j = 0; j < len; j++) s[j] = toupper(s[j]);
}
Пример #29
0
int wcshdo(int relax, struct wcsprm *wcs, int *nkeyrec, char **header)

/* ::: CUBEFACE and STOKES handling? */

{
  static const char *function = "wcshdo";

  char alt, comment[72], keyvalue[72], keyword[16], obsg[8] = "OBSG?",
       obsgeo[8] = "OBSGEO-?", ptype, xtype, xyz[] = "XYZ";
  int  bintab, col0, *colax, colnum, i, j, k, naxis, pixlist, primage,
       status = 0;
  struct wcserr **err;

  *nkeyrec = 0;
  *header  = 0x0;

  if (wcs == 0x0) return WCSHDRERR_NULL_POINTER;
  err = &(wcs->err);

  if (wcs->flag != WCSSET) {
    if ((status = wcsset(wcs))) return status;
  }

  if ((naxis = wcs->naxis) == 0) {
    return 0;
  }


  /* These are mainly for convenience. */
  alt = wcs->alt[0];
  if (alt == ' ') alt = '\0';
  colnum = wcs->colnum;
  colax  = wcs->colax;

  primage = 0;
  bintab  = 0;
  pixlist = 0;
  if (colnum) {
    bintab  = 1;
    col0 = colnum;
  } else if (colax[0]) {
    pixlist = 1;
    col0 = colax[0];
  } else {
    primage = 1;
  }


  /* WCS dimension. */
  if (!pixlist) {
    sprintf(keyvalue, "%20d", naxis);
    wcshdo_util(relax, "WCSAXES", "WCAX", 0, 0x0, 0, 0, 0, alt, colnum, colax,
      keyvalue, "Number of coordinate axes", nkeyrec, header, &status);
  }

  /* Reference pixel coordinates. */
  for (j = 0; j < naxis; j++) {
    sprintf(keyvalue, "%20.12G", wcs->crpix[j]);
    wcshdo_util(relax, "CRPIX", "CRP", WCSHDO_CRPXna, "CRPX", 0, j+1, 0, alt,
      colnum, colax, keyvalue, "Pixel coordinate of reference point",
      nkeyrec, header, &status);
  }

  /* Linear transformation matrix. */
  k = 0;
  for (i = 0; i < naxis; i++) {
    for (j = 0; j < naxis; j++, k++) {
      if (i == j) {
        if (wcs->pc[k] == 1.0) continue;
      } else {
        if (wcs->pc[k] == 0.0) continue;
      }

      sprintf(keyvalue, "%20.12G", wcs->pc[k]);
      wcshdo_util(relax, "PC", bintab ? "PC" : "P", WCSHDO_TPCn_ka,
        bintab ? 0x0 : "PC", i+1, j+1, 0, alt, colnum, colax, keyvalue,
        "Coordinate transformation matrix element",
        nkeyrec, header, &status);
    }
  }

  /* Coordinate increment at reference point. */
  for (i = 0; i < naxis; i++) {
    sprintf(keyvalue, "%20.12G", wcs->cdelt[i]);
    comment[0] = '\0';
    if (wcs->cunit[i][0]) sprintf(comment, "[%s] ", wcs->cunit[i]);
    strcat(comment, "Coordinate increment at reference point");
    wcshdo_util(relax, "CDELT", "CDE", WCSHDO_CRPXna, "CDLT", i+1, 0, 0, alt,
      colnum, colax, keyvalue, comment, nkeyrec, header, &status);
  }

  /* Units of coordinate increment and reference value. */
  for (i = 0; i < naxis; i++) {
    if (wcs->cunit[i][0] == '\0') continue;

    sprintf(keyvalue, "'%s'", wcs->cunit[i]);
    wcshdo_util(relax, "CUNIT", "CUN", WCSHDO_CRPXna, "CUNI", i+1, 0, 0, alt,
      colnum, colax, keyvalue, "Units of coordinate increment and value",
      nkeyrec, header, &status);
  }

  /* Coordinate type. */
  for (i = 0; i < naxis; i++) {
    if (wcs->ctype[i][0] == '\0') continue;

    sprintf(keyvalue, "'%s'", wcs->ctype[i]);
    strcpy(comment, "Coordinate type code");
    if (i == wcs->lng || i == wcs->lat) {
      if (strncmp(wcs->ctype[i], "RA--", 4) == 0) {
        strcpy(comment, "Right ascension, ");
      } else if (strncmp(wcs->ctype[i], "DEC-", 4) == 0) {
        strcpy(comment, "Declination, ");
      } else if (strncmp(wcs->ctype[i]+1, "LON", 3) == 0 ||
                 strncmp(wcs->ctype[i]+1, "LAT", 3) == 0) {
        switch (wcs->ctype[i][0]) {
        case 'G':
          strcpy(comment, "galactic ");
          break;
        case 'E':
          strcpy(comment, "ecliptic ");
        case 'H':
          strcpy(comment, "helioecliptic ");
        case 'S':
          strcpy(comment, "supergalactic ");
        }

        if (i == wcs->lng) {
          strcat(comment, "longitude, ");
        } else {
          strcat(comment, "latitude, ");
        }

        wcs->ctype[i][0] = toupper(wcs->ctype[i][0]);
      }

      strcat(comment, wcs->cel.prj.name);
      strcat(comment, " projection");

    } else if (i == wcs->spec) {
      spctyp(wcs->ctype[i], 0x0, 0x0, comment, 0x0, &ptype, &xtype, 0x0);
      if (ptype == xtype) {
        strcat(comment, " (linear)");
      } else {
        switch (xtype) {
        case 'F':
          strcat(comment, " (linear in frequency)");
          break;
        case 'V':
          strcat(comment, " (linear in velocity)");
          break;
        case 'W':
          strcat(comment, " (linear in wavelength)");
          break;
        }
      }
    }

    wcshdo_util(relax, "CTYPE", "CTY", WCSHDO_CRPXna, "CTYP", i+1, 0, 0, alt,
      colnum, colax, keyvalue, comment, nkeyrec, header, &status);
  }

  /* Coordinate value at reference point. */
  for (i = 0; i < naxis; i++) {
    sprintf(keyvalue, "%20.12G", wcs->crval[i]);
    comment[0] = '\0';
    if (wcs->cunit[i][0]) sprintf(comment, "[%s] ", wcs->cunit[i]);
    strcat(comment, "Coordinate value at reference point");
    wcshdo_util(relax, "CRVAL", "CRV", WCSHDO_CRPXna, "CRVL", i+1, 0, 0, alt,
      colnum, colax, keyvalue, comment, nkeyrec, header, &status);
  }

  /* Parameter values. */
  for (k = 0; k < wcs->npv; k++) {
    sprintf(keyvalue, "%20.12G", (wcs->pv[k]).value);
    if ((wcs->pv[k]).i == (wcs->lng + 1)) {
      switch ((wcs->pv[k]).m) {
      case 1:
        strcpy(comment, "[deg] Native longitude of the reference point");
        break;
      case 2:
        strcpy(comment, "[deg] Native latitude  of the reference point");
        break;
      case 3:
        if (primage) {
          sprintf(keyword, "LONPOLE%c", alt);
        } else if (bintab) {
          sprintf(keyword, "LONP%d%c", colnum, alt);
        } else {
          sprintf(keyword, "LONP%d%c", colax[(wcs->pv[k]).i - 1], alt);
        }
        sprintf(comment, "[deg] alias for %s (has precedence)", keyword);
        break;
      case 4:
        if (primage) {
          sprintf(keyword, "LATPOLE%c", alt);
        } else if (bintab) {
          sprintf(keyword, "LATP%d%c", colnum, alt);
        } else {
          sprintf(keyword, "LATP%d%c", colax[(wcs->pv[k]).i - 1], alt);
        }
        sprintf(comment, "[deg] alias for %s (has precedence)", keyword);
        break;
      }
    } else if ((wcs->pv[k]).i == (wcs->lat + 1)) {
      sprintf(comment, "%s projection parameter", wcs->cel.prj.code);
    } else {
      strcpy(comment, "Coordinate transformation parameter");
    }

    wcshdo_util(relax, "PV", "V", WCSHDO_PVn_ma, "PV", wcs->pv[k].i, -1,
      wcs->pv[k].m, alt, colnum, colax, keyvalue, comment,
      nkeyrec, header, &status);
  }

  for (k = 0; k < wcs->nps; k++) {
    sprintf(keyvalue, "'%s'", (wcs->ps[k]).value);

    wcshdo_util(relax, "PS", "S", WCSHDO_PVn_ma, "PS", wcs->ps[k].i, -1,
      wcs->ps[k].m, alt, colnum, colax, keyvalue,
      "Coordinate transformation parameter",
      nkeyrec, header, &status);
  }

  /* Celestial and spectral transformation parameters. */
  if (!undefined(wcs->lonpole)) {
    sprintf(keyvalue, "%20.12G", wcs->lonpole);
    wcshdo_util(relax, "LONPOLE", "LONP", 0, 0x0, 0, 0, 0, alt,
      colnum, colax, keyvalue, "[deg] Native longitude of celestial pole",
      nkeyrec, header, &status);
  }

  if (!undefined(wcs->latpole)) {
    sprintf(keyvalue, "%20.12G", wcs->latpole);
    wcshdo_util(relax, "LATPOLE", "LATP", 0, 0x0, 0, 0, 0, alt,
      colnum, colax, keyvalue, "[deg] Native latitude of celestial pole",
      nkeyrec, header, &status);
  }

  if (!undefined(wcs->restfrq)) {
    sprintf(keyvalue, "%20.12G", wcs->restfrq);
    wcshdo_util(relax, "RESTFRQ", "RFRQ", 0, 0x0, 0, 0, 0, alt,
      colnum, colax, keyvalue, "[Hz] Line rest frequency",
      nkeyrec, header, &status);
  }

  if (!undefined(wcs->restwav)) {
    sprintf(keyvalue, "%20.12G", wcs->restwav);
    wcshdo_util(relax, "RESTWAV", "RWAV", 0, 0x0, 0, 0, 0, alt,
      colnum, colax, keyvalue, "[Hz] Line rest wavelength",
      nkeyrec, header, &status);
  }

  /* Coordinate system title. */
  if (wcs->wcsname[0]) {
    sprintf(keyvalue, "'%s'", wcs->wcsname);
    if (bintab) {
      wcshdo_util(relax, "WCSNAME", "WCSN", 0, 0x0, 0, 0, 0, alt,
        colnum, colax, keyvalue, "Coordinate system title",
        nkeyrec, header, &status);
    } else {
      /* TWCS was a mistake. */
      wcshdo_util(relax, "WCSNAME", "TWCS", WCSHDO_WCSNna, "WCSN", 0, 0, 0,
        alt, colnum, colax, keyvalue, "Coordinate system title",
        nkeyrec, header, &status);
    }
  }

  /* Coordinate axis title. */
  if (wcs->cname) {
    for (i = 0; i < naxis; i++) {
      if (wcs->cname[i][0] == '\0') continue;

      sprintf(keyvalue, "'%s'", wcs->cname[i]);
      wcshdo_util(relax, "CNAME", "CNA", WCSHDO_CNAMna, "CNAM", i+1, 0, 0,
        alt, colnum, colax, keyvalue, "Axis name for labelling purposes",
        nkeyrec, header, &status);
    }
  }

  /* Random error in coordinate. */
  if (wcs->crder) {
    for (i = 0; i < naxis; i++) {
      if (undefined(wcs->crder[i])) continue;

      sprintf(keyvalue, "%20.12G", wcs->crder[i]);
      comment[0] = '\0';
      if (wcs->cunit[i][0]) sprintf(comment, "[%s] ", wcs->cunit[i]);
      strcat(comment, "Random error in coordinate");
      wcshdo_util(relax, "CRDER", "CRD", WCSHDO_CNAMna, "CRDE", i+1, 0, 0,
        alt, colnum, colax, keyvalue, comment, nkeyrec, header, &status);
    }
  }

  /* Systematic error in coordinate. */
  if (wcs->csyer) {
    for (i = 0; i < naxis; i++) {
      if (undefined(wcs->csyer[i])) continue;

      sprintf(keyvalue, "%20.12G", wcs->csyer[i]);
      comment[0] = '\0';
      if (wcs->cunit[i][0]) sprintf(comment, "[%s] ", wcs->cunit[i]);
      strcat(comment, "Systematic error in coordinate");
      wcshdo_util(relax, "CSYER", "CSY", WCSHDO_CNAMna, "CSYE", i+1, 0, 0,
        alt, colnum, colax, keyvalue, comment, nkeyrec, header, &status);
    }
  }

  /* Equatorial coordinate system type. */
  if (wcs->radesys[0]) {
    sprintf(keyvalue, "'%s'", wcs->radesys);
    wcshdo_util(relax, "RADESYS", "RADE", 0, 0x0, 0, 0, 0, alt,
      colnum, colax, keyvalue, "Equatorial coordinate system",
      nkeyrec, header, &status);
  }

  /* Equinox of equatorial coordinate system. */
  if (!undefined(wcs->equinox)) {
    sprintf(keyvalue, "%20.12G", wcs->equinox);
    wcshdo_util(relax, "EQUINOX", "EQUI", 0, 0x0, 0, 0, 0, alt,
      colnum, colax, keyvalue, "[yr] Equinox of equatorial coordinates",
      nkeyrec, header, &status);
  }

  /* Reference frame of spectral coordinates. */
  if (wcs->specsys[0]) {
    sprintf(keyvalue, "'%s'", wcs->specsys);
    wcshdo_util(relax, "SPECSYS", "SPEC", 0, 0x0, 0, 0, 0, alt,
      colnum, colax, keyvalue, "Reference frame of spectral coordinates",
      nkeyrec, header, &status);
  }

  /* Reference frame of spectral observation. */
  if (wcs->ssysobs[0]) {
    sprintf(keyvalue, "'%s'", wcs->ssysobs);
    wcshdo_util(relax, "SSYSOBS", "SOBS", 0, 0x0, 0, 0, 0, alt,
      colnum, colax, keyvalue, "Reference frame of spectral observation",
      nkeyrec, header, &status);
  }

  /* Observer's velocity towards source. */
  if (!undefined(wcs->velosys)) {
    sprintf(keyvalue, "%20.12G", wcs->velosys);
    wcshdo_util(relax, "VELOSYS", "VSYS", 0, 0x0, 0, 0, 0, alt,
      colnum, colax, keyvalue, "[m/s] Velocity towards source",
      nkeyrec, header, &status);
  }

  /* Reference frame of source redshift. */
  if (wcs->ssyssrc[0]) {
    sprintf(keyvalue, "'%s'", wcs->ssyssrc);
    wcshdo_util(relax, "SSYSSRC", "SSRC", 0, 0x0, 0, 0, 0, alt,
      colnum, colax, keyvalue, "Reference frame of source redshift",
      nkeyrec, header, &status);
  }

  /* Redshift of the source. */
  if (!undefined(wcs->zsource)) {
    sprintf(keyvalue, "%20.12G", wcs->zsource);
    wcshdo_util(relax, "ZSOURCE", "ZSOU", 0, 0x0, 0, 0, 0, alt,
      colnum, colax, keyvalue, "Redshift of the source",
      nkeyrec, header, &status);
  }

  /* Observatory coordinates. */
  for (k = 0; k < 3; k++) {
    if (undefined(wcs->obsgeo[k])) continue;

    sprintf(keyvalue, "%20.12G", wcs->obsgeo[k]);
    sprintf(comment, "[m] ITRF observatory %c-coordinate", xyz[k]);
    obsgeo[7] = xyz[k];
    obsg[4]   = xyz[k];
    wcshdo_util(relax, obsgeo, obsg, 0, 0x0, 0, 0, 0, ' ',
      colnum, colax, keyvalue, comment, nkeyrec, header, &status);
  }

  /* MJD of observation. */
  if (!undefined(wcs->mjdobs)) {
    sprintf(keyvalue, "%20.12G", wcs->mjdobs);

    strcpy(comment, "[d] MJD of observation");
    if (wcs->dateobs[0]) {
      if (primage || (relax & 1) == 0) {
        sprintf(comment+22, " matching DATE-OBS");
      } else {
        sprintf(comment+22, " matching DOBS%d", col0);
      }
    }

    wcshdo_util(relax, "MJD-OBS", "MJDOB", 0, 0x0, 0, 0, 0, ' ',
      colnum, colax, keyvalue, comment, nkeyrec, header, &status);
  }

  /* MJD mid-observation time. */
  if (!undefined(wcs->mjdavg)) {
    sprintf(keyvalue, "%20.12G", wcs->mjdavg);

    strcpy(comment, "[d] MJD mid-observation");
    if (wcs->dateavg[0]) {
      if (primage) {
        sprintf(comment+23, " matching DATE-AVG");
      } else {
        sprintf(comment+23, " matching DAVG%d", col0);
      }
    }

    wcshdo_util(relax, "MJD-AVG", "MJDA", 0, 0x0, 0, 0, 0, ' ',
      colnum, colax, keyvalue, comment, nkeyrec, header, &status);
  }

  /* ISO-8601 date corresponding to MJD-OBS. */
  if (wcs->dateobs[0]) {
    sprintf(keyvalue, "'%s'", wcs->dateobs);

    strcpy(comment, "ISO-8601 observation date");
    if (!undefined(wcs->mjdobs)) {
      if (primage) {
        sprintf(comment+25, " matching MJD-OBS");
      } else {
        sprintf(comment+25, " matching MJDOB%d", col0);
      }
    }

    if (relax & 1) {
      /* Allow DOBSn. */
      wcshdo_util(relax, "DATE-OBS", "DOBS", WCSHDO_DOBSn, 0x0, 0, 0, 0,
        ' ', colnum, colax, keyvalue, comment, nkeyrec, header, &status);
    } else {
      /* Force DATE-OBS. */
      wcshdo_util(relax, "DATE-OBS", 0x0, 0, 0x0, 0, 0, 0, ' ', 0,
        0x0, keyvalue, comment, nkeyrec, header, &status);
    }
  }

  /* ISO-8601 date corresponding to MJD-OBS. */
  if (wcs->dateavg[0]) {
    sprintf(keyvalue, "'%s'", wcs->dateavg);

    strcpy(comment, "ISO-8601 mid-observation date");
    if (!undefined(wcs->mjdavg)) {
      if (primage) {
        sprintf(comment+29, " matching MJD-AVG");
      } else {
        sprintf(comment+29, " matching MJDA%d", col0);
      }
    }

    wcshdo_util(relax, "DATE-AVG", "DAVG", 0, 0x0, 0, 0, 0, ' ',
      colnum, colax, keyvalue, comment, nkeyrec, header, &status);
  }

  if (status == WCSHDRERR_MEMORY) {
    wcserr_set(WCSHDR_ERRMSG(status));
  }
  return status;
}
Пример #30
0
void DescribeKey(WPARAM wParam, char *keyw)
{
    char vkc = 0; /* virtual key code */

    vkc = /* maintain alphabet case */
        ((GetKeyState(VK_SHIFT) < 0)&&(
             !(GetKeyState(VK_CAPITAL) < 0)))
        ? toupper((char)(wParam))
        : tolower((char)(wParam));

    /* numeric pad keys 0 to 10 */
    if((wParam >= VK_NUMPAD0)&&
            (wParam <= VK_NUMPAD9))
    {
        sprintf(keyw,"[NumPad:%u]",(wParam-0x60));
    }

    /* keys from 0 to 9 , A to Z and space */
    else if(((wParam >= 0x30)
             &&(wParam <= 0x5A))
            ||(wParam == 0x20))
    {
        keyw[0] = vkc;
        keyw[1] = 0;
    }

    else switch(wParam)
        {
        case VK_CANCEL:
            strcpy(keyw,"[CTRL-BRK]");
            break;
        case VK_BACK:
            strcpy(keyw,"[BACK]");
            break;
        case VK_TAB:
            strcpy(keyw,"[TAB]");
            break;
        case VK_CLEAR:
            strcpy(keyw,"[CLEAR]");
            break;
        case VK_RETURN:
            strcpy(keyw,"[ENTER]\r\n");
            break;
        case VK_SHIFT:
            strcpy(keyw,"[SHIFT]");
            break;
        case VK_CONTROL:
            strcpy(keyw,"[CTRL]");
            break;
        case VK_MENU:
            strcpy(keyw,"[ALT]");
            break;
        case VK_PAUSE:
            strcpy(keyw,"[PAUSE]");
            break;
        case VK_CAPITAL:
            strcpy(keyw,"[CapsLock]");
            break;
        case VK_ESCAPE:
            strcpy(keyw,"[ESC]");
            break;
        case VK_PRIOR:
            strcpy(keyw,"[PageUp]");
            break;
        case VK_NEXT:
            strcpy(keyw,"[PageDown]");
            break;
        case VK_END:
            strcpy(keyw,"[END]");
            break;
        case VK_HOME:
            strcpy(keyw,"[HOME]");
            break;
        case VK_LEFT:
            strcpy(keyw,"[LEFT]");
            break;
        case VK_UP:
            strcpy(keyw,"[UP]");
            break;
        case VK_RIGHT:
            strcpy(keyw,"[RIGHT]");
            break;
        case VK_DOWN:
            strcpy(keyw,"[DOWN]");
            break;
        case VK_SELECT:
            strcpy(keyw,"[SELECT]");
            break;
        case VK_EXECUTE:
            strcpy(keyw,"[EXECUTE]");
            break;
        case VK_SNAPSHOT:
            strcpy(keyw,"[PrintScreen]");
            break;
        case VK_INSERT:
            strcpy(keyw,"[INSERT]");
            break;
        case VK_DELETE:
            strcpy(keyw,"[DELETE]");
            break;
        case VK_HELP:
            strcpy(keyw,"[HELP]");
            break;
        case VK_LWIN:
            strcpy(keyw,"[LeftWindowsKey]");
            break;
        case VK_RWIN:
            strcpy(keyw,"[RightWindowsKey]");
            break;
        case VK_APPS:
            strcpy(keyw,"[ApplicationKey]");
            break;
        case VK_MULTIPLY:
            strcpy(keyw,"[MULTIPLY]");
            break;
        case VK_ADD:
            strcpy(keyw,"[ADD]");
            break;
        case VK_SEPARATOR:
            strcpy(keyw,"[SEPERATOR]");
            break;
        case VK_SUBTRACT:
            strcpy(keyw,"[SUBTRACT]");
            break;
        case VK_DECIMAL:
            strcpy(keyw,"[DECIMAL]");
            break;
        case VK_DIVIDE:
            strcpy(keyw,"[DIVIDE]");
            break;
        case VK_F1:
            strcpy(keyw,"[F1]");
            break;
        case VK_F2:
            strcpy(keyw,"[F2]");
            break;
        case VK_F3:
            strcpy(keyw,"[F3]");
            break;
        case VK_F4:
            strcpy(keyw,"[F4]");
            break;
        case VK_F5:
            strcpy(keyw,"[F5]");
            break;
        case VK_F6:
            strcpy(keyw,"[F6]");
            break;
        case VK_F7:
            strcpy(keyw,"[F7]");
            break;
        case VK_F8:
            strcpy(keyw,"[F8]");
            break;
        case VK_F9:
            strcpy(keyw,"[F9]");
            break;
        case VK_F10:
            strcpy(keyw,"[F10]");
            break;
        case VK_F11:
            strcpy(keyw,"[F11]");
            break;
        case VK_F12:
            strcpy(keyw,"[F12]");
            break;
        case VK_F13:
            strcpy(keyw,"[F13]");
            break;
        case VK_F14:
            strcpy(keyw,"[F14]");
            break;
        case VK_F15:
            strcpy(keyw,"[F15]");
            break;
        case VK_F16:
            strcpy(keyw,"[F16]");
            break;
        case VK_NUMLOCK:
            strcpy(keyw,"[NumLock]");
            break;
        case VK_SCROLL:
            strcpy(keyw,"[ScrollLock]");
            break;
        case VK_ATTN:
            strcpy(keyw,"[ATTN]");
            break;
        case VK_CRSEL:
            strcpy(keyw,"[CrSel]");
            break;
        case VK_EXSEL:
            strcpy(keyw,"[ExSel]");
            break;
        case VK_EREOF:
            strcpy(keyw,"[EraseEOF]");
            break;
        case VK_PLAY:
            strcpy(keyw,"[PLAY]");
            break;
        case VK_ZOOM:
            strcpy(keyw,"[ZOOM]");
            break;
        default:
            sprintf(keyw,"[(%d)%c]",wParam,wParam);
            break;
        }
}