Example #1
0
void
changestats(bool ingameflag)
{
	static char flag[2] =	/* for printing values of bools */
	{'F', 'T'};
	struct player *playerp;	/* pointer to structure to alter */
	char   *prompt;		/* pointer to prompt string */
	int     c;		/* input */
	int     today;		/* day of year of today */
	int     temp;		/* temporary variable */
	long    loc;		/* location in player file */
	time_t  now;		/* time now */
	double  dtemp;		/* temporary variable */
	bool   *bptr;		/* pointer to bool item to change */
	double *dptr;		/* pointer to double item to change */
	short  *sptr;		/* pointer to short item to change */

	clear();

	for (;;)
		/* get name of player to examine/alter */
	{
		mvaddstr(5, 0, "Which character do you want to look at ? ");
		getstring(Databuf, SZ_DATABUF);
		truncstring(Databuf);

		if (Databuf[0] == '\0')
			userlist(ingameflag);
		else
			break;
	}

	loc = -1L;

	if (!ingameflag)
		/* use 'Player' structure */
		playerp = &Player;
	else
		if (strcmp(Databuf, Player.p_name) == 0)
			/* alter/examine current player */
		{
			playerp = &Player;
			loc = Fileloc;
		} else
			/* use 'Other' structure */
			playerp = &Other;

	/* find player on file */
	if (loc < 0L && (loc = findname(Databuf, playerp)) < 0L)
		/* didn't find player */
	{
		clear();
		mvaddstr(11, 0, "Not found.");
		return;
	}
	time(&now);
	today = localtime(&now)->tm_yday;

	clear();

	for (;;)
		/* print player structure, and prompt for action */
	{
		mvprintw(0, 0, "A:Name         %s\n", playerp->p_name);

		if (Wizard)
			printw("B:Password     %s\n", playerp->p_password);
		else
			addstr("B:Password     XXXXXXXX\n");

		printw(" :Login        %s\n", playerp->p_login);

		printw("C:Experience   %.0f\n", playerp->p_experience);
		printw("D:Level        %.0f\n", playerp->p_level);
		printw("E:Strength     %.0f\n", playerp->p_strength);
		printw("F:Sword        %.0f\n", playerp->p_sword);
		printw(" :Might        %.0f\n", playerp->p_might);
		printw("G:Energy       %.0f\n", playerp->p_energy);
		printw("H:Max-Energy   %.0f\n", playerp->p_maxenergy);
		printw("I:Shield       %.0f\n", playerp->p_shield);
		printw("J:Quickness    %.0f\n", playerp->p_quickness);
		printw("K:Quicksilver  %.0f\n", playerp->p_quksilver);
		printw(" :Speed        %.0f\n", playerp->p_speed);
		printw("L:Magic Level  %.0f\n", playerp->p_magiclvl);
		printw("M:Mana         %.0f\n", playerp->p_mana);
		printw("N:Brains       %.0f\n", playerp->p_brains);

		if (Wizard || playerp->p_specialtype != SC_VALAR)
			mvaddstr(0, 40, descrstatus(playerp));

		mvprintw(1, 40, "O:Poison       %0.3f\n", playerp->p_poison);
		mvprintw(2, 40, "P:Gold         %.0f\n", playerp->p_gold);
		mvprintw(3, 40, "Q:Gem          %.0f\n", playerp->p_gems);
		mvprintw(4, 40, "R:Sin          %0.3f\n", playerp->p_sin);
		if (Wizard) {
			mvprintw(5, 40, "S:X-coord      %.0f\n", playerp->p_x);
			mvprintw(6, 40, "T:Y-coord      %.0f\n", playerp->p_y);
		} else {
			mvaddstr(5, 40, "S:X-coord      ?\n");
			mvaddstr(6, 40, "T:Y-coord      ?\n");
		}

		mvprintw(7, 40, "U:Age          %ld\n", playerp->p_age);
		mvprintw(8, 40, "V:Degenerated  %d\n", playerp->p_degenerated);

		mvprintw(9, 40, "W:Type         %d (%s)\n",
		    playerp->p_type, descrtype(playerp, FALSE) + 1);
		mvprintw(10, 40, "X:Special Type %d\n", playerp->p_specialtype);
		mvprintw(11, 40, "Y:Lives        %d\n", playerp->p_lives);
		mvprintw(12, 40, "Z:Crowns       %d\n", playerp->p_crowns);
		mvprintw(13, 40, "0:Charms       %d\n", playerp->p_charms);
		mvprintw(14, 40, "1:Amulets      %d\n", playerp->p_amulets);
		mvprintw(15, 40, "2:Holy Water   %d\n", playerp->p_holywater);

		temp = today - playerp->p_lastused;
		if (temp < 0)
			/* last year */
			temp += 365;
		mvprintw(16, 40, "3:Lastused     %d  (%d)\n", playerp->p_lastused, temp);

		mvprintw(18, 8, "4:Palantir %c  5:Blessing %c  6:Virgin %c  7:Blind %c",
		    flag[(int)playerp->p_palantir],
		    flag[(int)playerp->p_blessing],
		    flag[(int)playerp->p_virgin],
		    flag[(int)playerp->p_blindness]);

		if (!Wizard)
			mvprintw(19, 8, "8:Ring    %c",
			    flag[playerp->p_ring.ring_type != R_NONE]);
		else
			mvprintw(19, 8, "8:Ring    %d  9:Duration %d",
			    playerp->p_ring.ring_type, playerp->p_ring.ring_duration);

		if (!Wizard
		/* not wizard */
		    && (ingameflag || strcmp(Login, playerp->p_login) != 0))
			/* in game or not examining own character */
		{
			if (ingameflag) {
				more(LINES - 1);
				clear();
				return;
			} else
				cleanup(TRUE);
		}
		mvaddstr(20, 0, "!:Quit       ?:Delete");
		mvaddstr(21, 0, "What would you like to change ? ");

		if (Wizard)
			c = getanswer(" ", TRUE);
		else
			/* examining own player; allow to change name and
			 * password */
			c = getanswer("!BA", FALSE);

		switch (c) {
		case 'A':	/* change name */
		case 'B':	/* change password */
			if (!Wizard)
				/* prompt for password */
			{
				mvaddstr(23, 0, "Password ? ");
				Echo = FALSE;
				getstring(Databuf, 9);
				Echo = TRUE;
				if (strcmp(Databuf, playerp->p_password) != 0)
					continue;
			}
			if (c == 'A')
				/* get new name */
			{
				mvaddstr(23, 0, "New name: ");
				getstring(Databuf, SZ_NAME);
				truncstring(Databuf);
				if (Databuf[0] != '\0')
					if (Wizard || findname(Databuf, &Other) < 0L)
						strlcpy(playerp->p_name, Databuf,
						    sizeof playerp->p_name);
			} else
				/* get new password */
			{
				if (!Wizard)
					Echo = FALSE;

				do
					/* get two copies of new password
					 * until they match */
				{
					/* get first copy */
					mvaddstr(23, 0, "New password ? ");
					getstring(Databuf, SZ_PASSWORD);
					if (Databuf[0] == '\0')
						break;

					/* get second copy */
					mvaddstr(23, 0, "One more time ? ");
					getstring(playerp->p_password, SZ_PASSWORD);
				}
				while (strcmp(playerp->p_password, Databuf) != 0);

				Echo = TRUE;
			}

			continue;

		case 'C':	/* change experience */
			prompt = "experience";
			dptr = &playerp->p_experience;
			goto DALTER;

		case 'D':	/* change level */
			prompt = "level";
			dptr = &playerp->p_level;
			goto DALTER;

		case 'E':	/* change strength */
			prompt = "strength";
			dptr = &playerp->p_strength;
			goto DALTER;

		case 'F':	/* change swords */
			prompt = "sword";
			dptr = &playerp->p_sword;
			goto DALTER;

		case 'G':	/* change energy */
			prompt = "energy";
			dptr = &playerp->p_energy;
			goto DALTER;

		case 'H':	/* change maximum energy */
			prompt = "max energy";
			dptr = &playerp->p_maxenergy;
			goto DALTER;

		case 'I':	/* change shields */
			prompt = "shield";
			dptr = &playerp->p_shield;
			goto DALTER;

		case 'J':	/* change quickness */
			prompt = "quickness";
			dptr = &playerp->p_quickness;
			goto DALTER;

		case 'K':	/* change quicksilver */
			prompt = "quicksilver";
			dptr = &playerp->p_quksilver;
			goto DALTER;

		case 'L':	/* change magic */
			prompt = "magic level";
			dptr = &playerp->p_magiclvl;
			goto DALTER;

		case 'M':	/* change mana */
			prompt = "mana";
			dptr = &playerp->p_mana;
			goto DALTER;

		case 'N':	/* change brains */
			prompt = "brains";
			dptr = &playerp->p_brains;
			goto DALTER;

		case 'O':	/* change poison */
			prompt = "poison";
			dptr = &playerp->p_poison;
			goto DALTER;

		case 'P':	/* change gold */
			prompt = "gold";
			dptr = &playerp->p_gold;
			goto DALTER;

		case 'Q':	/* change gems */
			prompt = "gems";
			dptr = &playerp->p_gems;
			goto DALTER;

		case 'R':	/* change sin */
			prompt = "sin";
			dptr = &playerp->p_sin;
			goto DALTER;

		case 'S':	/* change x coord */
			prompt = "x";
			dptr = &playerp->p_x;
			goto DALTER;

		case 'T':	/* change y coord */
			prompt = "y";
			dptr = &playerp->p_y;
			goto DALTER;

		case 'U':	/* change age */
			mvprintw(23, 0, "age = %ld; age = ", playerp->p_age);
			dtemp = infloat();
			if (dtemp != 0.0)
				playerp->p_age = (long) dtemp;
			continue;

		case 'V':	/* change degen */
			mvprintw(23, 0, "degen = %d; degen = ", playerp->p_degenerated);
			dtemp = infloat();
			if (dtemp != 0.0)
				playerp->p_degenerated = (int) dtemp;
			continue;

		case 'W':	/* change type */
			prompt = "type";
			sptr = &playerp->p_type;
			goto SALTER;

		case 'X':	/* change special type */
			prompt = "special type";
			sptr = &playerp->p_specialtype;
			goto SALTER;

		case 'Y':	/* change lives */
			prompt = "lives";
			sptr = &playerp->p_lives;
			goto SALTER;

		case 'Z':	/* change crowns */
			prompt = "crowns";
			sptr = &playerp->p_crowns;
			goto SALTER;

		case '0':	/* change charms */
			prompt = "charm";
			sptr = &playerp->p_charms;
			goto SALTER;

		case '1':	/* change amulet */
			prompt = "amulet";
			sptr = &playerp->p_amulets;
			goto SALTER;

		case '2':	/* change holy water */
			prompt = "holy water";
			sptr = &playerp->p_holywater;
			goto SALTER;

		case '3':	/* change last-used */
			prompt = "last-used";
			sptr = &playerp->p_lastused;
			goto SALTER;

		case '4':	/* change palantir */
			prompt = "palantir";
			bptr = &playerp->p_palantir;
			goto BALTER;

		case '5':	/* change blessing */
			prompt = "blessing";
			bptr = &playerp->p_blessing;
			goto BALTER;

		case '6':	/* change virgin */
			prompt = "virgin";
			bptr = &playerp->p_virgin;
			goto BALTER;

		case '7':	/* change blindness */
			prompt = "blindness";
			bptr = &playerp->p_blindness;
			goto BALTER;

		case '8':	/* change ring type */
			prompt = "ring-type";
			sptr = &playerp->p_ring.ring_type;
			goto SALTER;

		case '9':	/* change ring duration */
			prompt = "ring-duration";
			sptr = &playerp->p_ring.ring_duration;
			goto SALTER;

		case '!':	/* quit, update */
			if (Wizard &&
			    (!ingameflag || playerp != &Player))
				/* turn off status if not modifying self */
			{
				playerp->p_status = S_OFF;
				playerp->p_tampered = T_OFF;
			}
			writerecord(playerp, loc);
			clear();
			return;

		case '?':	/* delete player */
			if (ingameflag && playerp == &Player)
				/* cannot delete self */
				continue;

			freerecord(playerp, loc);
			clear();
			return;

		default:
			continue;
		}
DALTER:
		mvprintw(23, 0, "%s = %f; %s = ", prompt, *dptr, prompt);
		dtemp = infloat();
		if (dtemp != 0.0)
			*dptr = dtemp;
		continue;

SALTER:
		mvprintw(23, 0, "%s = %d; %s = ", prompt, *sptr, prompt);
		dtemp = infloat();
		if (dtemp != 0.0)
			*sptr = (short) dtemp;
		continue;

BALTER:
		mvprintw(23, 0, "%s = %c; %s = ", prompt, flag[(int)*bptr],
		    prompt);
		c = getanswer("\nTF", TRUE);
		if (c == 'T')
			*bptr = TRUE;
		else
			if (c == 'F')
				*bptr = FALSE;
		continue;
	}
}
Example #2
0
long
rollnewplayer(void)
{
	int     chartype;	/* character type */
	int     ch;		/* input */

	initplayer(&Player);	/* initialize player structure */

	clear();
	mvaddstr(4, 21, "Which type of character do you want:");
	mvaddstr(8, 4,
"1:Magic User  2:Fighter  3:Elf  4:Dwarf  5:Halfling  6:Experimento  ");
	if (Wizard) {
		addstr("7:Super  ? ");
		chartype = getanswer("1234567", FALSE);
	} else {
		addstr("?  ");
		chartype = getanswer("123456", FALSE);
	}

	do {
		genchar(chartype);	/* roll up a character */

		/* print out results */
		mvprintw(12, 14,
		    "Strength    :  %2.0f  Quickness:  %2.0f  Mana       :  %2.0f\n",
		    Player.p_strength, Player.p_quickness, Player.p_mana);
		mvprintw(13, 14,
		    "Energy Level:  %2.0f  Brains   :  %2.0f  Magic Level:  %2.0f\n",
		    Player.p_energy, Player.p_brains, Player.p_magiclvl);

		if (Player.p_type == C_EXPER || Player.p_type == C_SUPER)
			break;

		mvaddstr(14, 14, "Type '1' to keep >");
		ch = getanswer(" ", TRUE);
	}
	while (ch != '1');

	if (Player.p_type == C_EXPER || Player.p_type == C_SUPER)
		/* get coordinates for experimento */
		for (;;) {
			mvaddstr(16, 0, "Enter the X Y coordinates of your experimento ? ");
			getstring(Databuf, SZ_DATABUF);
			sscanf(Databuf, "%lf %lf", &Player.p_x, &Player.p_y);

			if (fabs(Player.p_x) > D_EXPER || fabs(Player.p_y) > D_EXPER)
				mvaddstr(17, 0, "Invalid coordinates.  Try again.\n");
			else
				break;
		}

	for (;;)
		/* name the new character */
	{
		mvprintw(18, 0,
		    "Give your character a name [up to %d characters] ?  ", SZ_NAME - 1);
		getstring(Player.p_name, SZ_NAME);
		truncstring(Player.p_name);	/* remove trailing blanks */

		if (Player.p_name[0] == '\0')
			/* no null names */
			mvaddstr(19, 0, "Invalid name.");
		else
			if (findname(Player.p_name, &Other) >= 0L)
				/* cannot have duplicate names */
				mvaddstr(19, 0, "Name already in use.");
			else
				/* name is acceptable */
				break;

		addstr("  Pick another.\n");
	}

	/* get a password for character */
	Echo = FALSE;

	do {
		mvaddstr(20, 0, "Give your character a password [up to 8 characters] ? ");
		getstring(Player.p_password, SZ_PASSWORD);
		mvaddstr(21, 0, "One more time to verify ? ");
		getstring(Databuf, SZ_PASSWORD);
	}
	while (strcmp(Player.p_password, Databuf) != 0);

	Echo = TRUE;

	return (allocrecord());
}
Example #3
0
/*
 * This ist the Entry Function of this Mex-DLL
 */
void mexFunction(int nlhs, mxArray*plhs[], int nrhs, const mxArray*prhs[])
{
    mexAtExit(CloseDBs);
    
    /*
     * Get the current Language
     */
    if (Language == -1)
    {
#ifdef _WIN32        
        switch(PRIMARYLANGID(GetUserDefaultLangID()))
        {
            case LANG_GERMAN:
                Language = 1;
                break;
                
            default:
                Language = 0;
        }
#else
        Language = 0;
#endif
    }
    
	/*
	 * Print Version Information
	 */
	if (! FirstStart)
    {
    	FirstStart = true;

        mexPrintf (MSG_HELLO, sqlite3_libversion());
    }
    
    int db_id = 0;
    int CommandPos = 0;
    int NumArgs = nrhs;
    int i;
    
    /*
     * Check if the first argument is a number, then we have to use
	 * this number as an database id.
     */
    if (nrhs >= 1 && mxIsNumeric(prhs[0]))
    {
        db_id = getinteger(prhs[0]);
        if (db_id < 0 || db_id > MaxNumOfDbs)
        {
            mexPrintf(MSG_INVALIDDBHANDLE);
            mexErrMsgTxt(MSG_IMPOSSIBLE);
        }
        db_id --;
        CommandPos ++;
        NumArgs --;
    }

    /*
     * no argument -> fail
     */
    if (NumArgs < 1)
    {
        mexPrintf(MSG_USAGE);
        mexErrMsgTxt(MSG_INVALIDARG);
    }
    
    /*
     * The next (or first if no db number available) is the command,
     * it has to be a string.
     * This fails also, if the first arg is a db-id and there is no 
     * further argument
     */
    if (! mxIsChar(prhs[CommandPos]))
    {
        mexPrintf(MSG_USAGE);
        mexErrMsgTxt(MSG_INVALIDARG);
    }
    
	/*
	 * Get the command string
	 */
    char *command = getstring(prhs[CommandPos]);
    
    /*
     * Adjust the Argument pointer and counter
     */
    int FirstArg = CommandPos +1;
    NumArgs --;
    
    if (! strcmp(command, "open"))
    {
		/*
		 * open a database. There has to be one string argument,
		 * the database filename
		 */
        if (NumArgs != 1 || !mxIsChar(prhs[FirstArg]))
        {
            mexPrintf(MSG_NOOPENARG, mexFunctionName());
			mxFree(command);
            mexErrMsgTxt(MSG_INVALIDARG);
        }
        
		// TODO: possible Memoryleak 'command not freed' when getstring fails
        char* dbname = getstring(prhs[FirstArg]);

		/*
		 * Is there an database ID? The close the database with the same id 
		 */
        if (db_id > 0 && g_dbs[db_id])
        {
            sqlite3_close(g_dbs[db_id]);
            g_dbs[db_id] = 0;
        }

		/*
		 * If there isn't an database id, then try to get one
		 */
        if (db_id < 0)
        {
            for (i = 0; i < MaxNumOfDbs; i++)
            {
                if (g_dbs[i] == 0)
                {
                    db_id = i;
                    break;
                }
            }
        }
		/*
		 * no database id? sorry, database id table full
		 */
        if (db_id < 0)
        {
            plhs[0] = mxCreateDoubleScalar((double) 0);
            mexPrintf(MSG_NOFREESLOT);
			mxFree(command);
        	mxFree(dbname);
            mexErrMsgTxt(MSG_IMPOSSIBLE);
        }
       
		/*
		 * Open the database
		 */
        int rc = sqlite3_open(dbname, &g_dbs[db_id]);
        
        if (rc)
        {
			/*
			 * Anything wrong? free the database id and inform the user
			 */
            mexPrintf(MSG_CANTOPEN, sqlite3_errmsg(g_dbs[db_id]));
            sqlite3_close(g_dbs[db_id]);

            g_dbs[db_id] = 0;
            plhs[0] = mxCreateDoubleScalar((double) 0);
            
			mxFree(command);
	        mxFree(dbname);
            mexErrMsgTxt(MSG_IMPOSSIBLE);
        }
        
        /*
         * Set Default Busytimeout
         */
        rc = sqlite3_busy_timeout(g_dbs[db_id], DEFAULT_BUSYTIMEOUT);
        if (rc)
        {
			/*
			 * Anything wrong? free the database id and inform the user
			 */
            mexPrintf(MSG_CANTOPEN, sqlite3_errmsg(g_dbs[db_id]));
            sqlite3_close(g_dbs[db_id]);

            g_dbs[db_id] = 0;
            plhs[0] = mxCreateDoubleScalar((double) 0);
            
			mxFree(command);
	        mxFree(dbname);
            mexErrMsgTxt(MSG_BUSYTIMEOUTFAIL);
        }
        
		/*
		 * return value will be the used database id
		 */
        plhs[0] = mxCreateDoubleScalar((double) db_id +1);
        mxFree(dbname);
    }
    else if (! strcmp(command, "close"))
    {
		/*
		 * close a database
		 */

        /*
         * There should be no Argument to close
         */
        if (NumArgs > 0)
        {
			mxFree(command);
            mexErrMsgTxt(MSG_INVALIDARG);
        }
        
		/*
		 * if the database id is < 0 than close all open databases
		 */
        if (db_id < 0)
        {
            for (i = 0; i < MaxNumOfDbs; i++)
            {
                if (g_dbs[i])
                {
                    sqlite3_close(g_dbs[i]);
                    g_dbs[i] = 0;
                }
            }
        }
        else
        {
			/*
			 * If the database is open, then close it. Otherwise
			 * inform the user
			 */
            if (! g_dbs[db_id])
            {
				mxFree(command);
                mexErrMsgTxt(MSG_DBNOTOPEN);
            }
            else
            {
                sqlite3_close(g_dbs[db_id]);
                g_dbs[db_id] = 0;
            }
        }
    }
    else if (! strcmp(command, "status"))
    {
        /*
         * There should be no Argument to status
         */
        if (NumArgs > 0)
        {
			mxFree(command);
            mexErrMsgTxt(MSG_INVALIDARG);
        }
        
    	for (i = 0; i < MaxNumOfDbs; i++)
        {
            mexPrintf("DB Handle %d: %s\n", i, g_dbs[i] ? "OPEN" : "CLOSED");
        }
    }
    else if (! _strcmpi(command, "setbusytimeout"))
    {
        /*
         * There should be one Argument, the Timeout in ms
         */
        if (NumArgs != 1 || !mxIsNumeric(prhs[FirstArg]))
        {
			mxFree(command);
            mexErrMsgTxt(MSG_INVALIDARG);
        }

        if (! g_dbs[db_id])
        {
            mxFree(command);
            mexErrMsgTxt(MSG_DBNOTOPEN);
        }
        else
        {
            /*
             * Set Busytimeout
             */
            int TimeoutValue = getinteger(prhs[FirstArg]);
    
            int rc = sqlite3_busy_timeout(g_dbs[db_id], TimeoutValue);
            if (rc)
            {
                /*
                 * Anything wrong? free the database id and inform the user
                 */
                mexPrintf(MSG_CANTOPEN, sqlite3_errmsg(g_dbs[db_id]));
                sqlite3_close(g_dbs[db_id]);

                g_dbs[db_id] = 0;
                plhs[0] = mxCreateDoubleScalar((double) 0);

                mxFree(command);
                mexErrMsgTxt(MSG_BUSYTIMEOUTFAIL);
            }
        }
    }
    else
    {
		/*
		 * database id < 0? Thats an error...
		 */
        if (db_id < 0)
        {
            mexPrintf(MSG_INVALIDDBHANDLE);
			mxFree(command);
            mexErrMsgTxt(MSG_IMPOSSIBLE);
        }
        
		/*
		 * database not open? -> error
		 */
        if (!g_dbs[db_id])
        {
			mxFree(command);
            mexErrMsgTxt(MSG_DBNOTOPEN);
        }
        
		/*
		 * Every unknown command is treated as an sql query string
		 */
		const char* query = command;

        /*
         * a query shuld have no arguments
         */
        if (NumArgs > 0)
        {
			mxFree(command);
            mexErrMsgTxt(MSG_INVALIDARG);
        }
        
		/*
		 * emulate the "show tables" sql query
		 */
        if (! _strcmpi(query, "show tables"))
        {
            query = "SELECT name as tablename FROM sqlite_master "
                    "WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%' "
                    "UNION ALL "
                    "SELECT name as tablename FROM sqlite_temp_master "
                    "WHERE type IN ('table','view') "
                    "ORDER BY 1";
        }

		/*
		 * complete the query
		 */
        if (sqlite3_complete(query))
        {
			mxFree(command);
            mexErrMsgTxt(MSG_INVQUERY);
        }
        
        sqlite3_stmt *st;
        
		/*
		 * and prepare it
		 * if anything is wrong with the query, than complain about it.
		 */
        if (sqlite3_prepare_v2(g_dbs[db_id], query, -1, &st, 0))
        {
            if (st)
                sqlite3_finalize(st);
            
			mxFree(command);
            mexErrMsgIdAndTxt(TransErrToIdent(g_dbs[db_id]), sqlite3_errmsg(g_dbs[db_id]));
        }

		/*
		 * Any results?
		 */
        int ncol = sqlite3_column_count(st);
        if (ncol > 0)
        {
            char **fieldnames = new char *[ncol];   /* Column names */
            Values* allrows = 0;                    /* All query results */
            Values* lastrow = 0;					/* pointer to the last result row */
            int rowcount = 0;						/* number of result rows */
            
			/*
			 * Get the column names of the result set
			 */
            for(i=0; i<ncol; i++)
            {
                const char *cname = sqlite3_column_name(st, i);
                
                fieldnames[i] = new char [strlen(cname) +1];
                strcpy (fieldnames[i], cname);
				/*
				 * replace invalid chars by '_', so we can build
				 * valid MATLAB structs
				 */
                char *mk_c = fieldnames[i];
                while (*mk_c)
                {
                	if ((*mk_c == ' ') || (*mk_c == '*') || (*mk_c == '?'))
                    	*mk_c = '_';
                    mk_c++;
                }
            }
            
            /*
			 * get the result rows from the engine
			 *
			 * We cannot get the number of result lines, so we must
			 * read them in a loop and save them into an temporary list.
			 * Later, we can transfer this List into an MATLAB array of structs.
			 * This way, we must allocate enough memory for two result sets,
			 * but we save time by allocating the MATLAB Array at once.
			 */
            for(;;)
            {
				/*
				 * Advance to teh next row
				 */
                int step_res = sqlite3_step(st);

				/*
				 * no row left? break out of the loop
				 */
                if (step_res != SQLITE_ROW)
                    break;

				/*
				 * get new memory for the result
				 */
                Values* RecordValues = new Values(ncol);
                
                Value *v = RecordValues->m_Values;
                for (int j = 0; j < ncol; j++, v++)
                {
                     int fieldtype = sqlite3_column_type(st,j);

                     v->m_Type = fieldtype;
                     v->m_Size = 0;
                     
                     switch (fieldtype)
                     {
                         case SQLITE_NULL:      v->m_NumericValue = g_NaN;                                   break;
                         case SQLITE_INTEGER:	v->m_NumericValue = (double) sqlite3_column_int(st, j);      break;
                         case SQLITE_FLOAT:     v->m_NumericValue = (double) sqlite3_column_double(st, j);	 break;
                         case SQLITE_TEXT:      v->m_StringValue  = strnewdup((const char*) sqlite3_column_text(st, j));   break;
                         case SQLITE_BLOB:      
                            {
                                v->m_Size = sqlite3_column_bytes(st,j);
                                if (v->m_Size > 0)
                                {
                                    v->m_StringValue = new char[v->m_Size];
                                    memcpy(v->m_StringValue, sqlite3_column_blob(st,j), v->m_Size);
                                }
                                else
                                {
                                    v->m_Size = 0;
                                }
                            }
                            break;
                         default:	
							mxFree(command);
							mexErrMsgTxt(MSG_UNKNWNDBTYPE);
                     }
                }
				/*
				 * and add this row to the list of all result rows
				 */
                if (! lastrow)
                {
                    allrows = lastrow = RecordValues;
                }
                else
                {
                    lastrow->m_NextValues = RecordValues;
                    lastrow = lastrow->m_NextValues;
                }
				/*
				 * we have one more...
				 */
                rowcount ++;
            }
            
			/*
			 * end the sql engine
			 */
            sqlite3_finalize(st);

			/*
			 * got nothing? return an empty result to MATLAB
			 */
            if (rowcount == 0 || ! allrows)
            {
                if (!( plhs[0] = mxCreateDoubleMatrix(0,0,mxREAL) ))
				{
					mxFree(command);
                    mexErrMsgTxt(MSG_CANTCREATEOUTPUT);
				}
            }
            else
            {
				/*
				 * Allocate an array of MATLAB structs to return as result
				 */
                int ndims[2];
                
                ndims[0] = rowcount;
                ndims[1] = 1;
                
                if (( plhs[0] = mxCreateStructArray (2, ndims, ncol, (const char**)fieldnames)) == 0)
                {
					mxFree(command);
                    mexErrMsgTxt(MSG_CANTCREATEOUTPUT);
                }
                
				/*
				 * transfer the result rows from the temporary list into the result array
				 */
                lastrow = allrows;
                i = 0;
                while(lastrow)
                {
                    Value* recordvalue = lastrow->m_Values;
                    
                    for (int j = 0; j < ncol; j++, recordvalue++)
                    {
                        if (recordvalue -> m_Type == SQLITE_TEXT)
                        {
                            mxArray* c = mxCreateString(recordvalue->m_StringValue);
                            mxSetFieldByNumber(plhs[0], i, j, c);
                        }
                        else if (recordvalue -> m_Type == SQLITE_NULL && !NULLasNaN)
                        {
                            mxArray* out_double = mxCreateDoubleMatrix(0,0,mxREAL);
                            mxSetFieldByNumber(plhs[0], i, j, out_double);
                        }
                        else if (recordvalue -> m_Type == SQLITE_BLOB)
                        {
                            if (recordvalue->m_Size > 0)
                            {
                                int BytePos;
                                int NumDims[2]={1,1};
                                NumDims[1]=recordvalue->m_Size;
                                mxArray*out_uchar8=mxCreateNumericArray(2, NumDims, mxUINT8_CLASS, mxREAL);
                                unsigned char *v = (unsigned char *) mxGetData(out_uchar8);
                                
                                memcpy(v, recordvalue->m_StringValue, recordvalue->m_Size);
                                    
                                mxSetFieldByNumber(plhs[0], i, j, out_uchar8);
                            }
                            else
                            {
                                // empty BLOB
                                mxArray* out_double = mxCreateDoubleMatrix(0,0,mxREAL);
                                mxSetFieldByNumber(plhs[0], i, j, out_double);
                            }
                        }
                        else
                        {
                            mxArray* out_double = mxCreateDoubleScalar(recordvalue->m_NumericValue);
                            mxSetFieldByNumber(plhs[0], i, j, out_double);
                        }
                    }
                    allrows = lastrow;
                    lastrow = lastrow->m_NextValues;
                    delete allrows;
                    i++;
                }
            }
            for(int i=0; i<ncol; i++)
                delete [] fieldnames[i];
            delete [] fieldnames;
        }
        else
        {
			/*
			 * no result, cleanup the sqlite engine
			 */
            int res = sqlite3_step(st);
            sqlite3_finalize(st);

			if (!( plhs[0] = mxCreateDoubleMatrix(0, 0, mxREAL) )) 
			{
                mexErrMsgTxt(MSG_CANTCREATEOUTPUT);
            }

            if (res != SQLITE_DONE)
            {
				mxFree(command);
                mexErrMsgIdAndTxt(TransErrToIdent(g_dbs[db_id]), sqlite3_errmsg(g_dbs[db_id]));
            }            
        }
    }
	mxFree(command);
}
Example #4
0
int upload(void) {	/* Ändrad för nikfiles.data 960707 JÖ */
    int area,ret,editret,dirnr;
    long tid;
    struct EditLine *el;
    FILE *fp;
    __aligned struct FileInfoBlock info;
    struct Fil *allokpek;
    char nikfilename[100],errbuff[100],filnamn[50],tmpfullname[100], outbuffer[81];
    UBYTE tn;
    struct TransferFiles *tf;

    if(Servermem->cfg.ar.preup1) sendautorexx(Servermem->cfg.ar.preup1);
    if(area2==-1) {
        puttekn("\r\nI vilken area? ",-1);
    } else {
        sprintf(outbuffer,"\r\nI vilken area? (<RETURN> för %s)",Servermem->areor[area2].namn);
        puttekn(outbuffer,-1);
    }
    if(getstring(EKO,40,NULL)) return(1);
    if((area=parsearea(inmat))==-1) {
        puttekn("\n\rFinns ingen sådan area!\n\r",-1);
        return(0);
    } else if(area==-3) {
        if(area2==-1) return(0);
        area=area2;
    }
    if(!arearatt(area, inloggad, &Servermem->inne[nodnr])) {
        puttekn("\n\rFinns ingen sådan area!\n\r",-1);
        return(0);
    }
    if((Servermem->areor[area].flaggor & AREA_NOUPLOAD) && (Servermem->inne[nodnr].status < Servermem->cfg.st.laddaner)) {
        puttekn("\n\n\rDu har ingen rätt att ladda upp till den arean!\n\r",-1);
        return(0);
    }
    Servermem->action[nodnr] = UPLOAD;
    Servermem->varmote[nodnr] = area;
    Servermem->vilkastr[nodnr] = NULL;
    if(ret=recbinfile(Servermem->cfg.ultmp)) {
        while(tf=(struct TransferFiles *)RemHead((struct List *)&tf_list))
            FreeMem(tf,sizeof(struct TransferFiles));
        if(carrierdropped()) return(1);
        return(0);
    }

    /* printf("Filnamn = %s\n",FilePart(tf->Filnamn));
    printf("Cps = %d\n\n",tf->cps); */

    for(tf=(struct TransferFiles *)tf_list.mlh_Head; tf->node.mln_Succ; tf=(struct TransferFiles *)tf->node.mln_Succ) {
        strcpy(xprfilnamn,tf->Filnamn);
        if(stcgfn(filnamn,xprfilnamn)>40) puttekn("\r\nVARNING! Filnamnet större än 40 tecken!\r\n",-1);
        if(!filnamn[0]) {
            puttekn("\r\n\nHmm... Filen har inget namn. Skriv ett brev till sysop.\r\n",-1);
            continue;
        }
        if(!valnamn(filnamn,area,errbuff)) {
            for(;;) {
                puttekn(errbuff,-1);
                puttekn("\r\nNytt namn: ",-1);
                if(getstring(EKO,40,NULL)) {
                    DeleteFile(xprfilnamn);
                    return(1);
                }
                if(!inmat[0]) continue;
                if(valnamn(inmat,area,errbuff)) break;
            }
            strcpy(filnamn,inmat);
            sprintf(tmpfullname,"%s%s",Servermem->cfg.ultmp,filnamn);
            if(!Rename(xprfilnamn,tmpfullname)) {
                sprintf(outbuffer,"\r\n\nKunde inte döpa om filen från '%s'\r\ntill '%s'.\r\n",xprfilnamn,tmpfullname);
                puttekn(outbuffer,-1);
                DeleteFile(xprfilnamn);
                continue;
            }
        } else strcpy(tmpfullname,xprfilnamn);
        if(!(allokpek=(struct Fil *)AllocMem(sizeof(struct Fil),MEMF_PUBLIC | MEMF_CLEAR))) {
            puttekn("\r\n\nKunde inte allokera minne för filen!\r\n",-1);
            continue;
        }
        time(&tid);
        allokpek->tid=allokpek->validtime=tid;
        allokpek->uppladdare=inloggad;
        if(dfind(&info,tmpfullname,0)) {
            sprintf(outbuffer,"\r\nHittar inte filen %s!\r\n",tmpfullname);
            puttekn(outbuffer,-1);
            FreeMem(allokpek,sizeof(struct Fil));
            continue;
        }
        allokpek->size=info.fib_Size;

        sprintf(outbuffer,"\r\n\r\nFilnamn: %s", filnamn);
        puttekn(outbuffer,-1);
        puttekn("\r\nVilken status ska behövas för att ladda ner filen? (0)",-1);
        if(getstring(EKO,3,NULL)) {
            FreeMem(allokpek,sizeof(struct Fil));
            return(1);
        }
        allokpek->status=atoi(inmat);
        if(Servermem->inne[nodnr].status >= Servermem->cfg.st.filer) {
            puttekn("\n\rSka filen valideras? ",-1);
            if(jaellernej('j','n',1)) puttekn("Ja",-1);
            else {
                puttekn("Nej",-1);
                allokpek->flaggor|=FILE_NOTVALID;
            }
            puttekn("\n\rSka filen ha fri download? ",-1);
            if(jaellernej('j','n',2)) {
                puttekn("Ja",-1);
                allokpek->flaggor|=FILE_FREEDL;
            } else puttekn("Nej",-1);
        } else if(Servermem->cfg.cfgflags & NICFG_VALIDATEFILES) allokpek->flaggor|=FILE_NOTVALID;
        sendfile("NiKom:Texter/Nyckelhjälp.txt");
        puttekn("\r\nVilka söknycklar ska filen ha? (? för att få en lista)\r\n",-1);
        if(editkey(allokpek->nycklar)) {
            FreeMem(allokpek,sizeof(struct Fil));
            return(1);
        }
        puttekn("\r\nBeskrivning:\r\n",-1);
        if(getstring(EKO,70,NULL)) {
            FreeMem(allokpek,sizeof(struct Fil));
            return(1);
        }
        strcpy(allokpek->beskr,inmat);
        dirnr = ChooseDirectoryInFileArea(
                    area, allokpek->nycklar, allokpek->size);
        if(dirnr==-1) {
            puttekn("\r\n\nKunde inte hitta något lämpligt directory för filen!\r\n",-1);
            DeleteFile(tmpfullname);
            FreeMem(allokpek,sizeof(struct Fil));
            continue;
        }
        allokpek->dir=dirnr;
        strcpy(allokpek->namn,filnamn);
        sprintf(inmat,"%s %s",tmpfullname,Servermem->areor[area].dir[dirnr]);
        argument=inmat;
        sendrexx(10);
        AddTail((struct List *)&Servermem->areor[area].ar_list,(struct Node *)allokpek);
        if(writefiles(area)) {
            puttekn("\r\n\nKunde inte skriva till datafilen\r\n",-1);

        }

        Servermem->inne[nodnr].upload++;
        Statstr.ul++;
        if(Servermem->cfg.logmask & LOG_UPLOAD) {
            LogEvent(USAGE_LOG, INFO, "%s laddar upp %s",
                     getusername(inloggad), allokpek->namn);
        }
        if(Servermem->cfg.ar.postup1) sendautorexx(Servermem->cfg.ar.postup1);
        puttekn("\r\n\nVill du skriva en längre beskrivning? (J/n) ",-1);
        while((tn=gettekn())!='j' && tn!='J' && tn!='n' && tn!='N' && tn!=13);
        if(tn=='j' || tn=='J') {
            puttekn("\r\n\nOk, går in i editorn.\r\n",-1);
            if((editret=edittext(NULL))==1) return(1);
            else if(editret==2) continue;
            sprintf(nikfilename,"%slongdesc/%s.long",Servermem->areor[area].dir[dirnr],filnamn);
            if(!(fp=fopen(nikfilename,"w"))) {
                puttekn("\r\n\nKunde inte öppna longdesc-filen\r\n",-1);
                freeeditlist();
                continue;
            }
            for(el=(struct EditLine *)edit_list.mlh_Head; el->line_node.mln_Succ; el=(struct EditLine *)el->line_node.mln_Succ) {
                if(fputs(el->text,fp)) {
                    freeeditlist();
                    fclose(fp);
                    continue;
                }
                fputc('\n',fp);
            }
            freeeditlist();
            fclose(fp);
            puttekn("\r\n",-1);
            allokpek->flaggor|=FILE_LONGDESC;
            updatefile(area,allokpek);
        }
    }

    while(tf=(struct TransferFiles *)RemHead((struct List *)&tf_list))
        FreeMem(tf,sizeof(struct TransferFiles));

    return(0);
}
Example #5
0
/*
 * format: trade
 */
int
trad(void)
{
    struct sctstr sect;
    struct natstr *natp;
    struct comstr comt;
    int lotno;
    float price;
    coord sx, sy;
    int n;
    char *p;
    struct nstr_item ni;
    struct trdstr trade;
    struct trdstr tmpt;
    union empobj_storage tg;
    double canspend;
    time_t now, tleft;
    int bid;
    double tally;
    int i;
    char buf[1024];

    if (!opt_MARKET) {
	pr("The market is disabled.\n");
	return RET_FAIL;
    }
    /* First, we execute all trades, so that we can only buy what is available. */
    check_market();
    check_trade();

    pr("\n     Empire Trade Report\n  ");
    prdate();
    n = 0;
    pr(" lot high bid  by time left owner  description\n");
    pr(" --- --------  -- --------- -----  -------------------------\n");

    snxtitem_all(&ni, EF_TRADE);
    while (nxtitem(&ni, &trade)) {
	if (trade.trd_owner == 0)
	    continue;
	if (!trade_getitem(&trade, &tg)) {
	    continue;
	}
	pr(" %3d ", ni.cur);
	(void)time(&now);
	tleft = trade.trd_markettime + TRADE_DELAY - now;
	if (tleft < 0)
	    tleft = 0;
	pr("$%7d  %2d %5.2f hrs ",
	   trade.trd_price, trade.trd_maxbidder, tleft / 3600.0);
	trade_desc(&tg.gen);	/* XXX */
	pr("\n");
	if (trade.trd_owner == player->cnum && !player->god)
	    pr(" (your own lot)\n");
	n++;
    }
    if (n == 0) {
	pr("Nothing to buy at the moment...\n");
	return RET_OK;
    }
    p = getstring("Which lot to buy: ", buf);
    if (!p || !*p)
	return RET_OK;
    if (isdigit(*p) == 0)
	return RET_OK;
    lotno = atoi(p);
    if (lotno < 0 || lotno >= ni.cur) {
	pr("Bad lot number\n");
	return RET_OK;
    }
    if (!gettrade(lotno, &trade)) {
	pr("No such lot number\n");
	return RET_OK;
    }
    if (trade.trd_unitid < 0) {
	pr("Invalid lot number.\n");
	return RET_OK;
    }
    if (!trade_getitem(&trade, &tg)) {
	pr("Can't find trade #%d!\n", trade.trd_unitid);
	trade.trd_owner = 0;
	trade.trd_unitid = -1;
	if (!puttrade(lotno, &trade)) {
	    logerror("trad: can't write trade");
	    pr("Couldn't save after getitem failed; get help!\n");
	    return RET_FAIL;
	}
	return RET_OK;
    }
    switch (trade.trd_type) {
    case EF_NUKE:
    case EF_PLANE:
    case EF_SHIP:
    case EF_LAND:
	break;
    default:
	pr("Bad unit type on lot number %d\n", lotno);
	return RET_FAIL;
    }
    if (trade.trd_owner == player->cnum) {
	pr("You can't buy from yourself!\n");
	return RET_OK;
    }
    price = trade.trd_price;
    natp = getnatp(player->cnum);
    if (natp->nat_money < price) {
	pr("You don't have %.2f to spend!\n", price);
	return RET_OK;
    }
    tally = 0.0;
    for (i = 0; gettrade(i, &tmpt); i++) {
	if (tmpt.trd_maxbidder == player->cnum &&
	    tmpt.trd_unitid >= 0 && tmpt.trd_owner != player->cnum) {
	    tally += tmpt.trd_price * tradetax;
	}
    }
    for (i = 0; getcomm(i, &comt); i++) {
	if (comt.com_maxbidder == player->cnum &&
	    comt.com_owner != 0 && comt.com_owner != player->cnum) {
	    tally += (comt.com_price * comt.com_amount) * buytax;
	}
    }
    canspend = natp->nat_money - tally;

    /* Find the destination sector for the trade */
    if (((trade.trd_type == EF_PLANE) && !pln_is_in_orbit(&tg.plane))
	|| (trade.trd_type == EF_NUKE)) {
	while (1) {
	    p = getstring("Destination sector: ", buf);
	    if (!p)
		return RET_FAIL;
	    if (!trade_check_ok(&trade, &tg.gen))
		return RET_FAIL;
	    if (!sarg_xy(p, &sx, &sy) || !getsect(sx, sy, &sect)) {
		pr("Bad sector designation; try again!\n");
		continue;
	    }
	    if (!player->owner) {
		pr("You don't own that sector; try again!\n");
		continue;
	    }
	    if (!(plchr[tg.plane.pln_type].pl_flags & P_V)) {
		if (!player->god && (sect.sct_type != SCT_AIRPT)) {
		    pr("Destination sector is not an airfield!\n");
		    continue;
		}
		if (!player->god && (sect.sct_effic < 60)) {
		    pr("That airport still under construction!\n");
		    continue;
		}
	    }
	    break;
	}
    } else if (trade.trd_type == EF_LAND) {
	while (1) {
	    p = getstring("Destination sector: ", buf);
	    if (!p)
		return RET_FAIL;
	    if (!trade_check_ok(&trade, &tg.gen))
		return RET_FAIL;
	    if (!sarg_xy(p, &sx, &sy) || !getsect(sx, sy, &sect)) {
		pr("Bad sector designation; try again!\n");
		continue;
	    }
	    if (!player->owner) {
		pr("You don't own that sector; try again!\n");
		continue;
	    }
	    if (!player->god && (sect.sct_type != SCT_HEADQ)) {
		pr("Destination sector is not a headquarters!\n");
		continue;
	    }
	    if (!player->god && (sect.sct_effic < 60)) {
		pr("That headquarters still under construction!\n");
		continue;
	    }
	    break;
	}
    } else {
	/* This trade doesn't teleport; make destination invalid */
	sx = 1;
	sy = 0;
    }

    p = getstring("How much do you bid: ", buf);
    if (!p || !*p)
	return RET_OK;
    if (!trade_check_ok(&trade, &tg.gen))
	return RET_FAIL;
    bid = atoi(p);
    if (bid < price)
	bid = price;
    if (bid > canspend) {
	pr("You don't have %.2f to spend!\n", price);
	return RET_OK;
    }
    if (bid > trade.trd_price) {
	time(&now);
	if (trade.trd_markettime  + TRADE_DELAY - now < minutes(5) &&
	    trade.trd_maxbidder != player->cnum)
	    trade.trd_markettime = now + minutes(5) - TRADE_DELAY;
	trade.trd_price = bid;
	trade.trd_maxbidder = player->cnum;
	trade.trd_x = sx;
	trade.trd_y = sy;
	pr("Your bid on lot #%d is being considered.\n", lotno);
	if (!puttrade(lotno, &trade))
	    pr("Problems with the trade file.  Get help\n");
    } else
	pr("Your bid wasn't high enough (you need to bid more than someone else.)\n");

    check_trade();

    return RET_OK;
}
Example #6
0
static int do_chanstats(User * u, int ac, char **av)
{
    char *cmd1 = NULL;
    char *cmd2 = NULL;
    char *cmd3 = NULL;
    char *cmd4 = NULL;
    lnode_t *tn;

    ChannelStats *cs;
    Channel *c;
    int i;
    int x = 0;
    char *sqlchan;
    Uid *ud;

    char *modes;
    char nickbuf[BUFSIZE];
    *nickbuf = '\0';

    if (ac >= 1) {
        cmd1 = av[0];
    }
    if (ac >= 2) {
        cmd2 = av[1];
    }
    if (ac >= 3) {
        cmd3 = av[2];
    }
    if (ac >= 4) {
        cmd4 = av[3];
    }

    if (cmd1) {
        /* Since ChanStats does require SQL code... */
        if (!denora->do_sql) {
            notice_lang(s_StatServ, u, SQL_DISABLED);
            return MOD_CONT;
        }

        if (!stricmp("ADD", cmd1)) {
            if (LargeNet) {
                notice_lang(s_StatServ, u, STAT_CHANSTATS_CHAN_LARGENET);
                return MOD_CONT;
            }
            if (!cmd2) {
                syntax_error(s_StatServ, u, "CHANSTATS",
                             STAT_CHANSTATS_ADD_SYNTAX);
                return MOD_CONT;
            }
            if (BadChanName(cmd2)) {
                notice_lang(s_StatServ, u, STAT_CHANSTATS_NOT_VALID_CHAN);
                return MOD_CONT;
            }
            if (strlen(cmd2) > CHANMAX) {
                notice_lang(s_StatServ, u, STAT_CHANSTATS_NOT_VALID_CHAN);
                return MOD_CONT;
            }
            if (LogChannel) {
                if (!stricmp(cmd2, LogChannel)) {
                    notice_lang(s_StatServ, u, STAT_CHANSTATS_LOGCHAN);
                    return MOD_CONT;
                }
            }
            if (!(cs = find_cs(cmd2))) {
                cs = makecs(cmd2);
                save_cs_db();
                sqlchan = rdb_escape(cmd2);
                if (CSDefFlag) {
                    if (CSDefFlag == 1) {
                        cs->flags |= CS_FANTASY;
                        cs->flags &= ~CS_NOTICE;
                    } else if (CSDefFlag == 2) {
                        cs->flags |= CS_FANTASY;
                        cs->flags |= CS_NOTICE;
                    }
                }

                rdb_query(QUERY_LOW, "DELETE FROM %s WHERE chan=\'%s\'",
                          CStatsTable, sqlchan);
                rdb_query(QUERY_LOW, "DELETE FROM %s WHERE chan=\'%s\'",
                          UStatsTable, sqlchan);
                cs->timeadded = time(NULL);
                for (i = 0; i < 4; i++) {
                    rdb_query
                        (QUERY_LOW,
                         "INSERT INTO %s SET chan=\'%s\', type=%i, timeadded=%ld;",
                         CStatsTable, sqlchan, i, cs->timeadded);
                }
                notice_lang(s_StatServ, u, STAT_CHANSTATS_CHAN_ADDED,
                            cmd2);

                ud = find_uid(s_StatServ);
                if (PartOnEmpty) {
                    c = findchan(cmd2);
                    if (c) {
                        denora_cmd_join(s_StatServ, cs->name, time(NULL));
                        if (AutoOp && AutoMode) {
                            modes = sstrdup(AutoMode);
                            while (*modes) {
                                switch (*modes) {
                                case '+':
                                    break;
                                case '-':
                                    break;
                                default:
                                    ircsnprintf(nickbuf, BUFSIZE, "%s %s",
                                                nickbuf,
                                                ((ircd->p10
                                                  && ud) ? ud->uid :
                                                 s_StatServ));
                                }
                                (void) *modes++;
                            }
                            denora_cmd_mode(ServerName, cs->name, "%s%s",
                                            AutoMode, nickbuf);
                        }
                    }
                } else {
                    denora_cmd_join(s_StatServ, cs->name, time(NULL));
                    if (AutoOp && AutoMode) {
                        modes = sstrdup(AutoMode);
                        while (*modes) {
                            switch (*modes) {
                            case '+':
                                break;
                            case '-':
                                break;
                            default:
                                ircsnprintf(nickbuf, BUFSIZE, "%s %s",
                                            nickbuf,
                                            ((ircd->p10
                                              && ud) ? ud->uid :
                                             s_StatServ));
                            }
                            (void) *modes++;
                        }
                        denora_cmd_mode(ServerName, cs->name, "%s%s",
                                        AutoMode, nickbuf);
                    }
                }
                free(sqlchan);
            } else {
                notice_lang(s_StatServ, u, STAT_CHANSTATS_CHAN_ALREADY,
                            cmd2);
            }
        } else if (!stricmp("DEL", cmd1)) {
            if (!cmd2) {
                syntax_error(s_StatServ, u, "CHANSTATS",
                             STAT_CHANSTATS_DEL_SYNTAX);
                return MOD_CONT;
            }
            sqlchan = rdb_escape(cmd2);
            if ((cs = find_cs(cmd2))) {
                del_cs(cs);
                save_cs_db();
                rdb_query(QUERY_LOW, "DELETE FROM %s WHERE chan=\'%s\'",
                          CStatsTable, sqlchan);
                rdb_query(QUERY_LOW, "DELETE FROM %s WHERE chan=\'%s\'",
                          UStatsTable, sqlchan);
                notice_lang(s_StatServ, u, STAT_CHANSTATS_CHAN_DEL, cmd2);
                if (LogChannel) {
                    if (stricmp(LogChannel, cmd2)) {
                        denora_cmd_part(s_StatServ, cmd2,
                                        getstring(NULL,
                                                  STATS_CHANSTATS_PART),
                                        cmd2);
                    }
                } else {
                    denora_cmd_part(s_StatServ, cmd2,
                                    getstring(NULL, STATS_CHANSTATS_PART),
                                    cmd2);
                }
            } else {
                notice_lang(s_StatServ, u, STAT_CHANSTATS_CHAN_NOTFOUND,
                            cmd2);
            }
            free(sqlchan);
        } else if (!stricmp("LIST", cmd1)) {
            tn = list_first(CStatshead);
            while (tn != NULL) {
                cs = lnode_get(tn);
                notice(s_StatServ, u->nick, "%d %s", x, cs->name);
                x++;
                tn = list_next(CStatshead, tn);
            }
            if (!x) {
                notice_lang(s_StatServ, u, STATS_CHANSTATS_NOCHANNELS);
            }
        } else if (!stricmp("SUMUSER", cmd1)) {
            if (!cmd3) {
                syntax_error(s_StatServ, u, "CHANSTATS",
                             STATS_CHANSTATS_SUMUSER_SYNTAX);
                return MOD_CONT;
            }
            sumuser(u, cmd2, cmd3);
        } else if (!stricmp("RENAME", cmd1)) {
            if (!cmd3) {
                syntax_error(s_StatServ, u, "CHANSTATS",
                             STATS_CHANSTATS_RENAMEUSER_SYNTAX);
                return MOD_CONT;
            }
            renameuser(u, cmd2, cmd3);
        } else if (!stricmp("SET", cmd1)) {
            if (!cmd3) {
                syntax_error(s_StatServ, u, "CHANSTATS",
                             STATS_CHANSTATS_SET_SYNTAX);
                return MOD_CONT;
            }
            if (!(cs = find_cs(cmd2))) {
                notice_lang(s_StatServ, u, STAT_CHANSTATS_CHAN_NOTFOUND,
                            cmd2);
                return MOD_CONT;
            }
            if (!stricmp("FANTASY", cmd3)) {
                if (!cmd4) {
                    syntax_error(s_StatServ, u, "CHANSTATS",
                                 STATS_CHANSTATS_SET_SYNTAX);
                    return MOD_CONT;
                }
                if (!stricmp("ON", cmd4)) {
                    cs->flags |= CS_FANTASY;
                    cs->flags &= ~CS_NOTICE;
                    notice_lang(s_StatServ, u, STATS_CHANSTATS_FANTASY_ON,
                                cmd2);
                } else if (!stricmp("OFF", cmd4)) {
                    cs->flags &= ~CS_FANTASY;
                    cs->flags &= ~CS_NOTICE;
                    notice_lang(s_StatServ, u, STATS_CHANSTATS_FANTASY_OFF,
                                cmd2);
                } else if (!stricmp("NOTICE", cmd4)) {
                    cs->flags |= CS_FANTASY;
                    cs->flags |= CS_NOTICE;
                    notice_lang(s_StatServ, u,
                                STATS_CHANSTATS_FANTASY_NOTICE, cmd2);
                } else {
                    syntax_error(s_StatServ, u, "CHANSTATS",
                                 STATS_CHANSTATS_SET_SYNTAX);
                }
            }                   /* fantasy */
        } else {
            syntax_error(s_StatServ, u, "CHANSTATS",
                         STAT_CHANSTATS_SYNTAX);
        }
    } else {
        syntax_error(s_StatServ, u, "CHANSTATS", STAT_CHANSTATS_SYNTAX);
    }
    return MOD_CONT;
}
Example #7
0
int dumpatext(void) {
	int tnr,x;
	struct Header dumphead;
	FILE *fpr,*fpd;
	char *dumpfil,foostr[82],filnamn[40];
	if(!isdigit(argument[0])) {
		puttekn("\r\n\nSkriv: Dumpa Text <textnr> [filnamn]\r\n\n",-1);
		return(0);
	}
	tnr=atoi(argument);
	if(tnr<Servermem->info.lowtext || tnr>Servermem->info.hightext) {
		puttekn("\r\n\nTexten finns inte!\r\n",-1);
		return(0);
	}
	if(!MayReadConf(Servermem->texts[tnr%MAXTEXTS], inloggad, &Servermem->inne[nodnr])) {
		puttekn("\r\n\nDu har inte rätt att dumpa den texten!\r\n",-1);
		return(0);
	}
	dumpfil=hittaefter(argument);
	if(!dumpfil[0]) {
		puttekn("\r\n\nTill vilken fil? : ",-1);
		if(getstring(EKO,50,NULL)) return(1);
		if(!inmat[0]) return(0);
		dumpfil=inmat;
	}
	if(readtexthead(tnr,&dumphead)) return(0);
	sprintf(filnamn,"NiKom:Moten/Text%d.dat",dumphead.nummer/512);
	NiKForbid();
	if(!(fpr=fopen(filnamn,"r"))) {
		puttekn("\r\n\nKunde inte öppna Text.dat!\r\n\n",-1);
		NiKPermit();
		return(0);
	}
	if(fseek(fpr,dumphead.textoffset,0)) {
		puttekn("\r\n\nKunde inte söka i Text.dat!\r\n\n",-1);
		fclose(fpr);
		NiKPermit();
		return(0);
	}
	if(!(fpd=fopen(dumpfil,"w"))) {
		sprintf(outbuffer,"\r\n\nKunde inte öppna %s!\r\n",dumpfil);
		puttekn(outbuffer,-1);
		fclose(fpr);
		NiKPermit();
		return(0);
	}
	for(x=0;x<dumphead.rader;x++) {
		if(!(fgets(foostr,81,fpr))) {
			puttekn("\r\n\nFel vid läsandet av Text.dat!\r\n\n",-1);
			break;
		}
		if(fputs(foostr,fpd)) {
			sprintf(outbuffer,"\r\n\nFel vid skrivandet av %s!\r\n",dumpfil);
			puttekn(outbuffer,-1);
			break;
		}
	}
	fclose(fpr);
	fclose(fpd);
	NiKPermit();
	return(0);
}
Example #8
0
size_t memdecode(const void * memory, size_t extent, char const * object, char const * string)

{
	size_t length;
	if (! strcmp(object, "byte"))
	{
		uint8_t number;
		if (sizeof(number) > extent)
		{
			error (1, ECANCELED, "%s exceeds " SIZE_T_SPEC " bytes", object, length);
		}
		memcpy (& number, memory, sizeof(byte));
		printf ("%u", number);
		return (sizeof(number));
	}
	else if(! strcmp(object, "word"))
	{
		uint16_t number;
		if (sizeof(number) > extent)
		{
			error (1, ECANCELED, "%s exceeds " SIZE_T_SPEC " bytes", object, length);
		}
		memcpy (& number, memory, sizeof(number));
		printf ("%u", LE16TOH(number));
		return (sizeof(number));
	}
	else if(! strcmp(object, "long"))
	{
		uint32_t number;
		if (sizeof(number) > extent)
		{
			error (1, ECANCELED, "%s exceeds " SIZE_T_SPEC " bytes", object, length);
		}
		memcpy (& number, memory, sizeof(number));
		printf ("%u", LE32TOH(number));
		return (sizeof(number));
	}
	else if(! strcmp(object, "xbyte"))
	{
		uint8_t number;
		if (sizeof(number) > extent)
		{
			error (1, ECANCELED, "%s exceeds " SIZE_T_SPEC " bytes", object, length);
		}
		memcpy (& number, memory, sizeof(number));
		printf ("0x%02X", number);
		return (sizeof(number));
	}
	else if(! strcmp(object, "xword"))
	{
		uint16_t number;
		if (sizeof(number) > extent)
		{
			error (1, ECANCELED, "%s exceeds " SIZE_T_SPEC " bytes", object, length);
		}
		memcpy (& number, memory, sizeof(number));
		printf ("0x%04X", LE16TOH(number));
		return (sizeof(number));
	}
	else if(! strcmp(object, "xlong"))
	{
		uint32_t number;
		if (sizeof(number) > extent)
		{
			error (1, ECANCELED, "%s exceeds " SIZE_T_SPEC " bytes", object, length);
		}
		memcpy (& number, memory, sizeof(number));
		printf ("0x%08X", LE32TOH(number));
		return (sizeof(number));
	}
	else if(! strcmp(object, "data"))
	{
		char const * size = string;
		if (! size)
		{
			error (1, EINVAL, "%s needs a length", object);
		}
		length = (unsigned) (uintspec(size, 1, extent));
		if (length > extent)
		{
			error (1, ECANCELED, "%s exceeds " SIZE_T_SPEC " bytes", object, length);
		}
		hexout (memory, length, 0, 0, stdout);
		return (length);
	}
	else if(! strcmp(object, "text"))
	{
		char const * size = string;
		if (! size)
		{
			error (1, EINVAL, "%s needs a length", object);
		}
		length = (unsigned) (uintspec(size, 1, extent));
		getstring (memory, extent, object, length);
		return (length);
	}
	else if(! strcmp(object, "skip"))
	{
		char const * size = string;
		if (! size)
		{
			error (1, EINVAL, "%s needs a length", object);
		}
		length = (unsigned) (uintspec(size, 1, extent));
		return (length);
	}
	else if(! strcmp(object, "mac"))
	{
		length = ETHER_ADDR_LEN;
		getmemory (memory, extent, object, length);
		return (length);
	}
	else if(! strcmp(object, "url"))
	{
		length = STRINGSIZE;
		getstring (memory, extent, object, length);
		return (length);
	}
	else 
	{
		error (1, ENOTSUP, "%s", object);
	}
	return (0);
}
Example #9
0
void	RenderPass::AddParam( char* Type, char* Var )
{
	char*	Token;
	if ( stricmp( Type , "tcMod" ) == 0 )
	{
		if ( Var == NULL )
			Error( "token expected after surfaceparam, but none found");

		Token = getstring( Var );
		if ( Var == NULL )
			Error( "unexpected end after token: %s" , Token );
		
		if ( stricmp( Token , "rotate" ) == 0 )
		{
			Token = getstring( Var );
			if ( Var != NULL )
				Error( "%s followed by unexpected token: %s" , Token, Var );

			//TODO: add check if it's really a number
			rp_rotate = (float)atof(Token);
		} else
		if ( stricmp( Token , "scale" ) == 0 )
		{
			Token = getstring( Var );
			if ( Var == NULL )
				Error( "unexpected end after token: %s" , Token );

			//TODO: add check if it's really a number
			rp_scalex = (float)atof(Token);

			Token = getstring( Var );
			if ( Var != NULL )
				Error( "%s followed by unexpected token: %s" , Token, Var );

			//TODO: add check if it's really a number
			rp_scaley = (float)atof(Token);

		} else
		if ( stricmp( Token , "scroll" ) == 0 )
		{
			Token = getstring( Var );
			if ( Var == NULL )
				Error( "unexpected end after token: %s" , Token );

			//TODO: add check if it's really a number
			rp_scrollx = (float)atof(Token);

			Token = getstring( Var );
			//there is this "tcmod scroll" with four!! paramters..
			//i have no idear what the other 2 are for.
//			if ( Var != NULL )
//				Error( "%s followed by unexpected token: %s" , Token, Var );

			//TODO: add check if it's really a number
			rp_scrolly = (float)atof(Token);

		} else
		if ( stricmp( Token , "turb" ) == 0 )
		{
			Token = getstring( Var );
			if ( Var == NULL )
				Error( "unexpected end after token: %s" , Token );

			//TODO: add check if it's really a number
			rp_turba = (float)atof(Token);

			Token = getstring( Var );
			if ( Var == NULL )
				Error( "unexpected end after token: %s" , Token );

			//TODO: add check if it's really a number
			rp_turbb = (float)atof(Token);

			Token = getstring( Var );
			if ( Var == NULL )
				Error( "unexpected end after token: %s" , Token );

			//TODO: add check if it's really a number
			rp_turbc = (float)atof(Token);

			Token = getstring( Var );
			if ( Var != NULL )
				Error( "%s followed by unexpected token: %s" , Token, Var );

			//TODO: add check if it's really a number
			rp_turbd = (float)atof(Token);
		} else
		if ( stricmp( Token , "stretch" ) == 0 )
		{
			Token = getstring( Var );
			if ( Var == NULL )
				Error( "unexpected end after token: %s" , Token );

			if ( stricmp( Type , "sin" ) != 0 )
				Error( "unknown tcmod stretch function: %s" , Token );

			//TODO: add check if it's really a number
			rp_stretchsina = (float)atof(Token);

			Token = getstring( Var );
			if ( Var == NULL )
				Error( "unexpected end after token: %s" , Token );

			//TODO: add check if it's really a number
			rp_stretchsinb = (float)atof(Token);

			Token = getstring( Var );
			if ( Var == NULL )
				Error( "unexpected end after token: %s" , Token );

			//TODO: add check if it's really a number
			rp_stretchsinc = (float)atof(Token);

			Token = getstring( Var );
			if ( Var != NULL )
				Error( "%s followed by unexpected token: %s" , Token, Var );

			//TODO: add check if it's really a number
			rp_stretchsind = (float)atof(Token);
		} else
			Error("unknown tcmod command found %s:",Token);
	} else
	if ( stricmp( Type , "blendfunc" ) == 0 )
	{
		if ( Var == NULL )
			Error( "token expected after blendfunc, but none found");

		Token = getstring( Var );
		if ( Var == NULL )
			Error( "unexpected end after token: %s" , Token );

		if ( stricmp( Token , "gl_zero"					) == 0 ) blend_sfactor=GL_ZERO;else
		if ( stricmp( Token , "gl_one"					) == 0 ) blend_sfactor=GL_ONE;else
		if ( stricmp( Token , "gl_dst_color"			) == 0 ) blend_sfactor=GL_DST_COLOR;else
		if ( stricmp( Token , "gl_one_minus_dst_color"	) == 0 ) blend_sfactor=GL_ONE_MINUS_DST_COLOR;else
		if ( stricmp( Token , "gl_src_alpha"			) == 0 ) blend_sfactor=GL_SRC_ALPHA;else
		if ( stricmp( Token , "gl_one_minus_src_alpha"	) == 0 ) blend_sfactor=GL_ONE_MINUS_SRC_ALPHA;else
		if ( stricmp( Token , "gl_dst_alpha"			) == 0 ) blend_sfactor=GL_DST_ALPHA;else
		if ( stricmp( Token , "gl_one_minus_dst_alpha"	) == 0 ) blend_sfactor=GL_ONE_MINUS_DST_ALPHA;else
		if ( stricmp( Token , "gl_src_alpha_saturate"	) == 0 ) blend_sfactor=GL_SRC_ALPHA_SATURATE;
		else Error( "unknown blendfunc parameter found: %s ", Token );

		Token = getstring( Var );
		if ( Var != NULL )
			Error( "%s followed by unexpected token: %s" , Token, Var );

		if ( stricmp( Token , "gl_zero"					) == 0 ) blend_dfactor=GL_ZERO;else
		if ( stricmp( Token , "gl_one"					) == 0 ) blend_dfactor=GL_ONE;else
		if ( stricmp( Token , "gl_src_color"			) == 0 ) blend_dfactor=GL_SRC_COLOR;else
		if ( stricmp( Token , "gl_one_minus_dst_color"	) == 0 ) blend_dfactor=GL_ONE_MINUS_SRC_COLOR;else
		if ( stricmp( Token , "gl_src_alpha"			) == 0 ) blend_dfactor=GL_SRC_ALPHA;else
		if ( stricmp( Token , "gl_one_minus_src_alpha"	) == 0 ) blend_dfactor=GL_ONE_MINUS_SRC_ALPHA;else
		if ( stricmp( Token , "gl_dst_alpha"			) == 0 ) blend_dfactor=GL_DST_ALPHA;else
		if ( stricmp( Token , "gl_one_minus_dst_alpha"	) == 0 ) blend_dfactor=GL_ONE_MINUS_DST_ALPHA;
		else Error( "unknown blendfunc parameter found: %s ", Token );
	} else
	if ( stricmp( Type , "alphafunc" ) == 0 )
	{
		if ( Var == NULL )
			Error( "token expected after alphafunc, but none found");

		Token = getstring( Var );
		if ( Var != NULL )
			Error( "%s followed by unexpected token: %s" , Token, Var );

		if ( stricmp( Token , "gt0"	 ) == 0 ) {
			alpha_func = GL_GREATER;alpha_ref = 0;
		} else
		if ( stricmp( Token , "lt128") == 0 ) {
			alpha_func = GL_LESS;alpha_ref = 128;
		} else
		if ( stricmp( Token , "ge128") == 0 ) {
			alpha_func = GL_GEQUAL;alpha_ref = 128;
		}
		else Error( "unknown alphafunc parameter found: %s ", Token );
	} else
	if ( stricmp( Type , "depthfunc" ) == 0 )
	{
		if ( Var == NULL )
			Error( "token expected after depthfunc, but none found");
		
		Token = getstring( Var );
		if ( Var != NULL )
			Error( "%s followed by unexpected token: %s" , Token, Var );

		if ( stricmp( Token , "equal"	 ) == 0 ) { 
			depth_func = GL_EQUAL;
		}
		else Error( "unknown depthfunc parameter found: %s ", Token );
	} else
	if ( stricmp( Type , "detail" ) == 0 )
	{
		if ( Var != NULL )
			Error( "detail followed by unexpected token: %s" , Var );

		rp_detail = true;
	} else
	if ( stricmp( Type , "depthwrite" ) == 0 )
	{
		if ( Var != NULL )
			Error( "depthwrite followed by unexpected token: %s" , Var );

		rp_depthwrite = true;
	} else
	if ( stricmp( Type , "clamptexcoords" ) == 0 )
	{
		if ( Var != NULL )
			Error( "clamptexcoords followed by unexpected token: %s" , Var );

		rp_clamptexcoords = true;
	} else
	if ( stricmp( Type , "tcgen" ) == 0 )
	{
		if ( Var == NULL )
			Error( "token expected after tcgen, but none found");

		Token = getstring( Var );
		if ( Var != NULL )
			Error( "%s followed by unexpected token: %s" , Token, Var );

		if ( stricmp( Token , "environment" ) != 0 )
			Error( "unknown tcgen command found: %s ", Token );

		//TODO: add functionality
		// Create enviroment map
	} else
	if ( stricmp( Type , "map" ) == 0 )
	{
		if ( Var == NULL )
			Error( "token expected after map, but none found");
		
		Token = getstring( Var );
		if ( Var != NULL )
			Error( "%s followed by unexpected token: %s" , Token, Var );

		//TODO: add functionality
		// load texture map
	} else
	if ( stricmp( Type , "alphamap" ) == 0 )
	{
		if ( Var == NULL )
			Error( "token expected after alphamap, but none found");

		Token = getstring( Var );
		if ( Var != NULL )
			Error( "%s followed by unexpected token: %s" , Token, Var );

		//TODO: add functionality
		// load texture alphamap
	} else
	if ( stricmp( Type , "animmap" ) == 0 )
	{
		if ( Var == NULL )
			Error( "token expected after animmap, but none found");

		Token = getstring( Var );
		if ( Var == NULL )
			Error( "unexpected end after token: %s" , Token );

		// Token == unknown number

		while ( ( Token = getstring( Var ) ) != NULL )
		{
			//TODO: add functionality
			// load texture animmap
		}
	} else
	if ( stricmp( Type , "rgbgen" ) == 0 )
	{
		if ( Var == NULL )
			Error( "token expected after rgbgen, but none found");
		/*
			{"rgbGen","wave","sin",float,float,float,float}
			{"rgbGen","wave","inversesawtooth",float,float,float,float}
			{"rgbGen","wave","sawtooth",float,float,float,float}
			{"rgbGen","wave","square",float,float,float,float}
			{"rgbGen","wave","noise",float,float,float,float}
			{"rgbGen","wave","triangle",float,float,float,float}
			{"rgbGen","identity"}
			{"rgbGen","entity"}
			{"rgbGen","exactvertex"}
			{"rgbGen","vertex"}
			{"rgbGen","identitylighting"}
			{"rgbGen","lightingDiffuse"}
			{"rgbGen","lightingSpecular"}
			{"rgbGen","oneminusentity"}
		*/
	} else
	if ( stricmp( Type , "alphagen" ) == 0 )
	{
		if ( Var == NULL )
			Error( "token expected after alphagen, but none found");
		/*
			{"colorGen","wave","sin",float,float,float,float}
			{"colorGen","wave","inversesawtooth",float,float,float,float}
			{"colorGen","wave","sawtooth",float,float,float,float}
			{"colorGen","wave","square",float,float,float,float}
			{"colorGen","wave","noise",float,float,float,float}
			{"colorGen","wave","triangle",float,float,float,float}
			{"colorGen","identity"}
			{"colorGen","entity"}
			{"colorGen","exactvertex"}
			{"colorGen","vertex"}
			{"colorGen","identitylighting"}
			{"colorGen","lightingDiffuse"}
			{"colorGen","lightingSpecular"}
			{"colorGen","oneminusentity"}
		*/
	} else
	if ( stricmp( Type , "colorgen" ) == 0 )
	{
		if ( Var == NULL )
			Error( "token expected after colorgen, but none found");
		/*
			{"alphaGen","wave","sin",float,float,float,float}
			{"alphaGen","wave","inversesawtooth",float,float,float,float}
			{"alphaGen","wave","sawtooth",float,float,float,float}
			{"alphaGen","wave","square",float,float,float,float}
			{"alphaGen","wave","noise",float,float,float,float}
			{"alphaGen","wave","triangle",float,float,float,float}
			{"alphaGen","identity"}
			{"alphaGen","entity"}
			{"alphaGen","exactvertex"}
			{"alphaGen","vertex"}
			{"alphaGen","identitylighting"}
			{"alphaGen","lightingDiffuse"}
			{"alphaGen","lightingSpecular"}
			{"alphaGen","oneminusentity"}
		*/
	} else
		Error("unknown command found: %s", Type );
}
Example #10
0
void main(int argc, char **argv) {
  int going = TRUE, forsok = 2,car = 1, tmp, ch;
  long tid;
  char tellstr[100],*tmppscreen, titel[80];

  NewList((struct List *)&aliaslist);
  NewList((struct List *)&edit_list);
  if(!(IntuitionBase=(struct IntuitionBase *)OpenLibrary("intuition.library",0)))
    cleanup(EXIT_ERROR,"Kunde inte öppna intuition.library\n");
  if(!(UtilityBase=OpenLibrary("utility.library",37L)))
    cleanup(EXIT_ERROR,"Kunde inte öppna utility.library\n");
  if(!(LocaleBase=OpenLibrary("locale.library",38L)))
    cleanup(EXIT_ERROR,"Kunde inte öppna locale.library\n");
  if(!(NiKomBase=OpenLibrary("nikom.library",0L)))
    cleanup(EXIT_ERROR,"Kunde inte öppna nikom.linbrary");
  getnodeconfig("NiKom:Datocfg/ConNode.cfg");
  if(!(initnode(NODCON))) cleanup(EXIT_ERROR,"Kunde inte registrera noden i Servern\n");
  if(!(nikomnodeport = CreateMsgPort()))
    cleanup(EXIT_ERROR,"Kunde inte skapa NiKomNode-porten");
  sprintf(nikomnodeportnamn,"NiKomNode%d",nodnr);
  nikomnodeport->mp_Node.ln_Name = nikomnodeportnamn;
  nikomnodeport->mp_Node.ln_Pri = 1;
  AddPort(nikomnodeport);
  sprintf(rexxportnamn,"NiKomRexx%d",nodnr);
  if(!(rexxport=(struct MsgPort *)CreateMsgPort()))
    cleanup(EXIT_ERROR,"Kunde inte öppna RexxPort\n");
  rexxport->mp_Node.ln_Name=rexxportnamn;
  rexxport->mp_Node.ln_Pri=50;
  AddPort(rexxport);
  if(!(RexxSysBase=(struct RsxLib *)OpenLibrary("rexxsyslib.library",0L)))
    cleanup(EXIT_ERROR,"Kunde inte öppna rexxsyslib.library\n");
  if(pubscreen[0]=='-') tmppscreen=NULL;
  else tmppscreen=pubscreen;
  if(!(NiKwind=(struct Window *)OpenWindowTags(NULL,WA_Left,xpos,
                                               WA_Top,ypos,
                                               WA_Width,xsize,
                                               WA_Height,ysize,
                                               WA_IDCMP,IDCMP_CLOSEWINDOW,
                                               WA_MinWidth,50,
                                               WA_MinHeight,10,
                                               WA_MaxWidth,~0,
                                               WA_MaxHeight,~0,
                                               WA_SizeGadget,TRUE,
                                               WA_SizeBBottom, TRUE,
                                               WA_DragBar,TRUE,
                                               WA_DepthGadget,TRUE,
                                               WA_CloseGadget,TRUE,
                                               WA_SimpleRefresh,TRUE,
                                               WA_ScreenTitle,"NiKomCon",
                                               WA_AutoAdjust,TRUE,
                                               WA_PubScreenName,tmppscreen,
                                               TAG_DONE)))
    cleanup(EXIT_ERROR,"Kunde inte öppna fönstret\n");
  if(!OpenIO(NiKwind)) cleanup(EXIT_ERROR,"Kunde inte öppna IO\n");
  strcpy(Servermem->nodid[nodnr],nodid);
  sprintf(titel,"Nod #%d CON: <Ingen inloggad>",nodnr);
  SetWindowTitles(NiKwind,titel,(UBYTE *)-1L);
  Servermem->connectbps[nodnr] = -1;
  conreqtkn();
  do {
    Servermem->idletime[nodnr] = time(NULL);
    memset(commandhistory,0,1024);
    Servermem->inne[nodnr].rader=0;
    sendfile("NiKom:Texter/Inlogg.txt");
    if(Servermem->cfg.ar.preinlogg) sendautorexx(Servermem->cfg.ar.preinlogg);
    going=TRUE;
    while(going) {
      Servermem->idletime[nodnr] = time(NULL);
      puttekn("\r\nNamn: ",-1);
      getstring(EKO,40,NULL);
      if(!stricmp(inmat,Servermem->cfg.ny)) {
        tmp = RegisterNewUser();
        if(tmp == 2) {
          goto panik;
        }
        car = tmp ? 0 : 1;
        going=FALSE;
      }
      else if((inloggad=parsenamn(inmat))>=0) {
        if(readuser(inloggad,&Servermem->inne[nodnr])) {
          puttekn("Error reading user data.\r\n", -1);
          goto panik;
        }
        // TODO: Extract password loop. Should be identical to in PreNode/Ser.c
        forsok=2;
        while(forsok) {
          puttekn("\r\nLösen: ",-1);
          if(Servermem->inne[nodnr].flaggor & STAREKOFLAG)
            getstring(STAREKO,15,NULL);
          else
            getstring(EJEKO,15,NULL);
          if(CheckPassword(inmat, Servermem->inne[nodnr].losen)) {
            forsok=FALSE;
            going=FALSE;
          } else {
            forsok--;
          }
        }
      } else if(inloggad==-1) puttekn("\r\nHittar ej namnet\r\n",-1);
    }
    sprintf(titel,"Nod #%d CON: %s #%d",nodnr,Servermem->inne[nodnr].namn,inloggad);
    SetWindowTitles(NiKwind,titel,(UBYTE *)-1L);
    if(!ReadUnreadTexts(&Servermem->unreadTexts[nodnr], inloggad)) {
      puttekn("Error reading unread text info.\r\n", -1);
      LogEvent(SYSTEM_LOG, ERROR,
               "Can't read unread text info for user %d", inloggad);
      goto panik;
    }
    Servermem->inloggad[nodnr]=inloggad;
    Servermem->idletime[nodnr] = time(NULL);
    if(getft("NiKom:Texter/Bulletin.txt")>Servermem->inne[nodnr].senast_in) sendfile("NiKom:Texter/Bulletin.txt");

    connection();

    if(Servermem->cfg.logmask & LOG_UTLOGG) {
      LogEvent(USAGE_LOG, INFO, "%s loggar ut från nod %d",
               getusername(inloggad), nodnr);
    }
    if(Servermem->say[nodnr]) displaysay();
    if(Servermem->cfg.ar.utlogg) sendautorexx(Servermem->cfg.ar.utlogg);
    sendfile("NiKom:Texter/Utlogg.txt");
    sprintf(titel,"Nod #%d CON: <Ingen inloggad>",nodnr);
    SetWindowTitles(NiKwind,titel,(UBYTE *)-1L);
    Servermem->inloggad[nodnr]=-1;
    
    Servermem->action[nodnr]=0;
    time(&tid);
    Servermem->inne[nodnr].senast_in=tid;
    Servermem->inne[nodnr].tot_tid+=(tid-logintime);
    Servermem->inne[nodnr].loggin++;
    Servermem->info.inloggningar++;
    Servermem->inne[nodnr].defarea=area2;
    writeuser(inloggad,&Servermem->inne[nodnr]);
    WriteUnreadTexts(&Servermem->unreadTexts[nodnr], inloggad);
    writesenaste();
    freealiasmem();
    sprintf(tellstr,"loggade just ut från nod %d",nodnr);
    tellallnodes(tellstr);
  panik:
    nodestate = 0;
    puttekn("\r\n\nEn inloggning till? (J/n)",-1);
  } while((ch = GetChar()) != 'n' && ch != 'N');
  cleanup(EXIT_OK,"");
}
Example #11
0
File: ssh1.c Project: aahud/harvey
void
fromnet(Conn *c)
{
	int fd, len;
	char *s, *es, *r, *w;
	uint32_t ex;
	char buf[64];
	Msg *m;

	for(;;){
		m = recvmsg(c, -1);
		if(m == nil)
			break;
		switch(m->type){
		default:
			badmsg(m, 0);

		case SSH_SMSG_EXITSTATUS:
			ex = getlong(m);
			if(ex==0)
				exits(0);
			sprint(buf, "%lu", ex);
			exits(buf);

		case SSH_MSG_DISCONNECT:
			s = getstring(m);
			error("disconnect: %s", s);

		/*
		 * If we ever add reverse port forwarding, we'll have to
		 * revisit this.  It assumes that the agent connections are
		 * the only ones.
		 */
		case SSH_SMSG_AGENT_OPEN:
			if(!forwardagent)
				error("server tried to use agent forwarding");
			handleagentopen(m);
			break;
		case SSH_MSG_CHANNEL_INPUT_EOF:
			if(!forwardagent)
				error("server tried to use agent forwarding");
			handleagentieof(m);
			break;
		case SSH_MSG_CHANNEL_OUTPUT_CLOSED:
			if(!forwardagent)
				error("server tried to use agent forwarding");
			handleagentoclose(m);
			break;
		case SSH_MSG_CHANNEL_DATA:
			if(!forwardagent)
				error("server tried to use agent forwarding");
			handleagentmsg(m);
			break;

		case SSH_SMSG_STDOUT_DATA:
			fd = outfd;
			goto Dataout;
		case SSH_SMSG_STDERR_DATA:
			fd = 2;
			goto Dataout;
		Dataout:
			len = getlong(m);
			s = (char*)getbytes(m, len);
			if(crstrip){
				es = s+len;
				for(r=w=s; r<es; r++)
					if(*r != '\r')
						*w++ = *r;
				len = w-s;
			}
			write(fd, s, len);
			break;
		}
		free(m);
	}
}		
Example #12
0
bool questline_load(void)
{
  bool success;
  
  success = read_file(get_save_filename("questlines"), &buf, &bufsize);
  if(success == true)
    {
      assert(bufsize > 0);
      bufpos = 0;

      char * version_str;
      uint32_t tlen;
      
      success = getstring(&version_str);
      if(success == true)
        {
          if(strcmp(version_str, QUESTLINE_SAVEFILE_V1))
            success = false;
        }
      free(version_str);

      if(success == true)
        success = get(&globals.active_questline, sizeof globals.active_questline);

      unsigned int qlcount;

      qlcount = 0;
      if(success == true)
        {
          success = get(&tlen, sizeof tlen);
          qlcount = tlen;
        }

      for(unsigned int i = 0; success == true && i < qlcount && globals.questlines_size < MAX_QUESTLINES; i++)
        {
          struct questline * ql;

          ql = questline_new(QUEST_TYPE_SIZEOF_, RELATION_TYPE_SIZEOF_, RELATION_TYPE_SIZEOF_);
          if(ql != NULL)
            {
              globals.questlines[globals.questlines_size] = ql;
              globals.questlines_size++;
              
              if(success == true) success = get(&ql->type,                                sizeof ql->type);
              if(success == true) success = get(&ql->opening_weekday,                     sizeof ql->opening_weekday);
              if(success == true) success = get(&ql->opening_monthday_max,                sizeof ql->opening_monthday_max);
              if(success == true) success = get(&ql->opening_time_hour,                   sizeof ql->opening_time_hour);
              if(success == true) success = get(&ql->opening_time_length,                 sizeof ql->opening_time_length);
              if(success == true) success = get(&ql->first_questgiver.relation_to_player, sizeof ql->first_questgiver.relation_to_player);
              if(success == true) success = getstring(&ql->first_questgiver.name);
              if(success == true) success = get(&ql->first_questgiver.gender,             sizeof ql->first_questgiver.gender);
              if(success == true) success = get(&ql->ancient_person.relation_to_player,   sizeof ql->ancient_person.relation_to_player);
              if(success == true) success = getstring(&ql->ancient_person.name);
              if(success == true) success = get(&ql->ancient_person.gender,               sizeof ql->ancient_person.gender);
              if(success == true) success = get(&ql->reward,                              sizeof ql->reward);
              if(success == true) success = get(&ql->current_quest,                       sizeof ql->current_quest);
              if(success == true) success = get(&ql->current_phase,                       sizeof ql->current_phase);

              if(success == true) success = get(&tlen, sizeof tlen);
              for(unsigned int j = 0; success == true && j < tlen; j++)
                success = quest_load(ql);

              if(success == true) success = get(&tlen, sizeof tlen);
              for(unsigned int j = 0; success == true && j < tlen; j++)
                {
                  char * str;
          
                  success = getstring(&str);
                  if(success == true)
                    success = diary_entry_load(ql, str);
                  free(str);
                }
            }
          else
            success = false;
        }

      if(success == true) success = get(&globals.active_trader,       sizeof globals.active_trader);
      if(success == true) success = get(&globals.active_trader_start, sizeof globals.active_trader_start);
              
      for(int i = 0; success == true && i < MAX_TRADERS; i++)
        {
          char * str;
          
          success = getstring(&str);
          if(success == true)
            {
              globals.traders[i] = trader_load(str);
              if(globals.traders[i] == NULL)
                success = false;
              free(str);
            }
        }
      
      free(buf);

      assert(success == true);
      assert((int) bufpos == bufsize);
    }
  
  return success;
}
Example #13
0
/* parseLS_COLORS():
 *	Parse the LS_COLORS environment variable
 */
void
parseLS_COLORS(const Char *value)
{
    size_t  i, len;
    const Char	 *v;		/* pointer in value */
    char   *c;			/* pointer in colors */
    Extension *volatile e;	/* pointer in extensions */
    jmp_buf_t osetexit;
    size_t omark;

    (void) &e;

    /* init */
    xfree(extensions);
    for (i = 0; i < nvariables; i++)
	variables[i].color = variables[i].defaultcolor;
    colors = NULL;
    extensions = NULL;
    nextensions = 0;

    if (value == NULL)
	return;

    len = Strlen(value);
    /* allocate memory */
    i = 1;
    for (v = value; *v; v++)
	if ((*v & CHAR) == ':')
	    i++;
    extensions = xmalloc(len + i * sizeof(Extension));
    colors = i * sizeof(Extension) + (char *)extensions;
    nextensions = 0;

    /* init pointers */
    v = value;
    c = colors;
    e = &extensions[0];

    /* Prevent from crashing if unknown parameters are given. */

    omark = cleanup_push_mark();
    getexit(osetexit);

    if (setexit() == 0) {

    /* parse */
    while (*v) {
	switch (*v & CHAR) {
	case ':':
	    v++;
	    continue;

	case '*':		/* :*ext=color: */
	    v++;
	    if (getstring(&c, &v, &e->extension, '=') &&
		0 < e->extension.len) {
		v++;
		getstring(&c, &v, &e->color, ':');
		e++;
		continue;
	    }
	    break;

	default:		/* :vl=color: */
	    if (v[0] && v[1] && (v[2] & CHAR) == '=') {
		for (i = 0; i < nvariables; i++)
		    if ((Char)variables[i].variable[0] == (v[0] & CHAR) &&
			(Char)variables[i].variable[1] == (v[1] & CHAR))
			break;
		if (i < nvariables) {
		    v += 3;
		    getstring(&c, &v, &variables[i].color, ':');
		    continue;
		}
		else
		    stderror(ERR_BADCOLORVAR, v[0], v[1]);
	    }
	    break;
	}
	while (*v && (*v & CHAR) != ':')
	    v++;
    }
    }

    cleanup_pop_mark(omark);
    resexit(osetexit);

    nextensions = e - extensions;
}
Example #14
0
int
main(int argc, char **argv)
{
	int rval;
	char c;
	int n, i, cc;

	argc--, argv++;
	if (argc > 0) {
		debug = fopen(*argv, "w");
		if (debug == 0)
			exit(1);
		(void)setbuf(debug, (char *)0);
	}
top:
	errno = 0;
	rval = 0;
	if (read(STDIN_FILENO, &c, 1) != 1)
		exit(0);
	switch (c) {

	case 'O':
		if (tape >= 0)
			(void) close(tape);
		getstring(device);
		getstring(mode);
		DEBUG2("rmtd: O %s %s\n", device, mode);
		/*
		 * XXX the rmt protocol does not provide a means to
		 * specify the permission bits; allow rw for everyone,
		 * as modified by the users umask
		 */
		tape = open(device, atoi(mode), 0666);
		if (tape < 0)
			goto ioerror;
		goto respond;

	case 'C':
		DEBUG("rmtd: C\n");
		getstring(device);		/* discard */
		if (close(tape) < 0)
			goto ioerror;
		tape = -1;
		goto respond;

	case 'L':
		getstring(count);
		getstring(pos);
		DEBUG2("rmtd: L %s %s\n", count, pos);
		rval = lseek(tape, (off_t)strtoll(count, NULL, 10), atoi(pos));
		if (rval < 0)
			goto ioerror;
		goto respond;

	case 'W':
		getstring(count);
		n = atoi(count);
		DEBUG1("rmtd: W %s\n", count);
		record = checkbuf(record, n);
		for (i = 0; i < n; i += cc) {
			cc = read(STDIN_FILENO, &record[i], n - i);
			if (cc <= 0) {
				DEBUG("rmtd: premature eof\n");
				exit(2);
			}
		}
		rval = write(tape, record, n);
		if (rval < 0)
			goto ioerror;
		goto respond;

	case 'R':
		getstring(count);
		DEBUG1("rmtd: R %s\n", count);
		n = atoi(count);
		record = checkbuf(record, n);
		rval = read(tape, record, n);
		if (rval < 0)
			goto ioerror;
		(void)sprintf(resp, "A%d\n", rval);
		(void)write(STDOUT_FILENO, resp, strlen(resp));
		(void)write(STDOUT_FILENO, record, rval);
		goto top;

	case 'I':
		getstring(op);
		getstring(count);
		DEBUG2("rmtd: I %s %s\n", op, count);
		{ struct mtop mtop;
		  mtop.mt_op = atoi(op);
		  mtop.mt_count = atoi(count);
		  if (ioctl(tape, MTIOCTOP, (char *)&mtop) < 0)
			goto ioerror;
		  rval = mtop.mt_count;
		}
		goto respond;

	case 'S':		/* status */
		DEBUG("rmtd: S\n");
		{ struct mtget mtget;
		  if (ioctl(tape, MTIOCGET, (char *)&mtget) < 0)
			goto ioerror;
		  rval = sizeof (mtget);
		  if (rval > 24)	/* original mtget structure size */
			rval = 24;
		  (void)sprintf(resp, "A%d\n", rval);
		  (void)write(STDOUT_FILENO, resp, strlen(resp));
		  (void)write(STDOUT_FILENO, (char *)&mtget, rval);
		  goto top;
		}

        case 'V':               /* version */
                getstring(op);
                DEBUG1("rmtd: V %s\n", op);
                rval = 2;
                goto respond;

	default:
		DEBUG1("rmtd: garbage command %c\n", c);
		exit(3);
	}
respond:
	DEBUG1("rmtd: A %d\n", rval);
	(void)sprintf(resp, "A%d\n", rval);
	(void)write(STDOUT_FILENO, resp, strlen(resp));
	goto top;
ioerror:
	error(errno);
	goto top;
}
void string_setunicodetext(avm *vm)
{
    sfString_SetUnicodeText(getint(vm, 0), getstring(vm, 1));
}
Example #16
0
void	Surface::AddParam( char* Type, char* Var )
{
	char*	Token;
	if ( stricmp( Type , "surfaceparam" ) == 0 )
	{
		if ( Var == NULL )
			Error( "token expected after surfaceparam, but none found");

		Token = getstring( Var );
		if ( Var != NULL )
			Error( "%s followed by unexpected token: %s" , Token, Var );

		if ( stricmp( Token , "lightfilter" ) == 0 ) sp_lightfilter = true;else
		if ( stricmp( Token , "playerclip"  ) == 0 ) sp_playerclip  = true;else
		if ( stricmp( Token , "structural"  ) == 0 ) sp_structural  = true;else
		if ( stricmp( Token , "areaportal"  ) == 0 ) sp_areaportal  = true;else
		if ( stricmp( Token , "metalsteps"  ) == 0 ) sp_metalsteps  = true;else
		if ( stricmp( Token , "nolightmap"  ) == 0 ) sp_nolightmap  = true;else
		if ( stricmp( Token , "noimpact"    ) == 0 ) sp_noimpact	 = true;else
		if ( stricmp( Token , "nodamage"    ) == 0 ) sp_nodamage    = true;else
		if ( stricmp( Token , "nonsolid"    ) == 0 ) sp_nonsolid    = true;else
		if ( stricmp( Token , "nomarks"     ) == 0 ) sp_nomarks     = true;else
		if ( stricmp( Token , "origin"      ) == 0 ) sp_origin      = true;else
		if ( stricmp( Token , "nodrop"      ) == 0 ) sp_nodrop      = true;else
		if ( stricmp( Token , "nodraw"      ) == 0 ) sp_nodraw      = true;else
		if ( stricmp( Token , "water"       ) == 0 ) sp_water       = true;else
		if ( stricmp( Token , "slime"       ) == 0 ) sp_slime       = true;else
		if ( stricmp( Token , "slick"       ) == 0 ) sp_slick       = true;else
		if ( stricmp( Token , "trans"       ) == 0 ) sp_trans       = true;else
		if ( stricmp( Token , "lava"        ) == 0 ) sp_lava        = true;else
		if ( stricmp( Token , "sky"         ) == 0 ) sp_sky         = true;else
		if ( stricmp( Token , "fog"         ) == 0 ) sp_fog         = true;
		else Error( "unknown surfaceparam variable: %s" , Token );

	} else
	if ( stricmp( Type , "cull" ) == 0 )
	{
		if ( Var == NULL )
			Error( "token expected after cull, but none found");

		Token = getstring( Var );
		if ( Var != NULL )
			Error( "%s followed by unexpected token: %s" , Token, Var );

		if ( stricmp( Token , "none"		) == 0 ) cull = cull_none     ;else
		if ( stricmp( Token , "disable"		) == 0 ) cull = cull_disable  ;else
		if ( stricmp( Token , "twosided"	) == 0 ) cull = cull_twosided ;else
		if ( stricmp( Token , "backsided"   ) == 0 ) cull = cull_backsided;else
		if ( stricmp( Token , "back"        ) == 0 ) cull = cull_back     ;
		else Error( "unknown cull variable: %s" , Token );
		
	} else
	if ( stricmp( Type , "light" ) == 0 )
	{
		if ( Var == NULL )
			Error( "token expected after light, but none found");

		Token = getstring( Var );
		if ( Var != NULL )
			Error( "%s followed by unexpected token: %s" , Token, Var );

		//TODO: add check if it's really a number
		sf_light = (float)atof(Token);
	} else
	if ( stricmp( Type , "tesssize" ) == 0 )
	{
		if ( Var == NULL )
			Error( "token expected after tesssize, but none found");

		Token = getstring( Var );
		if ( Var != NULL )
			Error( "%s followed by unexpected token: %s" , Token, Var );

		//TODO: add check if it's really a number
		sf_tesssize = (float)atof(Token);
	} else
	if ( stricmp( Type , "sort" ) == 0 )
	{
		if ( Var == NULL )
			Error( "token expected after sort, but none found");

		Token = getstring( Var );
		if ( Var != NULL )
			Error( "%s followed by unexpected token: %s" , Token, Var );

		//TODO: add check if it's really a number
		sf_sort = (float)atof(Token);
	} else
	if ( stricmp( Type , "qer_trans" ) == 0 )
	{
		if ( Var == NULL )
			Error( "token expected after qer_trans, but none found");

		Token = getstring( Var );
		if ( Var != NULL )
			Error( "%s followed by unexpected token: %s" , Token, Var );

		//TODO: add check if it's really a number
		sf_qer_trans = (float)atof(Token);
	} else
	if ( stricmp( Type , "q3map_backsplash" ) == 0 )
	{
		if ( Var == NULL )
			Error( "token expected after q3map_backsplash, but none found");

		Token = getstring( Var );
		if ( Var != NULL )
			Error( "%s followed by unexpected token: %s" , Token, Var );

		//TODO: add check if it's really a number
		sf_q3map_backsplash = (float)atof(Token);
	} else
	if ( stricmp( Type , "q3map_surfacelight" ) == 0 )
	{
		if ( Var == NULL )
			Error( "token expected after q3map_surfacelight, but none found");

		Token = getstring( Var );
		if ( Var != NULL )
			Error( "%s followed by unexpected token: %s" , Token, Var );

		//TODO: add check if it's really a number
		sf_q3map_surfacelight = (float)atof(Token);
	} else
	if ( stricmp( Type , "sky" ) == 0 )
	{
		if ( Var == NULL )
			Error( "token expected after sky, but none found");

		Token = getstring( Var );
		if ( Var != NULL )
			Error( "%s followed by unexpected token: %s" , Token, Var );

		//TODO: add check if it's really a number
		sf_sky = new char[ strlen( Token ) ];
		strcpy( sf_sky , Token );
	} else
	if ( stricmp( Type , "qer_editorimage" ) == 0 )
	{
		if ( Var == NULL )
			Error( "token expected after qer_editorimage, but none found");

		Token = getstring( Var );
		if ( Var != NULL )
			Error( "%s followed by unexpected token: %s" , Token, Var );

		//TODO: add check if it's really a number
		sf_qer_editorimage = new char[ strlen( Token ) ];
		strcpy( sf_qer_editorimage , Token );
	} else
	if ( stricmp( Type , "q3map_lightimage" ) == 0 )
	{
		if ( Var == NULL )
			Error( "token expected after q3map_lightimage, but none found");

		Token = getstring( Var );
		if ( Var != NULL )
			Error( "%s followed by unexpected token: %s" , Token, Var );

		//TODO: add check if it's really a number
		sf_q3map_lightimage = new char[ strlen( Token ) ];
		strcpy( sf_q3map_lightimage , Token );
	} else
	if ( stricmp( Type , "cloudparms" ) == 0 )
	{
		//currently ignores cloudparms
		/*	
			{"cloudparms",int,"full"}
			{"cloudparms",int,"half"}
			{"cloudparms",int}
		*/
	} else
	if ( stricmp( Type , "skyparms" ) == 0 )
	{
		//currently ignores skyparms
		/*	
			{"skyparms",char*,"-","-"}
			{"skyparms",int,"full","-"}
			{"skyparms",int,"full","-"}
			{"skyparms","-",int,"-"}
			{"skyparms","full",int,"-"}
			{"skyparms","half",int,"-"}
		*/
	} else
	if ( stricmp( Type , "deformVertexes" ) == 0 )
	{
		//currently ignores deformVertexes
		/*	
			{"deformVertexes","wave",int,"sin",float,float,float,float}
			{"deformVertexes","autosprite"}
			{"deformVertexes","autosprite2"}
			{"deformVertexes","projectshadow"}
			{"deformVertexes","bulge",float,float,float}
			{"deformVertexes","bulge",float,float,float}
		*/
	} else
	if ( stricmp( Type , "fogparms" ) == 0 )
	{
		//currently ignores fogparms
		//{"fogparms",float,float,float,float,float}
	} else
	if ( stricmp( Type , "q3map_sun" ) == 0 )
	{
		//currently ignores q3map_sun
		//{"q3map_sun",float,float,float,int,int,int}
	} else
	if ( stricmp( Type , "fogGen" ) == 0 )
	{
		//currently ignores fogGen
		//{"fogGen","sin",float,float,float,float}
	} else
	if ( stricmp( Type , "blendMap" ) == 0 )
	{
		//currently ignores blendMap
		//{"blendMap",char*,char*}
	} else
	if ( Var == NULL )
	{
		if ( stricmp( Type , "portal"		 ) == 0 ) sf_portal			= true;else
		if ( stricmp( Type , "fogonly"		 ) == 0 ) sf_fogonly		= true;else
		if ( stricmp( Type , "nomipmaps"	 ) == 0 ) sf_nomipmaps		= true;else
		if ( stricmp( Type , "polygonOffset" ) == 0 ) sf_polygonOffset	= true;else
		if ( stricmp( Type , "lightning"	 ) == 0 ) sf_lightning		= true;else
		if ( stricmp( Type , "backsided"	 ) == 0 ) sf_backsided		= true;
		if ( stricmp( Type , "qer_nocarve"	 ) == 0 ) sf_qer_nocarve	= true;
		else Error( "unknown token: %s" , Type );

	} else
		Error( "unexpected token found: %s" , Type );
}
void font_createfromfile(avm *vm)
{
    word w;
    seti(&w,  sfFont_CreateFromFile(getstring(vm, 0), getint(vm, 1), NULL));
    returnv(vm, &w);
}
Example #18
0
bool	LoadScript( char* filename )
{
	FILE*	F;
	if ( ( F = fopen( filename , "rt" ) ) != NULL ) 
	{
		char*	lineptr;
		while ( !feof( F ) )
		{
			lineptr = getline( F );
			if ( lineptr != NULL )
			{
				char*	Token = getstring( lineptr );
				if ( ( stricmp( Token , "{" ) == 0 ) ||
					 ( stricmp( Token , "}" ) == 0 ) )
				{
					Debug("surface expected, got: %s",Token);
					return false;
				} else
				{
					if ( lineptr != NULL ) {
						Debug("surface name followed by unexpected token: %s",lineptr);
						return false;
					}

					Surface*	newSurface;
					if ( ( newSurface = CreateSurface( Token ) ) != NULL )
					{
						lineptr = getline( F );
						if ( lineptr == NULL ) {
							Error("unexpected end of file"); return false;
						}
						Token = getstring( lineptr );
						if ( stricmp( Token , "{" ) != 0 ) {
							Error("unexpected token found: %s", Token); return false;
						}
						if ( lineptr != NULL ) {
							Error("{ followed by unexpected token: %s", lineptr); 
							return false;
						}
						while ( ( ( Token = lineptr = getline( F ) ) != NULL ) &&
							    ( ( Token = getstring( lineptr ) ) != NULL ) &&
							    ( stricmp( Token , "}" ) != 0 ) )
						{
							if ( stricmp( Token , "{" ) != 0 )
							{
								newSurface->AddParam( Token , lineptr );
							} else
							{
								if ( lineptr != NULL ) {
									Error("{ followed by unexpected token: %s", lineptr); 
									return false;
								}
								RenderPass*	newPass = new RenderPass;
								while ( ( ( Token = lineptr = getline( F ) ) != NULL ) &&
										( ( Token = getstring( lineptr ) ) != NULL ) &&
										( stricmp( Token , "}" ) != 0 ) )
								{
									newPass->AddParam( Token , lineptr );
								}
								if ( Token == NULL ) {
									Error("unexpected end of file"); return false;
								}
								if ( lineptr != NULL ) {
									Error("} followed by unexpected token: %s ", lineptr); 
									return false;
								}
								newSurface->AddPass( newPass );
							}
						}
						if ( Token == NULL ) {
							Error("unexpected end of file"); return false;
						}
						if ( lineptr != NULL ) {
							Error("} followed by unexpected token: %s ", lineptr); 
							return false;
						}
					} else
						Error("failed to make surface");
				}
			}
		}
		fclose(F);
		return true;
	} else
		return false;
}
Example #19
0
int andmot(void) {
	int motnr,going=TRUE,tillf,chng=FALSE,y,mad,clearmed,setratt,changed,x;
	struct ShortUser *userletpek;
	struct FidoDomain *domain;
	struct User skuser;
	struct Mote tempmote,*motpek;
	char tkn;
	if((motnr=parsemot(argument))==-1) {
		puttekn("\r\n\nFinns inget möte som heter så!\r\n\n",-1);
		return(0);
	} else if(motnr==-3) {
		puttekn("\r\n\nSkriv: Ändra Möte <mötesnamn>\r\n\n",-1);
		return(0);
	}
	motpek=getmotpek(motnr);
	if(!MayAdminConf(motnr, inloggad, &Servermem->inne[nodnr])) {
		puttekn("\r\n\nDu har ingen rätt att ändra på det mötet!\r\n\n",-1);
		return(0);
	}
	memcpy(&tempmote,motpek,sizeof(struct Mote));
	while(going) {
		sprintf(outbuffer,"\r\nNamn : (%s) ",tempmote.namn);
		puttekn(outbuffer,-1);
		if(getstring(EKO,40,NULL)) return(1);
		if(inmat[0]) {
			if((tillf=parsemot(inmat))!=-1 && tillf!=motnr) puttekn("\r\n\nMötet finns redan!\r\n",-1);
			else {
				strncpy(tempmote.namn,inmat,40);
				tempmote.namn[40] = 0;
				going=FALSE;
			}
		} else going=FALSE;
	}
	sprintf(outbuffer,"\r\nMAD (%s) ",getusername(tempmote.mad));
	puttekn(outbuffer,-1);
	if(getstring(EKO,40,NULL)) return(1);
	if(inmat[0]) {
		if((mad=parsenamn(inmat))==-1) puttekn("\r\nFinns ingen sådan användare!",-1);
		else tempmote.mad=mad;
	}
	sprintf(outbuffer,"\r\nSorteringsvärde : (%d) ",tempmote.sortpri);
	puttekn(outbuffer,-1);
	if(getstring(EKO,10,NULL)) return(1);
	if(inmat[0]) {
		tillf=atoi(inmat);
		if(tillf<0 || tillf>LONG_MAX) {
			sprintf(outbuffer,"\n\rVärdet måste ligga mellan 0 och %d",LONG_MAX);
			puttekn(outbuffer,-1);
		}
		else tempmote.sortpri=tillf;
	}
	puttekn("\r\nSka mötet vara slutet? ",-1);
	if(!jaellernej('j','n',tempmote.status & SLUTET ? 1 : 2)) {
		puttekn("Öppet",-1);
		if(tempmote.status & SLUTET) {
			chng=TRUE;
			tempmote.status &= ~SLUTET;
		}
	} else {
		puttekn("Slutet",-1);
		if(!(tempmote.status & SLUTET)) {
			chng=TRUE;
			tempmote.status |= SLUTET;
		}
		puttekn("\r\nVilka grupper ska ha tillgång till mötet? (? för lista)\r\n",-1);
		if(editgrupp((char *)&tempmote.grupper)) return(1);
	}
	puttekn("\r\nSka mötet vara skrivskyddat? ",-1);
	if(!jaellernej('j','n',tempmote.status & SKRIVSKYDD ? 1 : 2)) {
		puttekn("Oskyddat",-1);
		tempmote.status &= ~SKRIVSKYDD;
	} else {
		tempmote.status |= SKRIVSKYDD;
		puttekn("Skyddat",-1);
	}
	puttekn("\r\nSka mötet vara kommentarsskyddat? ",-1);
	if(!jaellernej('j','n',tempmote.status & KOMSKYDD ? 1 : 2)) {
		puttekn("Oskyddat",-1);
		tempmote.status &= ~KOMSKYDD;
	} else {
		tempmote.status |= KOMSKYDD;
		puttekn("Skyddat",-1);
	}
	puttekn("\r\nSka mötet vara hemligt? ",-1);
	if(!jaellernej('j','n',tempmote.status & HEMLIGT ? 1 : 2)) {
		puttekn("Ej hemligt",-1);
		tempmote.status &= ~HEMLIGT;
	} else {
		tempmote.status |= HEMLIGT;
		puttekn("Hemligt",-1);
	}
	if(!(tempmote.status & SLUTET)) {
		puttekn("\n\rSka alla användare bli medlemmar automagiskt? ",-1);
		if(!jaellernej('j','n',tempmote.status & AUTOMEDLEM ? 1 : 2)) {
			puttekn("Nej",-1);
			if(tempmote.status & AUTOMEDLEM) {
				chng=TRUE;
				tempmote.status &= ~AUTOMEDLEM;
			}
		} else {
			puttekn("Ja",-1);
			tempmote.status |= AUTOMEDLEM;
		}
		puttekn("\r\nSka rättigheterna styra skrivmöjlighet? ",-1);
		if(!jaellernej('j','n',tempmote.status & SKRIVSTYRT ? 1 : 2)) {
			puttekn("Nej",-1);
			if(tempmote.status & SKRIVSTYRT) chng=TRUE;
			tempmote.status &= ~SKRIVSTYRT;
		} else {
			puttekn("Ja",-1);
			if(!(tempmote.status & SKRIVSTYRT)) chng=TRUE;
			tempmote.status |= SKRIVSTYRT;
			puttekn("\r\nVilka grupper ska ha tillgång till mötet? (? för lista)\r\n",-1);
			if(editgrupp((char *)&tempmote.grupper)) return(1);
		}
	} else tempmote.status &= ~(AUTOMEDLEM | SKRIVSTYRT);
	puttekn("\r\nSka mötet bara vara åtkomligt från ARexx? ",-1);
	if(!jaellernej('j','n',tempmote.status & SUPERHEMLIGT ? 1 : 2)) {
		puttekn("Nej",-1);
		tempmote.status &= ~SUPERHEMLIGT;
	} else {
		tempmote.status |= SUPERHEMLIGT;
		puttekn("Ja",-1);
	}
	if(tempmote.type == MOTE_FIDO) {
		sprintf(outbuffer,"\n\rKatalog: (%s) ",tempmote.dir);
		puttekn(outbuffer,-1);
		getstring(EKO,79,NULL);
		if(inmat[0]) strcpy(tempmote.dir,inmat);
		sprintf(outbuffer,"\n\rTag-namn: (%s) ",tempmote.tagnamn);
		puttekn(outbuffer,-1);
		getstring(EKO,49,NULL);
		if(inmat[0]) strcpy(tempmote.tagnamn,inmat);
		sprintf(outbuffer,"\n\rOrigin: (%s) ",tempmote.origin);
		puttekn(outbuffer,-1);
		getstring(EKO,69,NULL);
		if(inmat[0]) strcpy(tempmote.origin,inmat);
		sprintf(outbuffer,"\n\n\r%c1: ISO Latin 1 (ISO 8859-1)\n\r",tempmote.charset==CHRS_LATIN1 ? '*' : ' ');
		puttekn(outbuffer,-1);
		sprintf(outbuffer,"%c2: SIS-7 (SF7, 'Måsvingar')\n\r",tempmote.charset==CHRS_SIS7 ? '*' : ' ');
		puttekn(outbuffer,-1);
		sprintf(outbuffer,"%c3: IBM CodePage\n\r",tempmote.charset==CHRS_CP437 ? '*' : ' ');
		puttekn(outbuffer,-1);
		sprintf(outbuffer,"%c4: Mac\n\n\r",tempmote.charset==CHRS_MAC ? '*' : ' ');
		puttekn(outbuffer,-1);
		puttekn("Val: ",-1);
		for(;;) {
			tkn=gettekn();
			if(tkn=='1' || tkn=='2' || tkn=='3' || tkn=='4' || tkn=='\r') break;
		}
		switch(tkn) {
			case '1' : tempmote.charset = CHRS_LATIN1; break;
			case '2' : tempmote.charset = CHRS_SIS7; break;
			case '3' : tempmote.charset = CHRS_CP437; break;
			case '4' : tempmote.charset = CHRS_MAC; break;
			default: break;
		}
		puttekn("\n\n\r",-1);
		for(x=0;x<10;x++) {
			if(!Servermem->fidodata.fd[x].domain[0]) break;
			sprintf(outbuffer,"%c%3d: %s (%d:%d/%d.%d)\n\r",tempmote.domain == Servermem->fidodata.fd[x].nummer ? '*' : ' ',
			                                             Servermem->fidodata.fd[x].nummer,
			                                             Servermem->fidodata.fd[x].domain,
			                                             Servermem->fidodata.fd[x].zone,
			                                             Servermem->fidodata.fd[x].net,
			                                             Servermem->fidodata.fd[x].node,
			                                             Servermem->fidodata.fd[x].point);
			puttekn(outbuffer,-1);
		}
		if(!x) {
			puttekn("\n\rDu måste definiera en domän i NiKomFido.cfg först!\n\r",-1);
			return(0);
		}
		for(;;) {
			if(getstring(EKO,10,NULL)) return(1);
			if(!inmat[0]) break;
			if(domain=getfidodomain(atoi(inmat),0)) {
				tempmote.domain=domain->nummer;
				break;
			} else puttekn("\n\rFinns ingen sådan domän.\n\r",-1);
		}
	}


	puttekn("\r\n\nÄr allt korrekt? ",-1);
	if(jaellernej('j','n',1)) puttekn("Ja\n\n\r",-1);
	else {
		puttekn("Nej\r\n\n",-1);
		return(0);
	}
	if(chng) {
		puttekn("Users.dat kommer nu att gås igenom för att nollställa medlemskap\n\r",-1);
		puttekn("och rättigheter som om mötet var nyskapat.\n\n\r",-1);
		puttekn("Är ändringarna fortfarande korrekta? ",-1);
		if(!jaellernej('j','n',1)) {
			puttekn("Nej\n\r",-1);
			return(0);
		}
		puttekn("Ja\n\r",-1);
	}
	memcpy(motpek,&tempmote,sizeof(struct Mote));
	writemeet(motpek);
	if(!chng) return(0);
	if((tempmote.status & AUTOMEDLEM) && !(tempmote.status & SKRIVSTYRT)) return(0);
	if(tempmote.status & SUPERHEMLIGT) return(0);
	if(tempmote.status & AUTOMEDLEM) clearmed=FALSE;
	else clearmed=TRUE;
	if(tempmote.status & (SLUTET | SKRIVSTYRT)) setratt=FALSE;
	else setratt=TRUE;
	for(y=0;y<MAXNOD;y++) {
		BAMCLEAR(Servermem->inne[y].motmed,tempmote.nummer);
		if(setratt) BAMSET(Servermem->inne[y].motratt,tempmote.nummer);
		else BAMCLEAR(Servermem->inne[y].motratt,tempmote.nummer);
	}
	puttekn("\r\nÄndrar i Users.dat..\r\n",-1);
	for(userletpek=(struct ShortUser *)Servermem->user_list.mlh_Head;userletpek->user_node.mln_Succ;userletpek=(struct ShortUser *)userletpek->user_node.mln_Succ) {
		if(!(userletpek->nummer%10)) {
			sprintf(outbuffer,"\r%d",userletpek->nummer);
			puttekn(outbuffer,-1);
		}
		if(readuser(userletpek->nummer,&skuser)) return(0);
		changed=FALSE;
		if(setratt!=BAMTEST(skuser.motratt,tempmote.nummer)) {
			if(setratt) BAMSET(skuser.motratt,tempmote.nummer);
			else BAMCLEAR(skuser.motratt,tempmote.nummer);
			changed=TRUE;
		}
		if(clearmed && BAMTEST(skuser.motmed,tempmote.nummer)) {
			BAMCLEAR(skuser.motmed,tempmote.nummer);
			changed=TRUE;
		}
		if(changed && writeuser(userletpek->nummer,&skuser)) return(0);

	}
	for(y=0;y<MAXNOD;y++) {
		BAMCLEAR(Servermem->inne[y].motmed,tempmote.nummer);
		if(setratt) BAMSET(Servermem->inne[y].motratt,tempmote.nummer);
		else BAMCLEAR(Servermem->inne[y].motratt,tempmote.nummer);
	}
	BAMSET(Servermem->inne[nodnr].motratt,tempmote.nummer);
	BAMSET(Servermem->inne[nodnr].motmed,tempmote.nummer);
	return(0);
}
Example #20
0
void readcommands(int argc, char **argv) 

{
  int i,haploid=0;
  char *parname = NULL ;
  phandle *ph ;
  char str[5000]  ;
  char *tempname ;
  int n ;

  while ((i = getopt (argc, argv, "p:vV")) != -1) {

    switch (i)
      {

      case 'p':
	parname = strdup(optarg) ;
	break;

      case 'v':
	printf("version: %s\n", WVERSION) ; 
	break; 

      case 'V':
	verbose = YES ;
	break; 

      case '?':
	printf ("Usage: bad params.... \n") ;
	fatalx("bad params\n") ;
      }
  }

         
   pcheck(parname,'p') ;
   printf("parameter file: %s\n", parname) ;
   ph = openpars(parname) ;
   dostrsub(ph) ;

/**
DIR2:  /fg/nfiles/admixdata/ms2
SSSS:  DIR2/outfiles 
genotypename: DIR2/autos_ccshad_fakes
eglistname:    DIR2/eurlist  
output:        eurout
*/
   getstring(ph, "genotypename:", &genotypename) ;
   getstring(ph, "genotypelist:", &genotypelist) ;
   getstring(ph, "snpname:", &snpname) ;
   getstring(ph, "indivname:", &indivname) ;
   getstring(ph, "badsnpname:", &badsnpname) ;
   getstring(ph, "flipsnpname:", &flipsnpname) ;
   getstring(ph, "flipstrandname:", &flipstrandname) ;
   getstring(ph, "indoutfilename:", &indoutfilename) ;
   getstring(ph, "indivoutname:", &indoutfilename) ; /* changed 11/02/06 */
   getstring(ph, "snpoutfilename:", &snpoutfilename) ;
   getstring(ph, "snpoutname:", &snpoutfilename) ; /* changed 11/02/06 */
   getstring(ph, "genooutfilename:", &genooutfilename) ; 
   getstring(ph, "genotypeoutname:", &genooutfilename) ; /* changed 11/02/06 */
   getstring(ph, "outputformat:", &omode) ;
   getstring(ph, "outputmode:", &omode) ;
   getstring(ph, "polarize:", &polarid) ;
   getint(ph, "zerodistance:", &zerodistance) ;
   getint(ph, "checksizemode:", &checksizemode) ;
   getint(ph, "badpedignore:", &badpedignore) ;

   getint(ph, "numchrom:", &numchrom) ;
   getstring(ph, "xregionname:", &xregionname) ;
   getdbl(ph, "hwfilter:", &nhwfilter) ;
   getstring(ph, "deletesnpoutname:", &deletesnpoutname);

   getint(ph, "outputgroup:", &ogmode) ;
   getint(ph, "malexhet:", &malexhet) ;
   getint(ph, "nomalexhet:", &malexhet) ; /* changed 11/02/06 */
   getint(ph, "tersemode:", &tersem) ;
   getint(ph, "familynames:", &familynames) ;
   getint(ph, "packout:", &packout) ; /* now obsolete 11/02/06 */
   getint(ph, "decimate:", &decim) ; 
   getint(ph, "dmindis:", &dmindis) ; 
   getint(ph, "dmaxdis:", &dmaxdis) ; 
   getint(ph, "fastdup:", &fastdup) ;
   getint(ph, "flipreference:", &flipreference) ;
   getint(ph, "fastdupnum:", &fastdupnum) ;
   getdbl(ph, "fastdupthresh:", &fastdupthresh) ;
   getdbl(ph, "fastdupkill:", &fastdupkill) ;
   getint(ph, "killr2:",  &killr2) ;
   getint(ph, "hashcheck:", &hashcheck) ;
   getint(ph, "outputall:", &outputall) ;
   getint(ph, "sevencolumnped:", &sevencolumnped) ;
   getint(ph, "phasedmode:", &phasedmode) ;

   getdbl(ph, "r2thresh:", &r2thresh) ;
   getdbl(ph, "r2genlim:", &r2genlim) ;
   getdbl(ph, "r2physlim:", &r2physlim) ;

   getint(ph, "chrom:", &xchrom) ;
   getint(ph, "lopos:", &lopos) ;
   getint(ph, "hipos:", &hipos) ;

   getint(ph, "minchrom:", &minchrom) ;
   getint(ph, "maxchrom:", &maxchrom) ;
   getdbl(ph, "maxmissfrac:", &maxmissfrac) ;
   getint(ph, "maxmissing:", &maxmiss) ;
   
   getstring(ph, "poplistname:", &poplistname) ;
   getstring(ph, "newsnpname:", &newsnpname) ;
   getstring(ph, "newindivname:", &newindivname) ;
   getint(ph, "deletedup:", &deletedup) ;
   getint(ph, "mkdiploid:", &mkdiploid) ;

   writepars(ph) ;
   closepars(ph) ;

}
Example #21
0
static int dss_verifysig(void *key, char *sig, int siglen,
			 char *data, int datalen)
{
    struct dss_key *dss = (struct dss_key *) key;
    char *p;
    int slen;
    char hash[20];
    Bignum r, s, w, gu1p, yu2p, gu1yu2p, u1, u2, sha, v;
    int ret;

    if (!dss->p)
	return 0;

#ifdef DEBUG_DSS
    {
	int i;
	printf("sig:");
	for (i = 0; i < siglen; i++)
	    printf("  %02x", (unsigned char) (sig[i]));
	printf("\n");
    }
#endif
    /*
     * Commercial SSH (2.0.13) and OpenSSH disagree over the format
     * of a DSA signature. OpenSSH is in line with the IETF drafts:
     * it uses a string "ssh-dss", followed by a 40-byte string
     * containing two 160-bit integers end-to-end. Commercial SSH
     * can't be bothered with the header bit, and considers a DSA
     * signature blob to be _just_ the 40-byte string containing
     * the two 160-bit integers. We tell them apart by measuring
     * the length: length 40 means the commercial-SSH bug, anything
     * else is assumed to be IETF-compliant.
     */
    if (siglen != 40) {		       /* bug not present; read admin fields */
	getstring(&sig, &siglen, &p, &slen);
	if (!p || slen != 7 || memcmp(p, "ssh-dss", 7)) {
	    return 0;
	}
	sig += 4, siglen -= 4;	       /* skip yet another length field */
    }
    r = get160(&sig, &siglen);
    s = get160(&sig, &siglen);
    if (!r || !s)
	return 0;

    /*
     * Step 1. w <- s^-1 mod q.
     */
    w = modinv(s, dss->q);

    /*
     * Step 2. u1 <- SHA(message) * w mod q.
     */
    SHA_Simple(data, datalen, (unsigned char *)hash);
    p = hash;
    slen = 20;
    sha = get160(&p, &slen);
    u1 = modmul(sha, w, dss->q);

    /*
     * Step 3. u2 <- r * w mod q.
     */
    u2 = modmul(r, w, dss->q);

    /*
     * Step 4. v <- (g^u1 * y^u2 mod p) mod q.
     */
    gu1p = modpow(dss->g, u1, dss->p);
    yu2p = modpow(dss->y, u2, dss->p);
    gu1yu2p = modmul(gu1p, yu2p, dss->p);
    v = modmul(gu1yu2p, One, dss->q);

    /*
     * Step 5. v should now be equal to r.
     */

    ret = !bignum_cmp(v, r);

    freebn(w);
    freebn(sha);
    freebn(gu1p);
    freebn(yu2p);
    freebn(gu1yu2p);
    freebn(v);
    freebn(r);
    freebn(s);

    return ret;
}
Example #22
0
void syntax_error(const char *service, User *u, const char *command, int msgnum)
{
    const char *str = getstring(u->ni, msgnum);
    notice_lang(service, u, SYNTAX_ERROR, str);
    notice_lang(service, u, MORE_INFO, service, command);
}
Example #23
0
/*
 * Add an item in either the appointment or the event list,
 * depending if the start time is entered or not.
 */
void
apoint_add (void)
{
#define LTIME 6
  char *mesg_1 =
    _("Enter start time ([hh:mm] or [h:mm]), "
      "leave blank for an all-day event : ");
  char *mesg_2 =
    _("Enter end time ([hh:mm] or [h:mm]) or duration (in minutes) : ");
  char *mesg_3 = _("Enter description :");
  char *format_message_1 =
    _("You entered an invalid start time, should be [h:mm] or [hh:mm]");
  char *format_message_2 =
    _("You entered an invalid end time, should be [h:mm] or [hh:mm] or [mm]");
  char *enter_str = _("Press [Enter] to continue");
  int Id = 1;
  char item_time[LTIME] = "";
  char item_mesg[BUFSIZ] = "";
  long apoint_duration = 0, apoint_start;
  unsigned heures, minutes;
  unsigned end_h, end_m;
  int is_appointment = 1;

  /* Get the starting time */
  do
    {
      status_mesg (mesg_1, "");
      if (getstring (win[STA].p, item_time, LTIME, 0, 1) != GETSTRING_ESC)
        {
          if (strlen (item_time) == 0)
            {
              is_appointment = 0;
              break;
            }
          else if (check_time (item_time) != 1)
            {
              status_mesg (format_message_1, enter_str);
              (void)wgetch (win[STA].p);
            }
          else
            (void)sscanf (item_time, "%u:%u", &heures, &minutes);
        }
      else
        return;
    }
  while (check_time (item_time) != 1);

  /*
   * Check if an event or appointment is entered,
   * depending on the starting time, and record the
   * corresponding item.
   */
  if (is_appointment)
    {				/* Get the appointment duration */
      item_time[0] = '\0';
      do
        {
          status_mesg (mesg_2, "");
          if (getstring (win[STA].p, item_time, LTIME, 0, 1) != GETSTRING_VALID)
            return;		//nothing entered, cancel adding of event
          else if (check_time (item_time) == 0)
            {
              status_mesg (format_message_2, enter_str);
              (void)wgetch (win[STA].p);
            }
          else
            {
              if (check_time (item_time) == 2)
                apoint_duration = atoi (item_time);
              else if (check_time (item_time) == 1)
                {
                  (void)sscanf (item_time, "%u:%u", &end_h, &end_m);
                  if (end_h < heures || ((end_h == heures) && (end_m < minutes)))
                    {
                      apoint_duration = MININSEC - minutes + end_m
                        + (24 + end_h - (heures + 1)) * MININSEC;
                    }
                  else
                    {
                      apoint_duration = MININSEC - minutes
                        + end_m + (end_h - (heures + 1)) * MININSEC;
                    }
                }
            }
        }
      while (check_time (item_time) == 0);
    }
  else				/* Insert the event Id */
    Id = 1;

  status_mesg (mesg_3, "");
  if (getstring (win[STA].p, item_mesg, BUFSIZ, 0, 1) == GETSTRING_VALID)
    {
      if (is_appointment)
        {
          apoint_start = date2sec (*calendar_get_slctd_day (), heures, minutes);
          (void)apoint_new (item_mesg, 0L, apoint_start,
                            min2sec (apoint_duration), 0L);
          if (notify_bar ())
            notify_check_added (item_mesg, apoint_start, 0L);
        }
      else
        (void)event_new (item_mesg, 0L,
                         date2sec (*calendar_get_slctd_day (), 12, 0), Id);

      if (hilt == 0)
        hilt++;
    }
  wins_erase_status_bar ();
}
Example #24
0
static void
copyinverted(void)
{
	char	*cp;
	int	c;
	int	type;	/* reference type (mark character) */
	char	symbol[PATLEN + 1];

	/* note: this code was expanded in-line for speed */
	/* while (scanpast('\n') != NULL) { */
	/* other macros were replaced by code using cp instead of blockp */
	cp = blockp;
	for (;;) {
		setmark('\n');
		do {	/* innermost loop optimized to only one test */
			while (*cp != '\n') {
				dbputc(*cp++);
			}
		} while (*++cp == '\0' && (cp = readblock()) != NULL);
		dbputc('\n');	/* copy the newline */

		/* get the next character */
		if (*(cp + 1) == '\0') {
			cp = readblock();
		}
		/* exit if at the end of this file's data */
		if (cp == NULL) {
			break;
		}
		switch (*cp) {
		case '\n':
			lineoffset = dboffset + 1;
			continue;
		case '\t':
			dbputc('\t');
			blockp = cp;
			type = getrefchar();
			switch (type) {
			case NEWFILE:		/* file name */
				return;
			case INCLUDE:		/* #included file */
				putinclude(symbol);
				goto output;
			}
			dbputc(type);
			skiprefchar();
			getstring(symbol);
			goto output;
		}
		c = *cp;
		if (c & 0200) {	/* digraph char? */
			c = dichar1[(c & 0177) / 8];
		}
		/* if this is a symbol */
		if (isalpha(c) || c == '_') {
			blockp = cp;
			getstring(symbol);
			type = ' ';
		output:
			putposting(symbol, type);
			putstring(symbol);
			if (blockp == NULL) {
				return;
			}
			cp = blockp;
		}
	}
	blockp = cp;
}
Example #25
0
static int
get_any_string (int idx, sb *in, sb *out)
{
  sb_reset (out);
  idx = sb_skip_white (idx, in);

  if (idx < in->len)
    {
      if (in->len > idx + 2 && in->ptr[idx + 1] == '\'' && ISBASE (in->ptr[idx]))
	{
	  while (!ISSEP (in->ptr[idx]))
	    sb_add_char (out, in->ptr[idx++]);
	}
      else if (in->ptr[idx] == '%' && macro_alternate)
	{
	  int val;
	  char buf[20];

	  /* Turns the next expression into a string.  */
	  /* xgettext: no-c-format */
	  idx = (*macro_expr) (_("% operator needs absolute expression"),
			       idx + 1,
			       in,
			       &val);
	  sprintf (buf, "%d", val);
	  sb_add_string (out, buf);
	}
      else if (in->ptr[idx] == '"'
	       || (in->ptr[idx] == '<' && (macro_alternate || macro_mri))
	       || (macro_alternate && in->ptr[idx] == '\''))
	{
	  if (macro_alternate && ! macro_strip_at && in->ptr[idx] != '<')
	    {
	      /* Keep the quotes.  */
	      sb_add_char (out, '"');
	      idx = getstring (idx, in, out);
	      sb_add_char (out, '"');
	    }
	  else
	    {
	      idx = getstring (idx, in, out);
	    }
	}
      else
	{
	  char *br_buf = xmalloc(1);
	  char *in_br = br_buf;

	  *in_br = '\0';
	  while (idx < in->len
		 && (*in_br
		     || (in->ptr[idx] != ' '
			 && in->ptr[idx] != '\t'))
		 && in->ptr[idx] != ','
		 && (in->ptr[idx] != '<'
		     || (! macro_alternate && ! macro_mri)))
	    {
	      char tchar = in->ptr[idx];

	      switch (tchar)
		{
		case '"':
		case '\'':
		  sb_add_char (out, in->ptr[idx++]);
		  while (idx < in->len
			 && in->ptr[idx] != tchar)
		    sb_add_char (out, in->ptr[idx++]);
		  if (idx == in->len)
		    return idx;
		  break;
		case '(':
		case '[':
		  if (in_br > br_buf)
		    --in_br;
		  else
		    {
		      br_buf = xmalloc(strlen(in_br) + 2);
		      strcpy(br_buf + 1, in_br);
		      free(in_br);
		      in_br = br_buf;
		    }
		  *in_br = tchar;
		  break;
		case ')':
		  if (*in_br == '(')
		    ++in_br;
		  break;
		case ']':
		  if (*in_br == '[')
		    ++in_br;
		  break;
		}
	      sb_add_char (out, tchar);
	      ++idx;
	    }
	  free(br_buf);
	}
    }

  return idx;
}
Example #26
0
/**
 * The /bs info command.
 * @param u The user who issued the command
 * @param MOD_CONT to continue processing other modules, MOD_STOP to stop processing.
 **/
int do_info(User * u)
{
    BotInfo *bi;
    ChannelInfo *ci;
    char *query = strtok(NULL, " ");

    int need_comma = 0, is_servadmin = is_services_admin(u);
    char buf[BUFSIZE], *end;
    const char *commastr = getstring(u->na, COMMA_SPACE);

    if (!query)
        syntax_error(s_BotServ, u, "INFO", BOT_INFO_SYNTAX);
    else if ((bi = findbot(query))) {
        char buf[BUFSIZE];
        struct tm *tm;

        notice_lang(s_BotServ, u, BOT_INFO_BOT_HEADER, bi->nick);
        notice_lang(s_BotServ, u, BOT_INFO_BOT_MASK, bi->user, bi->host);
        notice_lang(s_BotServ, u, BOT_INFO_BOT_REALNAME, bi->real);
        tm = localtime(&bi->created);
        strftime_lang(buf, sizeof(buf), u, STRFTIME_DATE_TIME_FORMAT, tm);
        notice_lang(s_BotServ, u, BOT_INFO_BOT_CREATED, buf);
        notice_lang(s_BotServ, u, BOT_INFO_BOT_OPTIONS,
                    getstring(u->na,
                              (bi->
                               flags & BI_PRIVATE) ? BOT_INFO_OPT_PRIVATE :
                              BOT_INFO_OPT_NONE));
        notice_lang(s_BotServ, u, BOT_INFO_BOT_USAGE, bi->chancount);

        if (is_services_admin(u))
            send_bot_channels(u, bi);
    } else if ((ci = cs_findchan(query))) {
        if (!is_servadmin && !is_founder(u, ci)) {
            notice_lang(s_BotServ, u, PERMISSION_DENIED);
            return MOD_CONT;
        }
        if (ci->flags & CI_VERBOTEN) {
            notice_lang(s_BotServ, u, CHAN_X_FORBIDDEN, query);
            return MOD_CONT;
        }

        notice_lang(s_BotServ, u, BOT_INFO_CHAN_HEADER, ci->name);
        if (ci->bi)
            notice_lang(s_BotServ, u, BOT_INFO_CHAN_BOT, ci->bi->nick);
        else
            notice_lang(s_BotServ, u, BOT_INFO_CHAN_BOT_NONE);

        if (ci->botflags & BS_KICK_BADWORDS) {
            if (ci->ttb[TTB_BADWORDS])
                notice_lang(s_BotServ, u, BOT_INFO_CHAN_KICK_BADWORDS_BAN,
                            getstring(u->na, BOT_INFO_ACTIVE),
                            ci->ttb[TTB_BADWORDS]);
            else
                notice_lang(s_BotServ, u, BOT_INFO_CHAN_KICK_BADWORDS,
                            getstring(u->na, BOT_INFO_ACTIVE));
        } else
            notice_lang(s_BotServ, u, BOT_INFO_CHAN_KICK_BADWORDS,
                        getstring(u->na, BOT_INFO_INACTIVE));
        if (ci->botflags & BS_KICK_BOLDS) {
            if (ci->ttb[TTB_BOLDS])
                notice_lang(s_BotServ, u, BOT_INFO_CHAN_KICK_BOLDS_BAN,
                            getstring(u->na, BOT_INFO_ACTIVE),
                            ci->ttb[TTB_BOLDS]);
            else
                notice_lang(s_BotServ, u, BOT_INFO_CHAN_KICK_BOLDS,
                            getstring(u->na, BOT_INFO_ACTIVE));
        } else
            notice_lang(s_BotServ, u, BOT_INFO_CHAN_KICK_BOLDS,
                        getstring(u->na, BOT_INFO_INACTIVE));
        if (ci->botflags & BS_KICK_CAPS) {
            if (ci->ttb[TTB_CAPS])
                notice_lang(s_BotServ, u, BOT_INFO_CHAN_KICK_CAPS_BAN,
                            getstring(u->na, BOT_INFO_ACTIVE),
                            ci->ttb[TTB_CAPS], ci->capsmin,
                            ci->capspercent);
            else
                notice_lang(s_BotServ, u, BOT_INFO_CHAN_KICK_CAPS_ON,
                            getstring(u->na, BOT_INFO_ACTIVE), ci->capsmin,
                            ci->capspercent);
        } else
            notice_lang(s_BotServ, u, BOT_INFO_CHAN_KICK_CAPS_OFF,
                        getstring(u->na, BOT_INFO_INACTIVE));
        if (ci->botflags & BS_KICK_COLORS) {
            if (ci->ttb[TTB_COLORS])
                notice_lang(s_BotServ, u, BOT_INFO_CHAN_KICK_COLORS_BAN,
                            getstring(u->na, BOT_INFO_ACTIVE),
                            ci->ttb[TTB_COLORS]);
            else
                notice_lang(s_BotServ, u, BOT_INFO_CHAN_KICK_COLORS,
                            getstring(u->na, BOT_INFO_ACTIVE));
        } else
            notice_lang(s_BotServ, u, BOT_INFO_CHAN_KICK_COLORS,
                        getstring(u->na, BOT_INFO_INACTIVE));
        if (ci->botflags & BS_KICK_FLOOD) {
            if (ci->ttb[TTB_FLOOD])
                notice_lang(s_BotServ, u, BOT_INFO_CHAN_KICK_FLOOD_BAN,
                            getstring(u->na, BOT_INFO_ACTIVE),
                            ci->ttb[TTB_FLOOD], ci->floodlines,
                            ci->floodsecs);
            else
                notice_lang(s_BotServ, u, BOT_INFO_CHAN_KICK_FLOOD_ON,
                            getstring(u->na, BOT_INFO_ACTIVE),
                            ci->floodlines, ci->floodsecs);
        } else
            notice_lang(s_BotServ, u, BOT_INFO_CHAN_KICK_FLOOD_OFF,
                        getstring(u->na, BOT_INFO_INACTIVE));
        if (ci->botflags & BS_KICK_REPEAT) {
            if (ci->ttb[TTB_REPEAT])
                notice_lang(s_BotServ, u, BOT_INFO_CHAN_KICK_REPEAT_BAN,
                            getstring(u->na, BOT_INFO_ACTIVE),
                            ci->ttb[TTB_REPEAT], ci->repeattimes);
            else
                notice_lang(s_BotServ, u, BOT_INFO_CHAN_KICK_REPEAT_ON,
                            getstring(u->na, BOT_INFO_ACTIVE),
                            ci->repeattimes);
        } else
            notice_lang(s_BotServ, u, BOT_INFO_CHAN_KICK_REPEAT_OFF,
                        getstring(u->na, BOT_INFO_INACTIVE));
        if (ci->botflags & BS_KICK_REVERSES) {
            if (ci->ttb[TTB_REVERSES])
                notice_lang(s_BotServ, u, BOT_INFO_CHAN_KICK_REVERSES_BAN,
                            getstring(u->na, BOT_INFO_ACTIVE),
                            ci->ttb[TTB_REVERSES]);
            else
                notice_lang(s_BotServ, u, BOT_INFO_CHAN_KICK_REVERSES,
                            getstring(u->na, BOT_INFO_ACTIVE));
        } else
            notice_lang(s_BotServ, u, BOT_INFO_CHAN_KICK_REVERSES,
                        getstring(u->na, BOT_INFO_INACTIVE));
        if (ci->botflags & BS_KICK_UNDERLINES) {
            if (ci->ttb[TTB_UNDERLINES])
                notice_lang(s_BotServ, u,
                            BOT_INFO_CHAN_KICK_UNDERLINES_BAN,
                            getstring(u->na, BOT_INFO_ACTIVE),
                            ci->ttb[TTB_UNDERLINES]);
            else
                notice_lang(s_BotServ, u, BOT_INFO_CHAN_KICK_UNDERLINES,
                            getstring(u->na, BOT_INFO_ACTIVE));
        } else
            notice_lang(s_BotServ, u, BOT_INFO_CHAN_KICK_UNDERLINES,
                        getstring(u->na, BOT_INFO_INACTIVE));

        end = buf;
        *end = 0;
        if (ci->botflags & BS_DONTKICKOPS) {
            end += snprintf(end, sizeof(buf) - (end - buf), "%s",
                            getstring(u->na, BOT_INFO_OPT_DONTKICKOPS));
            need_comma = 1;
        }
        if (ci->botflags & BS_DONTKICKVOICES) {
            end += snprintf(end, sizeof(buf) - (end - buf), "%s%s",
                            need_comma ? commastr : "",
                            getstring(u->na, BOT_INFO_OPT_DONTKICKVOICES));
            need_comma = 1;
        }
        if (ci->botflags & BS_FANTASY) {
            end += snprintf(end, sizeof(buf) - (end - buf), "%s%s",
                            need_comma ? commastr : "",
                            getstring(u->na, BOT_INFO_OPT_FANTASY));
            need_comma = 1;
        }
        if (ci->botflags & BS_GREET) {
            end += snprintf(end, sizeof(buf) - (end - buf), "%s%s",
                            need_comma ? commastr : "",
                            getstring(u->na, BOT_INFO_OPT_GREET));
            need_comma = 1;
        }
        if (ci->botflags & BS_NOBOT) {
            end += snprintf(end, sizeof(buf) - (end - buf), "%s%s",
                            need_comma ? commastr : "",
                            getstring(u->na, BOT_INFO_OPT_NOBOT));
            need_comma = 1;
        }
        if (ci->botflags & BS_SYMBIOSIS) {
            end += snprintf(end, sizeof(buf) - (end - buf), "%s%s",
                            need_comma ? commastr : "",
                            getstring(u->na, BOT_INFO_OPT_SYMBIOSIS));
            need_comma = 1;
        }
        notice_lang(s_BotServ, u, BOT_INFO_CHAN_OPTIONS,
                    *buf ? buf : getstring(u->na, BOT_INFO_OPT_NONE));

    } else
        notice_lang(s_BotServ, u, BOT_INFO_NOT_FOUND, query);
    return MOD_CONT;
}
Example #27
0
void
procmain(void)
{
	int     ch;		/* input */
	double  x;		/* desired new x coordinate */
	double  y;		/* desired new y coordinate */
	double  temp;		/* for temporary calculations */
	FILE   *fp;		/* for opening files */
	int     loop;		/* a loop counter */
	bool    hasmoved = FALSE;	/* set if player has moved */

	ch = inputoption();
	mvaddstr(4, 0, "\n\n");	/* clear status area */

	move(7, 0);
	clrtobot();		/* clear data on bottom area of screen */

	if (Player.p_specialtype == SC_VALAR && (ch == '1' || ch == '7'))
		/* valar cannot move */
		ch = ' ';

	switch (ch) {
	case 'K':		/* move up/north */
	case 'N':
		x = Player.p_x;
		y = Player.p_y + MAXMOVE();
		hasmoved = TRUE;
		break;

	case 'J':		/* move down/south */
	case 'S':
		x = Player.p_x;
		y = Player.p_y - MAXMOVE();
		hasmoved = TRUE;
		break;

	case 'L':		/* move right/east */
	case 'E':
		x = Player.p_x + MAXMOVE();
		y = Player.p_y;
		hasmoved = TRUE;
		break;

	case 'H':		/* move left/west */
	case 'W':
		x = Player.p_x - MAXMOVE();
		y = Player.p_y;
		hasmoved = TRUE;
		break;

	default:		/* rest */
		Player.p_energy += (Player.p_maxenergy + Player.p_shield) / 15.0
		    + Player.p_level / 3.0 + 2.0;
		Player.p_energy =
		    MIN(Player.p_energy, Player.p_maxenergy + Player.p_shield);

		if (Player.p_status != S_CLOAKED)
			/* cannot find mana if cloaked */
		{
			Player.p_mana += (Circle + Player.p_level) / 4.0;

			if (drandom() < 0.2 && Player.p_status == S_PLAYING && !Throne)
				/* wandering monster */
				encounter(-1);
		}
		break;

	case 'X':		/* change/examine a character */
		changestats(TRUE);
		break;

	case '1':		/* move */
		for (loop = 3; loop; --loop) {
			mvaddstr(4, 0, "X Y Coordinates ? ");
			getstring(Databuf, SZ_DATABUF);

			if (sscanf(Databuf, "%lf %lf", &x, &y) != 2)
				mvaddstr(5, 0, "Try again\n");
			else
				if (distance(Player.p_x, x, Player.p_y, y) > MAXMOVE())
					ILLMOVE();
				else {
					hasmoved = TRUE;
					break;
				}
		}
		break;

	case '2':		/* players */
		userlist(TRUE);
		break;

	case '3':		/* message */
		mvaddstr(4, 0, "Message ? ");
		getstring(Databuf, SZ_DATABUF);
		/* we open the file for writing to erase any data which is
		 * already there */
		fp = fopen(_PATH_MESS, "w");
		if (Databuf[0] != '\0')
			fprintf(fp, "%s: %s", Player.p_name, Databuf);
		fclose(fp);
		break;

	case '4':		/* stats */
		allstatslist();
		break;

	case '5':		/* good-bye */
		leavegame();

	case '6':		/* cloak */
		if (Player.p_level < MEL_CLOAK || Player.p_magiclvl < ML_CLOAK)
			ILLCMD();
		else
			if (Player.p_status == S_CLOAKED)
				Player.p_status = S_PLAYING;
			else
				if (Player.p_mana < MM_CLOAK)
					mvaddstr(5, 0, "No mana left.\n");
				else {
					Changed = TRUE;
					Player.p_mana -= MM_CLOAK;
					Player.p_status = S_CLOAKED;
				}
		break;

	case '7':		/* teleport */
		/*
	         * conditions for teleport
	         *	- 20 per (level plus magic level)
	         *	- OR council of the wise or valar or ex-valar
	         *	- OR transport from throne
	         * transports from throne cost no mana
	         */
		if (Player.p_level < MEL_TELEPORT || Player.p_magiclvl < ML_TELEPORT)
			ILLCMD();
		else
			for (loop = 3; loop; --loop) {
				mvaddstr(4, 0, "X Y Coordinates ? ");
				getstring(Databuf, SZ_DATABUF);

				if (sscanf(Databuf, "%lf %lf", &x, &y) == 2) {
					temp = distance(Player.p_x, x, Player.p_y, y);
					if (!Throne
					/* can transport anywhere from throne */
					    && Player.p_specialtype <= SC_COUNCIL
					/* council, valar can transport
					 * anywhere */
					    && temp > (Player.p_level + Player.p_magiclvl) * 20.0)
						/* can only move 20 per exp.
						 * level + mag. level */
						ILLMOVE();
					else {
						temp = (temp / 75.0 + 1.0) * 20.0;	/* mana used */

						if (!Throne && temp > Player.p_mana)
							mvaddstr(5, 0, "Not enough power for that distance.\n");
						else {
							if (!Throne)
								Player.p_mana -= temp;
							hasmoved = TRUE;
							break;
						}
					}
				}
			}
		break;

	case 'C':
	case '9':		/* monster */
		if (Throne)
			/* no monsters while on throne */
			mvaddstr(5, 0, "No monsters in the chamber!\n");
		else
			if (Player.p_specialtype != SC_VALAR)
				/* the valar cannot call monsters */
			{
				Player.p_sin += 1e-6;
				encounter(-1);
			}
		break;

	case '0':		/* decree */
		if (Wizard || (Player.p_specialtype == SC_KING && Throne))
			/* kings must be on throne to decree */
			dotampered();
		else
			ILLCMD();
		break;

	case '8':		/* intervention */
		if (Wizard || Player.p_specialtype >= SC_COUNCIL)
			dotampered();
		else
			ILLCMD();
		break;
	}

	if (hasmoved)
		/* player has moved -- alter coordinates, and do random
		 * monster */
	{
		altercoordinates(x, y, A_SPECIFIC);

		if (drandom() < 0.2 && Player.p_status == S_PLAYING && !Throne)
			encounter(-1);
	}
}
void string_settext(avm *vm)
{
    sfString_SetText(getint(vm, 0), getstring(vm, 1));
}
/**
  * @brief  Main function
  * @param  None
  * @retval None
  */
int main(void)
{
    char temp;
    char str[20];
    char c = '%';
    int interval = 0;
    int i;
    unsigned int valid_data = 0;
    int temperature, voltage;
    signed int  AverageCurrent;
    unsigned int  RemainingCapacity;
    unsigned int  soc;                        /* Stores State of Charge */
    unsigned int  dcap;                       /* Stores Design Capacity */
    WDTCTL = WDTPW + WDTHOLD;                 /* Stop WDT */

    initI2C();
    /* Init UART for print message */
    initUART();

    printf("******************************************\r\n");
    printf("This is a battery demo !				  \r\n");
    printf("Press:									  \r\n");
    printf("1. To see the battery main parameter 	  \r\n");
    printf("2. To see the battery State of charge!	  \r\n");
    printf("******************************************\r\n");
    printf("\r\n");
    printf("\r\n");
    printf("\r\n");

    temp = receiveByte();

    while (1) {
        if (temp == '1') {
            /* Start the timer */
            initTimer();

            while (1) {
            	valid_data = 1;

                /* Read temperature (units = 0.1K) */
                if(!USCI_I2C_READ(RxDataBuff, 2, bq27510CMD_TEMP_LSB)) {
                	/* Convert K to Celsius degree */
                	temperature = (transBytes2Int(RxDataBuff[1], RxDataBuff[0])) / 10 - 273;
                } else {
                	valid_data = 0;
                }
                
                /* Read voltage (units = mV) */
                if(!USCI_I2C_READ(RxDataBuff, 2, bq27510CMD_VOLT_LSB)) {
                	voltage = transBytes2Int(RxDataBuff[1], RxDataBuff[0]);
                } else {
                	valid_data = 0;
                }
                
                /* Read AverageCurrent (units = mA) */
                if(!USCI_I2C_READ(RxDataBuff, 2, bq27510CMD_AI_LSB)) {
                	AverageCurrent = transBytes2Int(RxDataBuff[1], RxDataBuff[0]);
                } else {
                	valid_data = 0;
                }
                
                /* Read state of charge (units = %) */
                if(!USCI_I2C_READ(RxDataBuff, 2, bq27510CMD_SOC_LSB)){
                	soc = transBytes2Int(RxDataBuff[1], RxDataBuff[0]);
                } else {
                	valid_data = 0;
                }
                
                /* Read DesignCapacity (units = mAH) */
                if(!USCI_I2C_READ(RxDataBuff, 2, 0x2e)) {
                	dcap = transBytes2Int(RxDataBuff[1], RxDataBuff[0]);
                } else {
                	valid_data = 0;
                }
                
                /* Read RemainingCapacity (units = mAH) */
                if(!USCI_I2C_READ(RxDataBuff, 2, bq27510CMD_RM_LSB)) {
                	RemainingCapacity = transBytes2Int(RxDataBuff[1], RxDataBuff[0]);
                } else {
                	valid_data = 0;
                }

                /* every 10*0.5s print the battery message */
                if (timerCount >= 10) {
                    /* Clear the console */
                    printf("\033[2J");
                    printf("\033[H");
                    
                    if (valid_data) {
						/* Read AverageCurrent (units = mA) */
						USCI_I2C_READ(RxDataBuff, 2, bq27510CMD_AI_LSB);
						AverageCurrent = transBytes2Int(RxDataBuff[1], RxDataBuff[0]);

						if (AverageCurrent > 0) {
							printf("The battery is charging!\r\n");
						} else {
							printf("The battery is discharging!\r\n");
						}

						timerCount = 0;

						printf("Current Temperature  :%d¡æ\r\n", temperature);
						printf("Current Voltage  :%dmV\r\n", voltage);
						printf("AverageCurrent  :%dmA\r\n", AverageCurrent);
						printf("State of Charge :%d", soc);
						printf("%c\r\n", c);
						printf("DesignCapacity :%dmAH\r\n", dcap);
						printf("RemainingCapacity :%dmAH\r\n", RemainingCapacity);
                    } else {
                    	timerCount = 0;
                    	printf("There is no battery or the battery's capacity is too low\n\r");
                    	printf("Please plugin a battery or charge the battery\n\r");
                    }
                }
            }
        }

        if (temp == '2') {

            printf("Please set the show time interval(units = s)\r\n");

            /* Get your input and store in str */
            getstring(str);

            /* Convert the string into int */
            for (i = 0; str[i] != '\r'; i++) {
                interval = interval * 10 + str[i] - '0';
            }

            /* Star the timer */
            initTimer();
            printf("\r\n");
            timerCount = interval * 2;

            while (1) {
                /* Read state of charge (units = %) */
            	USCI_I2C_READ(RxDataBuff, 2, bq27510CMD_SOC_LSB);
            	USCI_I2C_READ(RxDataBuff, 2, bq27510CMD_SOC_LSB);

                if(!USCI_I2C_READ(RxDataBuff, 2, bq27510CMD_SOC_LSB)) {
                	soc = transBytes2Int(RxDataBuff[1], RxDataBuff[0]);
                } else {
                	 if (timerCount >= interval * 2) {
                	     timerCount = 0;
                	     /* Clear the console */
                	     printf("\033[2J");
                	     printf("\033[H");
                	     printf("There is no battery or the battery's capacity is too low\n\r");
                	     printf("Please plugin a battery or charge the battery\n\r");
                	     continue;
                	 }
                }

                /* Show the state of charge every interval*2*0.5s */
                //if (timerCount >= interval * 2) {
                {
                    timerCount = 0;
                    printf("State of Charge :%d", soc);
                    printf("%c\r\n", c);

                }

                if (soc == 100) {
                    printf("State of Charge :%d", soc);
                    printf("%c\r\n", c);
                    temp = '0';
                    break;
                }
            }
        }
    }
}
Example #30
0
command()
{
float tval;
int i,echeck;
int pmin,pmax,pstep;
char tbuf[20];

while (echeck = getstring(": ")) {
	if (echeck == EOF) {
		fileinput(STD);
	}
	else if (startsame(in,"cycle")) {
		cycle();
	}
	else if (startsame(in,"coarticulation")) {
		ttyprint("coarticulation %s: change? ",(coartflag ? "ON":"OFF"));
		fscanf(infp,"%s",in);
		if(in[0] == 'n') continue;
		coartflag = 1 - coartflag;
	}
	else if (startsame(in,"rc")) {
		printf("reset and cycle\n");
		zarrays();
		cycle();
	}
	else if (startsame(in,"wordacts")) {
		printwords(printmin,printmax,3,stdout);
		if (outfile) printwords(printmin,printmax,3,outfile);
	}
	else if (startsame(in,"wtacts")) {
		printwt(printmin,printmax,3,stdout);
		if (outfile) printwt(printmin,printmax,3,outfile);
	}
	else if (startsame(in,"owtacts")) {
		getstring("word: ");
		strcpy(tbuf,in);
		printonewt(tbuf,printmin,printmax,3,stdout);
		if (outfile) printonewt(tbuf,printmin,printmax,3,outfile);
	}
	else if (startsame(in,"phonacts")) {
		printphonemes(printmin,printmax,3,stdout);
		if (outfile) 
		    printphonemes(printmin,printmax,3,outfile);
	}
	else if (startsame(in,"featacts")) {
		printf("feature activations - give min,max,step: ");
		scanf("%d %d %d",&pmin,&pmax,&pstep);
		printfeatures(pmin,pmax,pstep,stdout);
		if (outfile) printfeatures(pmin,pmax,pstep,outfile);
	}
	else if (startsame(in,"expression")) {
		setex();
	}
	else if (startsame(in,"fileinput")) {
		fileinput(NONSTD);
	}
	else if (startsame(in,"inspecs")) {
		ttyprint("File name (- = stdin): ");
		fscanf(infp,"%s",in);
		inspecs(in);
	}
	else if (startsame(in,"infeatures")) {
		ttyprint("File name: ");
		fscanf(infp,"%s",in);
		infeats(in);
	}
	/* NOT PRESENTLY OPERATIVE -- JLM 10-5-82
	else if (startsame(in,"wsubset")) {
		wordsubset();
	}
	*/
	else if (startsame(in,"test")) {
		getstring("test string: ");
		test(in);
	}
	else if (startsame(in,"topdown")) {
		topdown();
	}
	else if (startsame(in,"output")) {
		setout();
	}
	else if (startsame(in,"ofile")) {
		getstring("give filename (or - for none): ");
		setoutfile(in);
	}
	else if (in[0] == '!') {
		system(&in[1]);
	}
	else if (in[0] == '?') {
		help();
	}
	else if (startsame(in,"help")) {
		help();
	}
	else if (startsame(in,"lexicon")) {
		getlex();
	}
	else if (startsame(in,"parameters")) {
		getpars();
	}
	else if (startsame(in,"quit")) {
		quit();
	}
	else if (startsame(in,"decay")) {
		ttyprint ("decay values:\n");
		getfloat(decay,NLEVS,"F","P","W");
	}
	else if (startsame(in,"alpha")) {
		ttyprint ("alpha values:\n");
		getfloat(alpha,NPARAMS,
		 "IF","FF","FP","PP","PW","WW","WP","PF","PFC");
	}
	else if (startsame(in,"gamma")) {
		ttyprint ("gamma values:\n");
		getfloat(ga,NLEVS,"F","P","W");
	}
	else if (startsame(in,"grace")) {
		ttyprint ("grace %s: change? ",(grace ? "ON" : "OFF"));
		fscanf(infp,"%s",in);
		if (in[0] == 'n') continue;
		grace = 1 - grace;
	}
	else if (startsame(in,"rest")) {
		tval = rest[W];
		ttyprint ("rest values:\n");
		getfloat(rest,NLEVS,"F","P","W");
		if (tval != rest[W]) {
			initialize();
		}
	}
	else if (startsame(in,"fweight")) {
		ttyprint ("fweight values:\n");
		getfloat(fweight,NCONTINS,
		"POW","PIT","VOI","ABT","DIF","ACU","CON","LWS",
		"MDS", "HIS","FT1","FT2","FT3","FT4","FT5","FT6");
	}
	else if (startsame(in,"pthresh")) {
		ttyprint ("pthresh values:\n");
		getfloat(pthresh,NLEVS,"F","P","W");
	}
	else if (startsame(in,"nreps")) {
		ttyprint ("%d nreps: change? ",nreps);
		fscanf(infp,"%s",in);
		if (in[0] == 'n') continue;
		sscanf(in,"%d",&nreps);
	}
	else if (startsame(in,"pfreq")) {
		ttyprint ("%d pfreq: change? ",printfreq);
		fscanf(infp,"%s",in);
		if (in[0] == 'n') continue;
		sscanf(in,"%d",&printfreq);
	}
	else if (startsame(in,"summarypr")) {
		ttyprint("give min, max, and step: ");
		fscanf(infp,"%d %d %d",&pmin,&pmax,&pstep);
		summarypr(pmin,pmax,pstep,stdout);
		if (outfile) summarypr(pmin,pmax,pstep,outfile);
	}
	else if (startsame(in,"spointers")) {
		qsort(wordptr,nwptrs,sizeof(struct word *),ecomp);
	}
	else if (startsame(in,"sinspec")) {
		sinspec();
	}
	else if (startsame(in,"sfeatures")) {
		ttyprint("file name: ");
		fscanf(infp,"%s",in);
		sfeatures(in);
	}
	else if (startsame(in,"dinspec")) {
		dinspec();
	}
	else if (startsame(in,"acoustinput")) {
		ttyprint("give min, max, and step: ");
		fscanf(infp,"%d %d %d",&pmin,&pmax,&pstep);
		acoustinput(pmin,pmax,pstep,stdout);
		if (outfile) acoustinput(pmin,pmax,pstep,outfile);
	}
	else if (startsame(in,"sumopt")) {
		ttyprint ("summaryprint %s: change? ",(sumflag ? "ON" : "OFF"));
		fscanf(infp,"%s",in);
		if (in[0] == 'n') continue;
		sumflag = 1 - sumflag;
	}
	else if (startsame(in,"echooutput")) {
		ttyprint ("echooutput %s: change? ",(echoflag ? "ON" : "OFF"));
		fscanf(infp,"%s",in);
		if (in[0] == 'n') continue;
		echoflag = 1 - echoflag;
	}
	else if (startsame(in,"min")) {
		ttyprint ("min = ");
		getval(&min);
	}
	else if (startsame(in,"max")) {
		ttyprint ("max = ");
		getval(&max);
	}
	else if (startsame(in,"windowcent")) {
		ttyprint ("windowcent = ");
		getval(&windowcent);
	}
	else if (startsame(in,"wbase")) {
		ttyprint ("wbase = ");
		getval(&wbase);
	}
	else if (startsame(in,"wchange")) {
		ttyprint ("wchange = ");
		getval(&wchange);
	}
	else if (startsame(in,"wgain")) {
		ttyprint ("wgain = ");
		getval(&wgain);
	}
	else if (startsame(in,"wramp")) {
		ttyprint ("wramp = ");
		getval(&wramp);
	}
	else if (startsame(in,"imax")) {
		ttyprint ("imax = ");
		getval(&imax);
	}
	else if (startsame(in,"freqscale")) {
		ttyprint ("freqscale = ");
		tval = fscale;
		getval(&fscale);
		if (tval != fscale) {
		    initialize();
		}
	}
	else if (startsame(in,"abort")) {
		abort();	/* to get a core dump for sdb */
	}
	else {
		printf("Unrecognized request: For help type ?.\n");
		if (infp != stdin) fileinput(STD);
	}
	wait(0);
}
}