Beispiel #1
0
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// comparePlayerData():
//      Compares two playerDataT structs based on their tournament score.
int
comparePlayerData (playerDataT * p1, playerDataT * p2, crosstableSortT option)
{
    int result = 0;
    switch (option) {
    case CROSSTABLE_SortScore:  // Sort by highest score, then fewest games:
        result = p2->score - p1->score;
        if (result == 0) { result = p1->gameCount - p2->gameCount; }
        if (result == 0) { result = p2->tiebreak - p1->tiebreak; }
        break;

    case CROSSTABLE_SortName:
        result = strCompare(p1->name, p2->name);
        break;

    case CROSSTABLE_SortElo:
        result = p2->elo - p1->elo;
        break;

    case CROSSTABLE_SortCountry:
        result = strCompare(p1->country, p2->country);
        break;
    }
    return result;
}
Beispiel #2
0
int strCompare(char* str1, char* str2) {

	//End scenario
	if (str1[0] == 0 && str2[0] == 0) {return 0;}

	//Result variable 
	int result = 0;

	//We do recursion until we reach the end of both strings 
	if (str1[0]!= 0 && str2[0]!=0){ result = strCompare(str1 + 1, str2 + 1);}
	else if (str1[0] == 0) {result = strCompare(str1, str2 + 1);}
	else if (str2[0] == 0) {result = strCompare(str1+1, str2);}

	//If past match was equal, we check if stll equal or return less or more 
	if (result == 0) {
		if (str1[0] == str2[0]) { return 0; }
		else if (str1[0] < str2[0]) { return -1; }
		else { return 1; }
	}
	//If currently equal, but the previous was not, we return the result 
	else if (str1[0] == str2[0]) {
		return result;
	}

	//Last case, if not equal, then check if for less or more 
	else {
		if (str1[0] < str2[0]) { return -1; }
		else { return 1; }
	}
	
}
Beispiel #3
0
bool AddTrait (CNPWorld *pWorld, 
			   CXMLElement *pTraitTable, 
			   CXMLElement *pTrait, 
			   CSymbolTable &Symbols)
	{
	int i;

	//	First check to see if the world has any of the traits
	//	listed in the "unless" sections

	for (i = 0; i < pTrait->GetContentElementCount(); i++)
		{
		CXMLElement *pUnless = pTrait->GetContentElement(i);
		if (strCompare(pUnless->GetTag(), CONSTLIT("Unless")) != 0)
			continue;

		//	If the world has the prohibited trait then we cannot
		//	add the desired trait.

		if (pWorld->HasTrait(GetSymbolicAttribute(Symbols, pUnless, CONSTLIT("Trait"))))
			return false;
		}

	//	Add the trait

	pWorld->SetTrait(GetSymbolicAttribute(Symbols, pTrait, CONSTLIT("Trait")));

	//	Add any traits that are implied by this trait

	for (i = 0; i < pTrait->GetContentElementCount(); i++)
		{
		CXMLElement *pImply = pTrait->GetContentElement(i);
		if (strCompare(pImply->GetTag(), CONSTLIT("Imply")) != 0)
			continue;

		//	Random chance of actually having this trait

		if (mathRandom(1, 100) > pImply->GetAttributeInteger(CONSTLIT("Prob")))
			continue;

		//	If we already have this trait the don't bother

		if (pWorld->HasTrait(GetSymbolicAttribute(Symbols, pImply, CONSTLIT("Trait"))))
			continue;

		//	Look for the implied trait in the table

		CXMLElement *pNewTrait = FindTraitInTable(pTraitTable, pImply->GetAttribute(CONSTLIT("Trait")));

		//	Add it. Note that we don't care if we cannot

		if (pNewTrait)
			AddTrait(pWorld, pTraitTable, pNewTrait, Symbols);
		}

	return true;
	}
Beispiel #4
0
void
Crosstable::PrintPlayer (DString * dstr, playerDataT * pdata)
{
    char stemp[1000];
    if (OutputFormat == CROSSTABLE_Hypertext) {
        sprintf (stemp, "<pi %s>", pdata->name);
        dstr->Append (stemp);
    }
    sprintf (stemp, "%-*s ", LongestNameLen, pdata->name);
    dstr->Append (StartCol, stemp, EndCol);

    if (PrintRatings) {
        if (pdata->elo) {
            sprintf (stemp, "%4u ", pdata->elo);
        } else {
	    if (OutputFormat == CROSSTABLE_Html) {
	      strcpy (stemp, "  -  ");
	    } else {
	      strcpy (stemp, "     ");
	    }
        }
        dstr->Append (StartRightCol, stemp, EndRightCol);
    }

    // if exporting to html, don't print blank fields
    //   as firefox doesn't make a grid box for blanks S.A.

    if (PrintTitles) {
	if (OutputFormat == CROSSTABLE_Html && !strCompare(pdata->title,"")) {
	  sprintf (stemp, " -  ");
	} else {
	  sprintf (stemp, "%3s ", pdata->title);
	}
        dstr->Append (StartCol, stemp, EndCol);
    }
    if (PrintAges) {
        if (pdata->ageInYears == 0) {
	    if (OutputFormat == CROSSTABLE_Html) {
	      sprintf (stemp, " -  ");
	    } else {
	      strCopy (stemp, "    ");
	    }
        } else {
            sprintf (stemp, "%3d ", pdata->ageInYears);
        }
        dstr->Append (StartCol, stemp, EndCol);
    }
    if (PrintCountries) {
	if (OutputFormat == CROSSTABLE_Html && !strCompare(pdata->country,"")) {
	  sprintf (stemp, " -  ");
	} else {
	  sprintf (stemp, "%-3s ", pdata->country);
	}
        dstr->Append (StartCol, stemp, EndCol);
    }
    if (OutputFormat == CROSSTABLE_Hypertext) { dstr->Append ("</pi>"); }
}
Beispiel #5
0
void test_strCompare()
{
  char *first = "ab";
  char *second = "ab";
  //int equal = stringCompare(first, second);
  //printf("*STR equal x? %d\n", equal);
  TEST_ASSERT_EQUAL(0,strCompare(first, second));
}
Beispiel #6
0
bool AtrmMotors :: isExecute(const char* cmdName, const int argc, char * const argv[], AStream *stream)
{
	char szName[MAX_TERMINAL_BUFFER];
	getCommandName(szName);
	if (strCompare(cmdName, szName))
	{
		execute(argc, argv, stream);
		return true;
	}
	return false;
}
Beispiel #7
0
/**
 * Chooses which I/O redirection to perform and sends arguments based on that
 * to handleRedirection(). If there is no redirection specified in the command,
 * nothing will happen.
 *
 * @param tokens  A character string array containing the tokens from parsing
 *
 * @returns nothing
 */
void redirect(char** tokens)
{
    for(int i = 0; tokens[i] != NULL; i++)
    {
        if(strCompare(tokens[i], ">"))
        {
            handleRedirection(tokens, &i, 1, O_CREAT | O_WRONLY | O_TRUNC);
        }

        if(strCompare(tokens[i], ">>"))
        {
            handleRedirection(tokens, &i, 1, O_WRONLY | O_APPEND);
        }

        if(strCompare(tokens[i], "<"))
        {
            handleRedirection(tokens, &i, 0, O_RDONLY);
        }
    }
}
Beispiel #8
0
CXMLElement *FindTraitInTable (CXMLElement *pTraitTable, const CString &sTrait)
	{
	for (int i = 0; i < pTraitTable->GetContentElementCount(); i++)
		{
		CXMLElement *pTrait = pTraitTable->GetContentElement(i);

		if (strCompare(pTrait->GetAttribute(CONSTLIT("Trait")), sTrait) == 0)
			return pTrait;
		}

	return NULL;
	}
/*********************************************************************************************************************
                                          strCompare
This function uses recursion to compare strings. The function returns -1 if str1 is less than str2, returns 0 if the
two strings are equal, and returns 1 if str1 is greater than str2. ASCII value is used to compare each character.
*********************************************************************************************************************/
int strCompare(char* str1, char* str2)
{
	if (str1[0] == 0 && str2[0] == 0)	// Both null terminators, strings must be equal
	{
		return 0;
	}
	if (str1[0] < str2[0])				// str1 is "less than" str2
	{
		return -1;
	}
	else if (str1[0] > str2[0])			// str1 is "greater than" str2
	{
		return 1;
	}
	if (str1[0] == str2[0])				// First character of both strings are equal, check rest
	{
		return strCompare(str1 + 1, str2 + 1);
	}
}
Beispiel #10
0
/* This function (for internal use only) locates an element in an
** hash table that matches the given key.  The hash for this key has
** already been computed and is passed as the 4th parameter.
*/
static HashElem *findElementGivenHash(
  const Hash *pH,     /* The pH to be searched */
  const void *pKey,   /* The key we are searching for */
  int nKey,
  int h               /* The hash for this key. */
){
  HashElem *elem;                /* Used to loop thru the element list */
  int count;                     /* Number of elements left to test */

  if( pH->ht ){
    struct _ht *pEntry = &pH->ht[h];
    elem = pEntry->chain;
    count = pEntry->count;
    while( count-- && elem ){
      if( strCompare(elem->pKey,elem->nKey,pKey,nKey)==0 ){ 
        return elem;
      }
      elem = elem->next;
    }
  }
  return 0;
}
Beispiel #11
0
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// strCompareRound():
//    String comparison function for round names. Sorts by the integer
//    number at the start of each string first.
int
strCompareRound (const char * sleft, const char * sright)
{
    int ileft = strGetInteger (sleft);
    int iright = strGetInteger (sright);
    int diff = ileft - iright;
    if (diff != 0) { return diff; }

    // Now check if both strings are equal up to the first dot.
    // If so, do an integer comparison after the ".":

    bool equalUpToDot = false;
    const char * templeft = sleft;
    const char * tempright = sright;

    while (true) {
        char leftc = *templeft;
        char rightc = *tempright;
        if (leftc == 0  ||  rightc == 0) { break; }
        if (leftc != rightc) { break; }
        if (leftc == '.'  &&  rightc == '.') { equalUpToDot = true; break; }
        templeft++;
        tempright++;
    }

    if (equalUpToDot) {
        templeft++;
        tempright++;
        // Now templeft and tempright point to the first character
        // after each dot.
        ileft = strGetInteger (templeft);
        iright = strGetInteger(tempright);
        diff = ileft - iright;
        if (diff != 0) { return diff; }
    }
    
    // Give up on integer comparisons and do a regular string comparison:
    return strCompare (sleft, sright);
}
int equal(int idx, char** out, char*** ans) {
	if (out == NULL)
		return 0;
		
	char** sol = ans[idx];
	
	int i = 0;
	
	while (sol[i]) {
		if (out[i] == NULL)
			return 0;

		if (!strCompare(sol[i], out[i])) 
			return 0;

		++i;
	}
	
	if (out[i])				// need to check in case their solution is not NULL terminated
		return 0;
		
	return 1;
}
int strCompare(char* str1, char* str2) {
	if (str1[0] == str2[0]) {
		if (str1[0] == 0) {
			return 0;
		}
	}
	if (str1[0] != str2[0]) {
		if (str1[0] > str2[0]) {
			return 1;
		}
		else {
			return -1;
		}

		}
	else {
		str1++;
		str2++;
		int t = strCompare(str1, str2);
		return t;
	}
	
	}
Beispiel #14
0
bool CDlgFileAssoc::IsExtAssignedDyn(LPWSTR extName) {

	wchar_t szKeyName[20];
	wchar_t szKeyUpr[20];
	wchar_t szKeyDesc[50];

	wcscpy(szKeyUpr, extName);
	wcsupr(szKeyUpr);

	wsprintf(szKeyName, L".%s", extName);
	wsprintf(szKeyDesc, L"Nitrogen%sFile", szKeyUpr);

	bool result = false;

	HKEY hKey;
	wchar_t buf[100];
	DWORD ln = 100;

	if (RegOpenKeyExW(HKEY_CLASSES_ROOT, szKeyName, 0, 0, &hKey) == ERROR_SUCCESS) {
		if ((RegQueryValueExW(hKey, NULL, NULL, NULL, (BYTE*)&buf, &ln) == ERROR_SUCCESS) && (strCompare(buf, szKeyDesc) == 0)) {
			result = true;
		}
		RegCloseKey(hKey);
	}

	return result;

}
Beispiel #15
0
/**
 * Parses a given command into an array of tokens using strtok()
 *
 * @param command   The command that was entered at the prompt
 * @param arguments An array in which to store the results of parsing
 * @param env       The shell's internal environnment
 *
 * @returns A pointer to an array of tokens obtained from the given command.
 *
 *          i.e. `ls -la` will be stored as { "ls", "-la", NULL }
 */
void parseCommand(char* command, char** arguments, shellInternal* env)
{
    char* tokenArray[strlen(command)];
    char* token = strtok(command, " ");

    int i = 0;

    while(token)
    {
        char* start = token;

        while(*(token++))
        {
            if(*token == '\n')
            {
                *token = '\0';
            }
        }

        // Reset to the start of the string
        token = start;

        tokenArray[i] = token;

        token = strtok(NULL, " ");
        i++;
    }

    tokenArray[i] = NULL;

    env->numberOfPipes = 0;

    for(i = 0; tokenArray[i] != NULL; i++)
    {
        // Exclude empty strings from the returned array
        // This could cause commands such as `ls` to be passed nothing if there
        // are spaces after it
        if(!strCompare(tokenArray[i], ""))
        {
            if(!strCompare(tokenArray[i], "&") && !strCompare(tokenArray[i], "|"))
            {
		if(tokenArray[i][0] == '$')
		{
		    if(strCompare(tokenArray[i], "$0"))
		    {
		        tokenArray[i] = "msh";
		    }
		    else
		    {
			tokenArray[i] = "";
		    }
		}

                arguments[i] = tokenArray[i];
            }
            else
            {
                if(strCompare(tokenArray[i], "|"))
                {
                    env->piping = 1;
		    env->numberOfPipes++;
                }
                else if(strCompare(tokenArray[i], "&"))
                {
                    env->background = 1;
                }

                arguments[i] = NULL;
            }
        }
    }

    arguments[i] = NULL;
}
Beispiel #16
0
ERROR recursive_interpret(FUNCTION_PTR function, STACK_PTR stack)
{
	
// 	fprintf(stderr,"Zavolana funkce: %d\n",function);
	LIST_NODE_PTR instr_node = function->instructions.begin;
	ERROR err = E_OK;
	
	// ----- Priprava promenych ------
	INSTRUCTION_PTR instruction = NULL;
	int str_from,str_to,tmp_count;
	STRING tmp_string;
	
	STACK_PTR tmp_stack;
	tmp_stack = gcMalloc(sizeof(struct STACK));
	stackInit(tmp_stack);
	
	// NULL SYMBOL
	ITEMPTR null_item;
	null_item = gcMalloc(sizeof(struct ITEM));
	null_item->type = TYPE_NULL;
	
	SYMBOL* null_symbol;
	null_symbol = gcMalloc(sizeof(struct SYMBOL));
	null_symbol->type = TYPE_NULL;
	null_symbol->items = null_item;
	
	// TMP SYMBOL
	ITEMPTR tmp_item;
	
	SYMBOL* tmp_symbol;
	
    SYMBOL* op1 = NULL;
    SYMBOL* op2 = NULL;
    SYMBOL* op3 = NULL;
	
	FUNCTION_PTR tmp_function = NULL;
	
	while(instr_node != NULL && err == E_OK)
	{
		instruction = instr_node->value;
		
		tmp_item = gcMalloc(sizeof(struct ITEM));
		tmp_symbol = gcMalloc(sizeof(struct SYMBOL));
		tmp_symbol->items = tmp_item;
	
		op1 = (SYMBOL*) instruction->operand1;
		op2 = (SYMBOL*) instruction->operand2;
		op3 = (SYMBOL*) instruction->destionation;
		
		fprintf(stderr,"while interpret : %d (%s)\n",instruction->type, debugInstruction(instruction->type));
		
		switch(instruction->type)
		{
			case INSTRUCTION_NOP:
			break;
			
			case INSTRUCTION_MOV:
				if ((err = op_check(op1,'O')) != E_OK)
					return err;
				if ((err = op_check(op2,'I')) != E_OK)
					return err;
				
				data_copy(op2, op1);
				op1->filgy = true;
			break;
			
			case INSTRUCTION_LOAD_NULL:
				if ((err = op_check(op1,'O')) != E_OK)
					return err;
				if ((err = op_check(op2,'O')) != E_OK)
					return err;
				if ((err = op_check(op3,'O')) != E_OK)
					return err;
				
				data_copy(null_symbol,op1);
				data_copy(null_symbol,op2);
				data_copy(null_symbol,op3);
				op1->filgy = true;
				op2->filgy = true;
				op3->filgy = true;
			break;
			
			case INSTRUCTION_ADDITION:
				if ((err = op_check(op1,'O')) != E_OK)
					return err;
				if ((err = op_check(op2,'I')) != E_OK)
					return err;
				if ((err = op_check(op3,'I')) != E_OK)
					return err;
				
				if(op2->items->type == TYPE_DIGIT_INT && op3->items->type == TYPE_DIGIT_INT)
				{
					tmp_symbol->items->type = TYPE_DIGIT_INT;
					tmp_symbol->items->value.valInt = op2->items->value.valInt + op3->items->value.valInt;
					data_copy(tmp_symbol,op1); // from, to
				}
				else if(op2->items->type == TYPE_DIGIT_INT && op3->items->type == TYPE_DIGIT_DOUBLE)
				{
					tmp_symbol->items->type = TYPE_DIGIT_DOUBLE;
					tmp_symbol->items->value.valDouble = op2->items->value.valInt + op3->items->value.valDouble;
					data_copy(tmp_symbol,op1); // from, to
				}
				else if(op2->items->type == TYPE_DIGIT_DOUBLE && op3->items->type == TYPE_DIGIT_INT)
				{
					tmp_symbol->items->type = TYPE_DIGIT_DOUBLE;
					tmp_symbol->items->value.valDouble = op2->items->value.valDouble + op3->items->value.valInt;
					data_copy(tmp_symbol,op1); // from, to
				}
				else if(op2->items->type == TYPE_DIGIT_DOUBLE && op3->items->type == TYPE_DIGIT_DOUBLE)
				{
					tmp_symbol->items->type = TYPE_DIGIT_DOUBLE;
					tmp_symbol->items->value.valDouble = op2->items->value.valDouble + op3->items->value.valDouble;
					data_copy(tmp_symbol,op1); // from, to
				}
				else if(op2->items->type == TYPE_STRING && op3->items->type == TYPE_STRING)
				{
					tmp_symbol->items->type = TYPE_STRING;
					
					strConcatenate(&tmp_symbol->items->value.valString, &op2->items->value.valString);
					strConcatenate(&tmp_symbol->items->value.valString, &op3->items->value.valString);
					
					data_copy(tmp_symbol,op1); // from, to
				}
				else if(op2->items->type == TYPE_STRING && op3->items->type == TYPE_DIGIT_INT)
				{
					STRING new_string;
					char* new_char_string = gcMalloc(sizeof(char*));;
					sprintf(new_char_string, "%d", op3->items->value.valInt);
					strInitRaw(&new_string, new_char_string);
					
					tmp_symbol->items->type = TYPE_STRING;
					
					strConcatenate(&tmp_symbol->items->value.valString, &op2->items->value.valString);
					strConcatenate(&tmp_symbol->items->value.valString, &op3->items->value.valString);
					
					data_copy(tmp_symbol,op1); // from, to
				}
				else if(op2->items->type == TYPE_STRING && op3->items->type == TYPE_DIGIT_DOUBLE)
				{
					STRING new_string;
					char* new_char_string = gcMalloc(sizeof(char*));
					sprintf(new_char_string, "%lf", op3->items->value.valDouble);
					strInitRaw(&new_string, new_char_string);
					
					tmp_symbol->items->type = TYPE_STRING;
					
					strConcatenate(&tmp_symbol->items->value.valString, &op2->items->value.valString);
					strConcatenate(&tmp_symbol->items->value.valString, &op3->items->value.valString);
					
					data_copy(tmp_symbol,op1); // from, to
				}
				else
					return E_SEMANTIC_TYPE_MISMATCH;
				op1->filgy = true;
				tmp_symbol = NULL;
			break;
			
			case INSTRUCTION_SUBSTRACTION:
				if ((err = op_check(op1,'O')) != E_OK)
					return err;
				if ((err = op_check(op2,'I')) != E_OK)
					return err;
				if ((err = op_check(op3,'I')) != E_OK)
					return err;
				
				if(op2->items->type == TYPE_DIGIT_INT && op3->items->type == TYPE_DIGIT_INT)
				{
					tmp_symbol->items->type = TYPE_DIGIT_INT;
					tmp_symbol->items->value.valInt = op2->items->value.valInt - op3->items->value.valInt;
					
					data_copy(tmp_symbol,op1); // from, to
				}
				else if(op2->items->type == TYPE_DIGIT_INT && op3->items->type == TYPE_DIGIT_DOUBLE)
				{
					tmp_symbol->items->type = TYPE_DIGIT_DOUBLE;
					tmp_symbol->items->value.valDouble = op2->items->value.valInt - op3->items->value.valDouble;
					data_copy(tmp_symbol,op1); // from, to
				}
				else if(op2->items->type == TYPE_DIGIT_DOUBLE && op3->items->type == TYPE_DIGIT_INT)
				{
					tmp_symbol->items->type = TYPE_DIGIT_DOUBLE;
					tmp_symbol->items->value.valDouble = op2->items->value.valDouble - op3->items->value.valInt;
					data_copy(tmp_symbol,op1); // from, to
				}
				else if(op2->items->type == TYPE_DIGIT_DOUBLE && op3->items->type == TYPE_DIGIT_DOUBLE)
				{
					tmp_symbol->items->type = TYPE_DIGIT_DOUBLE;
					tmp_symbol->items->value.valDouble = op2->items->value.valDouble - op3->items->value.valDouble;
					data_copy(tmp_symbol,op1); // from, to
				}
				else
					return E_SEMANTIC_TYPE_MISMATCH;
				op1->filgy = true;
				tmp_symbol = NULL;
			break;
			
			case INSTRUCTION_MULTIPLICATION:
				if ((err = op_check(op1,'O')) != E_OK)
					return err;
				if ((err = op_check(op2,'I')) != E_OK)
					return err;
				if ((err = op_check(op3,'I')) != E_OK)
					return err;
				
				if(op2->items->type == TYPE_DIGIT_INT && op3->items->type == TYPE_DIGIT_INT)
				{
					tmp_symbol->items->type = TYPE_DIGIT_INT;
					tmp_symbol->items->value.valInt = op2->items->value.valInt * op3->items->value.valInt;
					data_copy(tmp_symbol,op1); // from, to
				}
				else if(op2->items->type == TYPE_DIGIT_INT && op3->items->type == TYPE_DIGIT_DOUBLE)
				{
					tmp_symbol->items->type = TYPE_DIGIT_DOUBLE;
					tmp_symbol->items->value.valDouble = ((double)op2->items->value.valInt) * op3->items->value.valDouble;
					data_copy(tmp_symbol,op1); // from, to
				}
				else if(op2->items->type == TYPE_DIGIT_DOUBLE && op3->items->type == TYPE_DIGIT_INT)
				{
					tmp_symbol->items->type = TYPE_DIGIT_DOUBLE;
					tmp_symbol->items->value.valDouble = op2->items->value.valDouble * ((double)op3->items->value.valInt);
					data_copy(tmp_symbol,op1); // from, to
				}
				else if(op2->items->type == TYPE_DIGIT_DOUBLE && op3->items->type == TYPE_DIGIT_DOUBLE)
				{
					tmp_symbol->items->type = TYPE_DIGIT_DOUBLE;
					tmp_symbol->items->value.valDouble = op2->items->value.valDouble * op3->items->value.valDouble;
					data_copy(tmp_symbol,op1); // from, to
				}
				else
					return E_SEMANTIC_TYPE_MISMATCH;
				op1->filgy = true;
				tmp_symbol = NULL;
			break;
			
			case INSTRUCTION_DIVISION:
				if ((err = op_check(op1,'O')) != E_OK)
					return err;
				if ((err = op_check(op2,'I')) != E_OK)
					return err;
				if ((err = op_check(op3,'I')) != E_OK)
					return err;
				
				if(op2->items->type == TYPE_DIGIT_INT && op3->items->type == TYPE_DIGIT_INT)
				{
					if(op3->items->value.valInt == 0)
						return E_SEMANTIC_ZERO_DIV;
					tmp_symbol->items->type = TYPE_DIGIT_INT;
					tmp_symbol->items->value.valInt = op2->items->value.valInt / op3->items->value.valInt;
					data_copy(tmp_symbol,op1); // from, to
				}
				else if(op2->items->type == TYPE_DIGIT_INT && op3->items->type == TYPE_DIGIT_DOUBLE)
				{
					if(op3->items->value.valDouble == 0.0)
						return E_SEMANTIC_ZERO_DIV;
					tmp_symbol->items->type = TYPE_DIGIT_DOUBLE;
					tmp_symbol->items->value.valDouble = op2->items->value.valInt / op3->items->value.valDouble;
					data_copy(tmp_symbol,op1); // from, to
				}
				else if(op2->items->type == TYPE_DIGIT_DOUBLE && op3->items->type == TYPE_DIGIT_INT)
				{
					if(op3->items->value.valInt == 0)
						return E_SEMANTIC_ZERO_DIV;
					tmp_symbol->items->type = TYPE_DIGIT_DOUBLE;
					tmp_symbol->items->value.valDouble = op2->items->value.valDouble / op3->items->value.valInt;
					data_copy(tmp_symbol,op1); // from, to
				}
				else if(op2->items->type == TYPE_DIGIT_DOUBLE && op3->items->type == TYPE_DIGIT_DOUBLE)
				{
					if(op3->items->value.valDouble == 0.0)
						return E_SEMANTIC_ZERO_DIV;
					tmp_symbol->items->type = TYPE_DIGIT_DOUBLE;
					tmp_symbol->items->value.valDouble = op2->items->value.valDouble / op3->items->value.valDouble;
					data_copy(tmp_symbol,op1); // from, to
				}
				else
					return E_SEMANTIC_TYPE_MISMATCH;
				op1->filgy = true;
				tmp_symbol = NULL;
			break;
			
			case INSTRUCTION_LESS:
				if ((err = op_check(op1,'O')) != E_OK)
					return err;
				if ((err = op_check(op2,'I')) != E_OK)
					return err;
				if ((err = op_check(op3,'I')) != E_OK)
					return err;
				
				tmp_symbol->items->type = TYPE_BOOL;
				if(op2->items->type == TYPE_DIGIT_INT && op3->items->type == TYPE_DIGIT_INT)
				{
					tmp_symbol->items->value.valBool = op2->items->value.valInt < op3->items->value.valInt;
				}
				else if(op2->items->type == TYPE_DIGIT_DOUBLE && op3->items->type == TYPE_DIGIT_DOUBLE)
				{
					tmp_symbol->items->value.valBool = op2->items->value.valDouble < op3->items->value.valDouble;
				}
				else if(op2->items->type == TYPE_STRING && op3->items->type == TYPE_STRING)
				{
					tmp_symbol->items->value.valBool = op2->items->value.valString.used < op3->items->value.valString.used;
				}
				else
					return E_SEMANTIC_TYPE_MISMATCH;
				data_copy(tmp_symbol,op1);
				tmp_symbol = NULL;
			break;
			
			case INSTRUCTION_GREATER:
				if ((err = op_check(op1,'O')) != E_OK)
					return err;
				if ((err = op_check(op2,'I')) != E_OK)
					return err;
				if ((err = op_check(op3,'I')) != E_OK)
					return err;
				
				tmp_symbol->items->type = TYPE_BOOL;
				if(op2->items->type == TYPE_DIGIT_INT && op3->items->type == TYPE_DIGIT_INT)
				{
					tmp_symbol->items->value.valBool = op2->items->value.valInt > op3->items->value.valInt;
				}
				else if(op2->items->type == TYPE_DIGIT_DOUBLE && op3->items->type == TYPE_DIGIT_DOUBLE)
				{
					tmp_symbol->items->value.valBool = op2->items->value.valDouble > op3->items->value.valDouble;
				}
				else if(op2->items->type == TYPE_STRING && op3->items->type == TYPE_STRING)
				{
					tmp_symbol->items->value.valBool = op2->items->value.valString.used > op3->items->value.valString.used;
				}
				else
					return E_SEMANTIC_TYPE_MISMATCH;
				data_copy(tmp_symbol,op1);
				tmp_symbol = NULL;
			break;
			
			case INSTRUCTION_LESS_EQUAL:
				if ((err = op_check(op1,'O')) != E_OK)
					return err;
				if ((err = op_check(op2,'I')) != E_OK)
					return err;
				if ((err = op_check(op3,'I')) != E_OK)
					return err;
				
				tmp_symbol->items->type = TYPE_BOOL;
				if(op2->items->type == TYPE_DIGIT_INT && op3->items->type == TYPE_DIGIT_INT)
				{
					tmp_symbol->items->value.valBool = op2->items->value.valInt <= op3->items->value.valInt;
				}
				else if(op2->items->type == TYPE_DIGIT_DOUBLE && op3->items->type == TYPE_DIGIT_DOUBLE)
				{
					tmp_symbol->items->value.valBool = op2->items->value.valDouble <= op3->items->value.valDouble;
				}
				else if(op2->items->type == TYPE_STRING && op3->items->type == TYPE_STRING)
				{
					tmp_symbol->items->value.valBool = op2->items->value.valString.used <= op3->items->value.valString.used;
				}
				else
					return E_SEMANTIC_TYPE_MISMATCH;
				data_copy(tmp_symbol,op1);
				tmp_symbol = NULL;
			break;
			
			case INSTRUCTION_GREATER_EQUAL:
				if ((err = op_check(op1,'O')) != E_OK)
					return err;
				if ((err = op_check(op2,'I')) != E_OK)
					return err;
				if ((err = op_check(op3,'I')) != E_OK)
					return err;
				
				tmp_symbol->items->type = TYPE_BOOL;
				if(op2->items->type == TYPE_DIGIT_INT && op3->items->type == TYPE_DIGIT_INT)
				{
					tmp_symbol->items->value.valBool = op2->items->value.valInt >= op3->items->value.valInt;
				}
				else if(op2->items->type == TYPE_DIGIT_DOUBLE && op3->items->type == TYPE_DIGIT_DOUBLE)
				{
					tmp_symbol->items->value.valBool = op2->items->value.valDouble >= op3->items->value.valDouble;
				}
				else if(op2->items->type == TYPE_STRING && op3->items->type == TYPE_STRING)
				{
					tmp_symbol->items->value.valBool = op2->items->value.valString.used >= op3->items->value.valString.used;
				}
				else
					return E_SEMANTIC_TYPE_MISMATCH;
				data_copy(tmp_symbol,op1);
				tmp_symbol = NULL;
			break;
			
			case INSTRUCTION_EQUAL:
				if ((err = op_check(op1,'O')) != E_OK)
					return err;
				if ((err = op_check(op2,'I')) != E_OK)
					return err;
				if ((err = op_check(op3,'I')) != E_OK)
					return err;
				
				tmp_symbol->items->type = TYPE_BOOL;
				if(op2->items->type == TYPE_DIGIT_INT && op3->items->type == TYPE_DIGIT_INT)
				{
					tmp_symbol->items->value.valBool = op2->items->value.valInt == op3->items->value.valInt;
				}
				else if(op2->items->type == TYPE_DIGIT_DOUBLE && op3->items->type == TYPE_DIGIT_DOUBLE)
				{
					tmp_symbol->items->value.valBool = op2->items->value.valDouble == op3->items->value.valDouble;
				}
				else if(op2->items->type == TYPE_STRING && op3->items->type == TYPE_STRING)
				{
					tmp_symbol->items->value.valBool = op2->items->value.valString.used == op3->items->value.valString.used;
				}
				else
					tmp_symbol->items->value.valBool = false;
				data_copy(tmp_symbol,op1);
				tmp_symbol = NULL;
			break;
			
			case INSTRUCTION_NOT_EQUAL:
				if ((err = op_check(op1,'O')) != E_OK)
					return err;
				if ((err = op_check(op2,'I')) != E_OK)
					return err;
				if ((err = op_check(op3,'I')) != E_OK)
					return err;
				
				tmp_symbol->items->type = TYPE_BOOL;				
				if(op2->items->type == TYPE_DIGIT_INT && op3->items->type == TYPE_DIGIT_INT)
				{
					tmp_symbol->items->value.valBool = op2->items->value.valInt != op3->items->value.valInt;
				}
				else if(op2->items->type == TYPE_DIGIT_DOUBLE && op3->items->type == TYPE_DIGIT_DOUBLE)
				{
					tmp_symbol->items->value.valBool = op2->items->value.valDouble != op3->items->value.valDouble;
				}
				else if(op2->items->type == TYPE_STRING && op3->items->type == TYPE_STRING)
				{
					tmp_symbol->items->value.valBool = op2->items->value.valString.used != op3->items->value.valString.used;
					if(!tmp_symbol->items->value.valBool)
					{
						tmp_symbol->items->value.valBool = !strCompare(op2->items->value.valString, op3->items->value.valString.data);
					}
				}
				else
					tmp_symbol->items->value.valBool = false;
				data_copy(tmp_symbol,op1);
				tmp_symbol = NULL;
			break;
			
			case INSTRUCTION_PUSH:
// 				printf("ahoj %d\n",op1->filgy);
				if ((err = op_check(op1,'I')) != E_OK)
					return err;
				
				stackPush(stack,op1);
			break;
			
			case INSTRUCTION_POP:
				if ((err = op_check(op1,'O')) != E_OK)
					return err;
				
				tmp_symbol = stackPop(stack);
				
				if(tmp_symbol == NULL){
					tmp_symbol = gcMalloc(sizeof(SYMBOL));
					tmp_symbol->items = gcMalloc(sizeof(ITEM));
					
					tmp_symbol->items->type = TYPE_NULL;
					tmp_symbol->filgy = true;
					
				}
				
				data_copy(tmp_symbol,op1);
				op1->filgy = true;
			break;
			
			case INSTRUCTION_CALL:
				if(op1 == NULL)
					return E_COMPILATOR;
				
				tmp_function = function;
				function = (FUNCTION_PTR)op1;
				
				err=recursive_interpret(function,stack);
				if (err != E_OK)
					return err;
				
				function = tmp_function;
			break;
			
			case INSTRUCTION_RETURN:
				return err;
			break;
			
			case INSTRUCTION_JUMP:
				if(op3 == NULL)
					return E_COMPILATOR;
				
				instr_node = function->instructions.begin;
				while(instr_node != (LIST_NODE_PTR)op3)
				{
					if(instr_node->next == NULL)
					{
						fprintf(stderr,"NENALEZENO!!!\n");
						fprintf(stderr,"NENALEZENO!!!\n");
						fprintf(stderr,"NENALEZENO!!!\n");
						break;
					}
					instr_node = instr_node->next;
				}
				continue;
			break;
			
			case INSTRUCTION_IF_JUMP:	
// 				if ((err = op_check(op2,'I')) != E_OK)
// 					return err;
				if(op3 == NULL)
					return E_COMPILATOR;
				
				if(op2->items->type == TYPE_BOOL)
				{
					if(!op2->items->value.valBool)
					{
						instr_node = function->instructions.begin;
						while(instr_node != (LIST_NODE_PTR)op3)
						{
							if(instr_node->next == NULL)
								break;
							instr_node = instr_node->next;
						}
						continue;						
					}
				}
// 				if(op2->items->type == TYPE_DIGIT_INT)
// 				{
// 					printf("AHOJ\n");
// 					if(!op2->items->value.valInt)
// 					{
// 						instr_node = function->instructions.begin;
// 						while(instr_node != (LIST_NODE_PTR)op3)
// 						{
// 							if(instr_node->next == NULL)
// 								break;
// 							instr_node = instr_node->next;
// 						}
// 						continue;						
// 					}
// 				}
			break;
			
			case INSTRUCTION_LABEL:
				
			break;
			
			case INSTRUCTION_BOOLVAL:
				if ((err = op_check(op1,'O')) != E_OK)
					return err;
				
				tmp_symbol = stackPop(stack);
				tmp_symbol->items = boolval(*tmp_symbol->items);
				
				data_copy(tmp_symbol,op1);
				op1->filgy = true;
				tmp_symbol = NULL;
			break;
			
			case INSTRUCTION_DOUBLEVAL:
				if ((err = op_check(op1,'O')) != E_OK)
					return err;
				
				tmp_symbol = stackPop(stack);
				tmp_symbol->items = doubleval(*tmp_symbol->items);
				if(tmp_symbol->items == NULL)
					return E_SEMANTIC_DOUBLEVAL;
				
				data_copy(tmp_symbol,op1);
				op1->filgy = true;
				tmp_symbol = NULL;
			break;
			
			case INSTRUCTION_INTVAL:	
				if ((err = op_check(op1,'O')) != E_OK)
					return err;
				
				op1 = stackPop(stack);
				if ((err = op_check(op1,'I')) != E_OK)
					return err;
				
				tmp_symbol->items = intval(*op1->items);
				data_copy(tmp_symbol,op1);
				op1->filgy = true;
				tmp_symbol = NULL;
			break;
			
			case INSTRUCTION_STRVAL:
				if ((err = op_check(op1,'O')) != E_OK)
					return err;
				
				tmp_symbol = stackPop(stack);
				tmp_symbol->items = strval(*tmp_symbol->items);
				
				data_copy(tmp_symbol,op1);
				op1->filgy = true;
				tmp_symbol = NULL;
			break;
			
			case INSTRUCTION_GET_STRING:
				if ((err = op_check(op1,'O')) != E_OK)
					return err;
				
				tmp_string = get_string();
				
				tmp_symbol->items->type = TYPE_STRING;
				strInit(&tmp_symbol->items->value.valString);
				strCopy(&tmp_string, &tmp_symbol->items->value.valString);
				
				data_copy(tmp_symbol, op1);
				op1->filgy = true;
				tmp_symbol = NULL;
			break;
			
			case INSTRUCTION_CONCATE:
				if ((err = op_check(op1,'O')) != E_OK)
					return err;
				if ((err = op_check(op2,'I')) != E_OK)
					return err;
				if ((err = op_check(op3,'I')) != E_OK)
					return err;
				
				if(op2->items->type == TYPE_STRING && op3->items->type == TYPE_STRING)
				{
					tmp_symbol->items->type = TYPE_STRING;
					strInit(&tmp_symbol->items->value.valString);
					strConcatenate(&tmp_symbol->items->value.valString, &op2->items->value.valString);
					strConcatenate(&tmp_symbol->items->value.valString, &op3->items->value.valString);
					data_copy(tmp_symbol,op1); // from, to
				}
				else if(op2->items->type == TYPE_STRING && op3->items->type == TYPE_DIGIT_INT)
				{
					STRING new_string;
					char* new_char_string = gcMalloc(sizeof(char*));
					sprintf(new_char_string, "%d", op3->items->value.valInt);
					strInitRaw(&new_string, new_char_string);
					
					tmp_symbol->items->type = TYPE_STRING;
					strConcatenate(&tmp_symbol->items->value.valString, &op2->items->value.valString);
					strConcatenate(&tmp_symbol->items->value.valString, &op3->items->value.valString);
					
					data_copy(tmp_symbol,op1); // from, to
				}
				else if(op2->items->type == TYPE_STRING && op3->items->type == TYPE_DIGIT_DOUBLE)
				{
					STRING new_string;
					char* new_char_string = gcMalloc(sizeof(char*));
					sprintf(new_char_string, "%lf", op3->items->value.valDouble);
					strInitRaw(&new_string, new_char_string);
					
					tmp_symbol->items->type = TYPE_STRING;
					
					strConcatenate(&tmp_symbol->items->value.valString, &op2->items->value.valString);
					strConcatenate(&tmp_symbol->items->value.valString, &op3->items->value.valString);
					
					data_copy(tmp_symbol,op1); // from, to
				}
				else
					return E_SEMANTIC_TYPE_MISMATCH;
				op1->filgy = true;
				tmp_symbol = NULL;
			break;
			
			case INSTRUCTION_PUT_STRING:
				if ((err = op_check(op1,'O')) != E_OK)
					return err;
				if (op2 == NULL)
					return E_COMPILATOR;
				
				// DODELAT VRACENI POCTU VYPSANYCH! DO OP1
				
				tmp_count = *((int*)op2);
				for(int i=0;i<tmp_count;i++)
				{
					tmp_symbol = stackPop(stack);
					if ((err = op_check(tmp_symbol,'I')) != E_OK)
						return err;
					stackPush(tmp_stack,tmp_symbol);
				}
				for(int i=0;i<tmp_count;i++)
				{
					tmp_symbol = stackPop(tmp_stack);
					if(tmp_symbol->items->type == 2)
						printf("%d",tmp_symbol->items->value.valInt);
					else if(tmp_symbol->items->type == 3)
						printf("%lf",tmp_symbol->items->value.valDouble);
					else if(tmp_symbol->items->type == 4)
						printf("%s",tmp_symbol->items->value.valString.data);
				}
				tmp_symbol = NULL;
			break;
			
			case INSTRUCTION_STRLEN:
				if ((err = op_check(op1,'O')) != E_OK)
					return err;
				if (op2 == NULL)
					return E_COMPILATOR;
				
				tmp_count = *((int*)op2);
				if (tmp_count != 1)
					return E_COMPILATOR;
				
				op1 = stackPop(stack);
				if ((err = op_check(op1,'I')) != E_OK)
					return err;
				tmp_symbol->items->type = TYPE_DIGIT_INT;
				tmp_symbol->items->value.valInt = my_strlen(op1->items->value.valString);
				
				data_copy(tmp_symbol, op1);
				op1->filgy = true;
				tmp_symbol = NULL;
			break;
			
			case INSTRUCTION_GET_SUBSTRING:
				if ((err = op_check(op1,'O')) != E_OK)
					return err;
				if (op2 == NULL)
					return E_COMPILATOR;
				tmp_count = *((int*)op2);
				if (tmp_count != 3)
					return E_COMPILATOR;
				
				// TO
				tmp_symbol = stackPop(stack);
				if ((err = op_check(tmp_symbol,'I')) != E_OK)
					return err;
				str_to = tmp_symbol->items->value.valInt;
				
				// FROM
				tmp_symbol = stackPop(stack);
				if ((err = op_check(tmp_symbol,'I')) != E_OK)
					return err;
				str_from = tmp_symbol->items->value.valInt;
				
				// STRING
				tmp_symbol = stackPop(stack);
				if ((err = op_check(tmp_symbol,'I')) != E_OK)
					return err;
				
				tmp_string = get_substring(tmp_symbol->items->value.valString,str_from,str_to,&err);
				if(err != E_OK)
					return err;
				
				tmp_symbol->items->type = TYPE_STRING;
				strCopy(&tmp_symbol->items->value.valString,&tmp_string);
				data_copy(tmp_symbol,op1);
				op1->filgy = true;
				tmp_symbol = NULL;
			break;
			
			case INSTRUCTION_FIND_STRING:
				if ((err = op_check(op1,'O')) != E_OK)
					return err;
				
				op2 = stackPop(stack);
				if ((err = op_check(op2,'I')) != E_OK)
					return err;
				
				op3 = stackPop(stack);
				if ((err = op_check(op1,'I')) != E_OK)
					return err;
				
				tmp_symbol->items->type = TYPE_DIGIT_INT;
				tmp_symbol->items->value.valInt = find_string(op3->items->value.valString, op2->items->value.valString);
				data_copy(tmp_symbol,op1);
				op1->filgy = true;
				tmp_symbol = NULL;
			break;
			
			case INSTRUCTION_SORT_STRING:
				if ((err = op_check(op1,'O')) != E_OK)
					return err;
				
				tmp_symbol = stackPop(stack);
				if ((err = op_check(tmp_symbol,'I')) != E_OK)
					return err;
				
				sort_string(tmp_symbol->items->value.valString);
				data_copy(tmp_symbol,op1);
				op1->filgy = true;
				tmp_symbol = NULL;
			break;
			
			default:
				return E_OK;
			break;
			
		}
		instr_node = instr_node->next;
	}
	return err;
}
Beispiel #17
0
int
main (int argc, char * argv[])
{
    setbuf(stdout, NULL);   // Make stdout unbuffered.

    gameNumberT gNumber;

    bool option_ForceReplace = false;
    bool option_PreGameComments = true;

    uint pgnFileSize = 0;
    char *progname = argv[0];
    fileNameT fname;
    fileNameT baseName;
    uint argsleft = argc - 1;
    char ** nextArg = argv + 1;

    // Parse command-line argments:
    while (argsleft > 0  &&  nextArg[0][0] == '-') {
        if (! strCompare (*nextArg, "-f")) {
            option_ForceReplace = true;
        } else if (! strCompare (*nextArg, "-x")) {
            option_PreGameComments = false;
        } else {
            usage (progname);
        }
        argsleft--;
        nextArg++;
    }
    if (argsleft != 1  &&  argsleft != 2) {
        usage (progname);
    }

    char * pgnName = *nextArg;
    MFile pgnFile;

    pgnFileSize = fileSize (pgnName, "");

    // Ensure positive file size counter to avoid division by zero:
    if (pgnFileSize < 1) {
        pgnFileSize = 1;
    }

    // Make baseName from pgnName if baseName is not provided:
    if (argsleft == 1) {
        strCopy (baseName, pgnName);
        // If a gzip file, remove two suffixes, the first being ".gz":
        const char * lastSuffix = strFileSuffix (baseName);
        if (lastSuffix != NULL  &&  strEqual (lastSuffix, GZIP_SUFFIX)) {
            strTrimFileSuffix (baseName);
        }
        // Trim the ".pgn" suffix:
        strTrimFileSuffix (baseName);
    } else {
        strCopy (baseName, nextArg[1]);
    }

    // Check for existing database, avoid overwriting it:
    if (! option_ForceReplace) {
        if (fileSize (baseName, INDEX_SUFFIX) > 0) {
            // Scid index file already exists:
            fprintf (stderr, "%s: database already exists: %s\n", progname,
                     baseName);
            fprintf (stderr, "You can use:  %s -f %s   to overwrite"
                     " the existing database.\n", progname, pgnName);
            exit(1);
        }
    }

    if (pgnFile.Open (pgnName, FMODE_ReadOnly) != OK) {
        fprintf (stderr, "%s: could not open file %s\n", progname, pgnName);
        exit(1);
    }

    // Try opening the log file:
    strCopy (fname, baseName);
    strAppend (fname, ".err");
    FILE * logFile = fopen (fname, "w");
    if (logFile == NULL) {
        fprintf (stderr, "%s: could not open log file: %s\n", progname, fname);
        exit(1);
    }

    printf ("Converting file %s to Scid database %s:\n", pgnName, baseName);
    printf ("Errors/warnings will be written to %s.\n\n", fname);

    scid_Init();

    GFile * gameFile = new GFile;
    if ((gameFile->Create (baseName, FMODE_WriteOnly)) != OK) {
        fprintf (stderr, "%s: could not create the file %s%s\n",
                 progname, baseName, GFILE_SUFFIX);
        fprintf (stderr, "The file may already exist and be read-only, or\n");
        fprintf (stderr, "you may not have permission to create this file.\n");
        exit(1);
    }

    NameBase * nb = new NameBase;
    Index * idx = new Index;
    IndexEntry * ie = new IndexEntry;
    idx->SetFileName (baseName);
    idx->CreateIndexFile (FMODE_WriteOnly);

    Game * game = new Game;
    ProgBar progBar(stdout);
    progBar.Start();

    ByteBuffer *bbuf = new ByteBuffer;
    bbuf->SetBufferSize (BBUF_SIZE); // 32768

    PgnParser pgnParser (&pgnFile);
    pgnParser.SetErrorFile (logFile);
    pgnParser.SetPreGameText (option_PreGameComments);

    // TODO: Add command line option for ignored tags, rather than
    //       just hardcoding PlyCount as the only ignored tag.
    pgnParser.AddIgnoredTag ("PlyCount");

    // Add each game found to the database:
    while (pgnParser.ParseGame(game) != ERROR_NotFound) {
        ie->Init();

        if (idx->AddGame (&gNumber, ie) != OK) {
            fprintf (stderr, "\nLimit of %d games reached!\n", MAX_GAMES);
            exit(1);
        }

        // Add the names to the namebase:
        idNumberT id = 0;

        if (nb->AddName (NAME_PLAYER, game->GetWhiteStr(), &id) != OK) {
            fatalNameError (NAME_PLAYER);
        }
        nb->IncFrequency (NAME_PLAYER, id, 1);
        ie->SetWhite (id);

        if (nb->AddName (NAME_PLAYER, game->GetBlackStr(), &id) != OK) {
            fatalNameError (NAME_PLAYER);
        }
        nb->IncFrequency (NAME_PLAYER, id, 1);
        ie->SetBlack (id);

        if (nb->AddName (NAME_EVENT, game->GetEventStr(), &id) != OK) {
            fatalNameError (NAME_EVENT);
        }
        nb->IncFrequency (NAME_EVENT, id, 1);
        ie->SetEvent (id);

        if (nb->AddName (NAME_SITE, game->GetSiteStr(), &id) != OK) {
            fatalNameError (NAME_SITE);
        }
        nb->IncFrequency (NAME_SITE, id, 1);
        ie->SetSite (id);

        if (nb->AddName (NAME_ROUND, game->GetRoundStr(), &id) != OK) {
            fatalNameError (NAME_ROUND);
        }
        nb->IncFrequency (NAME_ROUND, id, 1);
        ie->SetRound (id);

        bbuf->Empty();
        if (game->Encode (bbuf, ie) != OK) {
            fprintf (stderr, "Fatal error encoding game!\n");
            abort();
        }
        uint offset = 0;
        if (gameFile->AddGame (bbuf, &offset) != OK) {
            fprintf (stderr, "Fatal error writing game file!\n");
            abort();
        }
        ie->SetOffset (offset);
        ie->SetLength (bbuf->GetByteCount());
        idx->WriteEntries (ie, gNumber, 1);

        // Update the progress bar:
        if (! (gNumber % 100)) {
            int bytesSeen = pgnParser.BytesUsed();
            int percentDone = 1 + ((bytesSeen) * 100 / pgnFileSize);
            progBar.Update (percentDone);
        }

    }

    uint t = 0;   // = time(0);
    nb->SetTimeStamp(t);
    nb->SetFileName (baseName);
    if (nb->WriteNameFile() != OK) {
        fprintf (stderr, "Fatal error writing name file!\n");
        exit(1);
    }
    progBar.Finish();

    printf ("\nDatabase `%s': %d games, %d players, %d events, %d sites.\n",
            baseName, idx->GetNumGames(), nb->GetNumNames (NAME_PLAYER),
            nb->GetNumNames (NAME_EVENT), nb->GetNumNames (NAME_SITE));
    fclose (logFile);
    if (pgnParser.ErrorCount() > 0) {
        printf ("There were %u errors or warnings; ", pgnParser.ErrorCount());
        printf ("examine the file \"%s.err\"\n", baseName);
    } else {
        printf ("There were no warnings or errors.\n");
        removeFile (baseName, ".err");
    }
    gameFile->Close();
    idx->CloseIndexFile();

    // If there is a tree cache file for this database, it is out of date:
    removeFile (baseName, TREEFILE_SUFFIX);
#ifdef ASSERTIONS
    printf("%d asserts were tested\n", numAsserts);
#endif
    return 0;
}
Beispiel #18
0
static int initFunction( DEVICE_INFO *deviceInfo, const char *name,
						 const int nameLength )
	{
	CK_SESSION_HANDLE hSession;
	CK_SLOT_ID slotList[ MAX_PKCS11_SLOTS + 8 ];
	CK_ULONG slotCount = MAX_PKCS11_SLOTS;
	CK_SLOT_INFO slotInfo;
	CK_TOKEN_INFO tokenInfo;
	CK_RV status;
	PKCS11_INFO *pkcs11Info = deviceInfo->devicePKCS11;
	const PKCS11_MECHANISM_INFO *mechanismInfoPtr;
	char *labelPtr;
	int tokenSlot = DEFAULT_SLOT, i, labelLength, mechanismInfoSize;
	int cryptStatus, cryptStatus2;

	assert( isWritePtr( deviceInfo, sizeof( DEVICE_INFO ) ) );
	assert( isReadPtr( name, nameLength ) );

	/* Get information on all available slots */
	memset( slotList, 0, sizeof( slotList ) );
	status = C_GetSlotList( TRUE, slotList, &slotCount );
	if( status != CKR_OK )
		return( pkcs11MapError( status, CRYPT_ERROR_OPEN ) );
	if( slotCount <= 0 )
		{
		/* There are token slots present but no tokens in the slots */
		return( CRYPT_ERROR_OPEN );
		}

	/* Check whether a token name (used to select the slot) has been 
	   specified */
	for( i = 1; i < nameLength - 1; i++ )
		{
		if( name[ i ] == ':' && name[ i + 1 ] == ':' )
			break;
		}
	if( i < nameLength - 1 )
		{
		const char *tokenName = name + i + 2;	/* Skip '::' */
		const int tokenNameLength = nameLength - ( i + 2 );

		if( tokenNameLength <= 0 )
			return( CRYPT_ARGERROR_STR1 );

		/* Some tokens don't implement named slots, so we also allow them to 
		   be specified using slot counts */
		if( tokenNameLength == 1 && isDigit( *tokenName ) )
			{
			tokenSlot = *tokenName - '0';
			if( tokenSlot < 0 || tokenSlot > 9 )
				return( CRYPT_ARGERROR_STR1 );
			if( tokenSlot > slotCount - 1 )	/* Slots numbered from zero */
				return( CRYPT_ERROR_NOTFOUND );
			status = C_GetTokenInfo( slotList[ tokenSlot ], &tokenInfo );
			if( status != CKR_OK )
				return( CRYPT_ERROR_NOTFOUND );
			}
		else
			{
			/* Check each (named) slot for a token matching the given name */
			for( tokenSlot = 0; tokenSlot < slotCount && \
								tokenSlot < FAILSAFE_ITERATIONS_MED; 
				 tokenSlot++ )
				{
				status = C_GetTokenInfo( slotList[ tokenSlot ], &tokenInfo );
				if( status == CKR_OK && \
					!strCompare( tokenName, tokenInfo.label, tokenNameLength ) )
					break;
				}
			ENSURES( tokenSlot < FAILSAFE_ITERATIONS_MED );
			if( tokenSlot >= slotCount )
				return( CRYPT_ERROR_NOTFOUND );
			}
		}
	pkcs11Info->slotID = slotList[ tokenSlot ];

	/* Get information on device-specific capabilities */
	status = C_GetSlotInfo( pkcs11Info->slotID, &slotInfo );
	if( status != CKR_OK )
		{
		shutdownFunction( deviceInfo );
		return( pkcs11MapError( status, CRYPT_ERROR_OPEN ) );
		}
	if( slotInfo.flags & CKF_REMOVABLE_DEVICE )
		{
		/* The device is removable */
		deviceInfo->flags |= DEVICE_REMOVABLE;
		}
	status = C_GetTokenInfo( pkcs11Info->slotID, &tokenInfo );
	if( status != CKR_OK )
		{
		shutdownFunction( deviceInfo );
		return( pkcs11MapError( status, CRYPT_ERROR_OPEN ) );
		}
	if( tokenInfo.flags & CKF_RNG )
		{
		/* The device has an onboard RNG that we can use */
		deviceInfo->getRandomFunction = getRandomFunction;
		}
#if 0	/* The Spyrus driver for pre-Lynks-II cards returns the local system 
		   time (with a GMT/localtime offset), ignoring the fact that the 
		   token has an onboard clock, so having the CKF_CLOCK_ON_TOKEN not 
		   set is accurate, although having it ignore the presence of the 
		   clock isn't very valid */
	if( !( tokenInfo.flags & CKF_CLOCK_ON_TOKEN ) && \
		( !strCompare( tokenInfo.label, "Lynks Token", 11 ) || \
		  !strCompare( tokenInfo.model, "Rosetta", 7 ) ) )
		{
		/* Fix buggy Spyrus PKCS #11 drivers which claim that the token
		   doesn't have a RTC even though it does (the Rosetta (smart card) 
		   form of the token is even worse, it returns garbage in the label 
		   and manufacturer fields, but the model field is OK).  There is a 
		   chance that there's a genuine problem with the clock (there are 
		   batches of tokens with bad clocks) but the time check that  
		   follows below will catch those */
		tokenInfo.flags |= CKF_CLOCK_ON_TOKEN;
		}
#endif /* 0 */
	if( tokenInfo.flags & CKF_CLOCK_ON_TOKEN )
		{
		const time_t theTime = getTokenTime( &tokenInfo );
		const time_t currentTime = getTime();

		/* The token claims to have an onboard clock that we can use.  Since
		   this could be arbitrarily inaccurate we compare it with the 
		   system time and only rely on it if it's within +/- 1 day of the
		   system time.
		   
		   There is a second check that we should make to catch drivers that
		   claim to read the time from the token but actually use the local
		   computer's time, but this isn't easy to do.  The most obvious way
		   is to set the system time to a bogus value and check whether this
		   matches the returned time, but this is somewhat drastic and 
		   requires superuser privs on most systems.  An alternative is to 
		   check whether the claimed token time exactly matches the system 
		   time, but this will produce false positives if (for example) the
		   token has been recently synchronised to the system time.  For now
		   all we can do is throw an exception if it appears that the token
		   time is faked */
		if( theTime > MIN_TIME_VALUE && \
			theTime >= currentTime - 86400 && \
			theTime <= currentTime + 86400 )
			deviceInfo->flags |= DEVICE_TIME;

		/* If this check is triggered then the token time may be faked since 
		   it's identical to the host system time, see the comment above for 
		   details.  We make an exception for soft-tokens (if we can detect 
		   them), which will (by definition) have the same time as the 
		   system time */
		if( !( pkcs11InfoTbl[ pkcs11Info->deviceNo ].name[ 0 ] && \
			   !strCompare( pkcs11InfoTbl[ pkcs11Info->deviceNo ].name, 
							"Software", 8 ) ) && \
			theTime == currentTime )
			{
			DEBUG_DIAG(( "PKCS #11 token time is the same as the host "
						 "system time, token time may be faked by the "
						 "driver." ));
			assert( DEBUG_WARN );
			}
		}
	if( tokenInfo.flags & CKF_WRITE_PROTECTED )
		{
		/* The device can't have data on it changed */
		deviceInfo->flags |= DEVICE_READONLY;
		}
	if( ( tokenInfo.flags & CKF_LOGIN_REQUIRED ) || \
		!( tokenInfo.flags & CKF_USER_PIN_INITIALIZED ) )
		{
		/* The user needs to log in before using various device functions.
		   We check for the absence of CKF_USER_PIN_INITIALIZED as well as 
		   the more obvious CKF_LOGIN_REQUIRED because if we've got an 
		   uninitialised device there's no PIN set so some devices will 
		   report that there's no login required (or at least none is 
		   possible).  We need to introduce some sort of pipeline stall if 
		   this is the case because otherwise the user could successfully 
		   perform some functions that don't require a login (where the 
		   exact details of what's allowed without a login are device-
		   specific) before running into mysterious failures when they get 
		   to functions that do require a login.  To avoid this, we make an 
		   uninitialised device look like a login-required device, so the 
		   user gets an invalid-PIN error if they try and proceed */
		deviceInfo->flags |= DEVICE_NEEDSLOGIN;
		}
	if( ( pkcs11Info->minPinSize = ( int ) tokenInfo.ulMinPinLen ) < 4 )
		{
		/* Some devices report silly PIN sizes */
		DEBUG_DIAG(( "Driver reports suspicious minimum PIN size %lu, "
					 "using 4", tokenInfo.ulMinPinLen ));
		pkcs11Info->minPinSize = 4;
		}
	if( ( pkcs11Info->maxPinSize = ( int ) tokenInfo.ulMaxPinLen ) < 4 )
		{
		/* Some devices report silly PIN sizes (setting this to ULONG_MAX or
		   4GB, which becomes -1 as an int, counts as silly).  Since we can't
		   differentiate between 0xFFFFFFFF = bogus value and 0xFFFFFFFF = 
		   ULONG_MAX we play it safe and set the limit to 8 bytes, which most
		   devices should be able to handle */
		DEBUG_DIAG(( "Driver reports suspicious maximum PIN size %lu, "
					 "using 8", tokenInfo.ulMinPinLen ));
		pkcs11Info->maxPinSize = 8;
		}
	labelPtr = ( char * ) tokenInfo.label;
	for( labelLength = 32;
		 labelLength > 0 && \
		 ( labelPtr[ labelLength - 1 ] == ' ' || \
		   !labelPtr[ labelLength - 1 ] ); 
		  labelLength-- );	/* Strip trailing blanks/nulls */
	while( labelLength > 0 && *labelPtr == ' ' )
		{
		/* Strip leading blanks */
		labelPtr++;
		labelLength--;
		}
	if( labelLength > 0 )
		{
		memcpy( pkcs11Info->label, labelPtr, labelLength );
		pkcs11Info->labelLen = labelLength;
		sanitiseString( pkcs11Info->label, CRYPT_MAX_TEXTSIZE, 
						labelLength );
		}
	else
		{
		/* There's no label for the token, use the device label instead */
		if( pkcs11InfoTbl[ pkcs11Info->deviceNo ].name[ 0 ] )
			{
			labelLength = \
				min( strlen( pkcs11InfoTbl[ pkcs11Info->deviceNo ].name ),
					 CRYPT_MAX_TEXTSIZE );
			memcpy( pkcs11Info->label, 
					pkcs11InfoTbl[ pkcs11Info->deviceNo ].name, labelLength );
			}
		}
	pkcs11Info->hActiveSignObject = CK_OBJECT_NONE;
	deviceInfo->label = pkcs11Info->label;
	deviceInfo->labelLen = pkcs11Info->labelLen;

	/* Open a session with the device.  This gets a bit awkward because we 
	   can't tell whether a R/W session is OK without opening a session, but 
	   we can't open a session unless we know whether a R/W session is OK, 
	   so we first try for a RW session and if that fails we go for a read-
	   only session */
	status = C_OpenSession( pkcs11Info->slotID, 
							CKF_RW_SESSION | CKF_SERIAL_SESSION, NULL_PTR, 
							NULL_PTR, &hSession );
	if( status == CKR_TOKEN_WRITE_PROTECTED )
		{
		status = C_OpenSession( pkcs11Info->slotID, 
								CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, 
								&hSession );
		}
	if( status != CKR_OK )
		{
		cryptStatus = pkcs11MapError( status, CRYPT_ERROR_OPEN );
		if( cryptStatus == CRYPT_ERROR_OPEN && \
			!( tokenInfo.flags & CKF_USER_PIN_INITIALIZED ) )
			{
			/* We couldn't do much with the error code, it could be that the
			   token hasn't been initialised yet but unfortunately PKCS #11 
			   doesn't define an error code for this condition.  In addition
			   many tokens will allow a session to be opened and then fail 
			   with a "PIN not set" error at a later point (which allows for
			   more accurate error reporting), however a small number won't
			   allow a session to be opened and return some odd-looking error
			   because there's nothing useful available.  The best way to
			   report this in a meaningful manner to the caller is to check
			   whether the user PIN has been initialised, if it hasn't then 
			   it's likely that the token as a whole hasn't been initialised 
			   so we return a not initialised error */
			cryptStatus = CRYPT_ERROR_NOTINITED;
			}
		return( cryptStatus );
		}
	ENSURES( hSession != CK_OBJECT_NONE );
	pkcs11Info->hSession = hSession;
	deviceInfo->flags |= DEVICE_ACTIVE;

	/* Set up the capability information for this device.  Since there can 
	   be devices that have one set of capabilities but not the other (e.g.
	   a smart card that only performs RSA ops), we allow one of the two
	   sets of mechanism information setups to fail, but not both */
	mechanismInfoPtr = getMechanismInfoPKC( &mechanismInfoSize );
	cryptStatus = getCapabilities( deviceInfo, mechanismInfoPtr, 
								   mechanismInfoSize );
	mechanismInfoPtr = getMechanismInfoConv( &mechanismInfoSize );
	cryptStatus2 = getCapabilities( deviceInfo, mechanismInfoPtr, 
									mechanismInfoSize );
	if( cryptStatusError( cryptStatus ) && cryptStatusError( cryptStatus2 ) )
		{
		shutdownFunction( deviceInfo );
		return( ( cryptStatus == CRYPT_ERROR ) ? \
				CRYPT_ERROR_OPEN : ( int ) cryptStatus );
		}

	return( CRYPT_OK );
	}
Beispiel #19
0
CString CNPServer::CmdLogin (ClientCtx *pClient, const CDataPackStruct &Data)
	{
	//	If we're already logged in, then fail (for now)

	if (pClient->ACL != aclNoLogin)
		return ComposeCmdFail(pClient, CMD_LOGIN, LITERAL("You are already logged in."));

	//	Get the data

	CString sName = Data.GetStringItem(1);
	CString sPassword = Data.GetStringItem(2);

	Lock();

	//	Check for overlord

	if (strCompare(sName, LITERAL("overlord")) == 0)
		{
		//	Check the password

		if (strCompare(sPassword, m_sOverlordPassword) != 0)
			{
			Unlock();
			return ComposeCmdFail(pClient, CMD_LOGIN, LITERAL("Invalid name or password."));
			}

		//	Complete login

		pClient->sName = LITERAL("Overlord");
		pClient->ACL = aclOverlord;
		pClient->pSovereign = m_pUniv->GetSovereign(m_pUniv->GetOverlordUNID());

		Log("[%d] Login as Overlord", pClient->dwClientID);
		}

	//	Check for guest

	else if (strCompare(sName, LITERAL("guest")) == 0)
		{
		//	Not allowed, for now

		Unlock();
		return ComposeCmdFail(pClient, CMD_LOGIN, LITERAL("Guest access not allowed in this universe."));
		}

	//	A player

	else
		{
		//	Look-up the player

		CNPHumanPlayer *pPlayer;
		if (m_Players.Lookup(sName, (CObject **)&pPlayer) != NOERROR)
			{
			Unlock();
			return ComposeCmdFail(pClient, CMD_LOGIN, LITERAL("Invalid name or password."));
			}

		//	Check the password

		if (strCompare(sPassword, pPlayer->GetPassword()) != 0)
			{
			Unlock();
			return ComposeCmdFail(pClient, CMD_LOGIN, LITERAL("Invalid name or password."));
			}

		//	Complete login

		pClient->sName = sName;
		pClient->ACL = aclPlayer;
		pClient->pSovereign = m_pUniv->GetSovereign(pPlayer->GetSovereignID());

		Log("[%d] Login as %s", pClient->dwClientID, sName.GetASCIIZPointer());
		}

	//	Compose reply

	CDataPackStruct Reply;
	Reply.AppendInteger(RES_LOGIN);
	Reply.AppendInteger(pClient->pSovereign->GetUNID());
	Reply.AppendInteger(m_pUniv->GetTurn());
	Reply.AppendString(pClient->pSovereign->GetName());

	Unlock();

	return Reply.SerializeToString();
	}
Beispiel #20
0
bool CDlgFileAssoc::IsExtAssigned(LPWSTR extName, LPWSTR extDesc) {

	bool result = false;

	HKEY hKey;
	wchar_t buf[100];
	DWORD ln = 100;

	if (RegOpenKeyExW(HKEY_CLASSES_ROOT, extName, 0, 0, &hKey) == ERROR_SUCCESS) {
		if ((RegQueryValueExW(hKey, NULL, NULL, NULL, (BYTE*)&buf, &ln) == ERROR_SUCCESS) && (strCompare(buf, extDesc) == 0)) {
			result = true;
		}
		RegCloseKey(hKey);
	}

	return result;

}
Beispiel #21
0
ALERROR CNPUniverse::CreateSovereign (CString sName, CNPWorld *pCapital, CXMLElement *pSovTemplate, CNPSovereign **retpSovereign)

//	CreateSovereign
//
//	Creates a new sovereign

	{
	ALERROR error;
	CNPSovereign *pSovereign;
	int i;

	if (error = CNPSovereign::Create(m_Sovereigns.RegisterEntry(), sName, &pSovereign))
		return error;

	m_Sovereigns.SetEntry(pSovereign->GetUNID(), pSovereign);

	//	Obviously we know about ourselves

	pSovereign->SetKnowledge(pSovereign->GetUNID());

	//	Set a capital

	if (pCapital)
		{
		pSovereign->SetCapital(pCapital->GetUNID());

		pCapital->RemoveTrait(traitReservedCapital);
		pCapital->SetTrait(traitCapital);
		pCapital->SetSovereign(pSovereign);

		//	Scan the capital

		CNPNullPoint *pNP = GetNullPoint(pCapital->GetLocation());
		ScanNullPoint(pSovereign, pNP, 1);

		//	Scan the area around the capital

		for (i = 0; i < pNP->GetLinkCount(); i++)
			{
			CNPNullPoint *pDest = pNP->GetLinkDest(i);
			ScanNullPoint(pSovereign, pDest, 1);
			}

		//	Create ships

		if (pSovTemplate)
			{
			CNPFleet *pFleet = NULL;
			for (i = 0; i < pSovTemplate->GetContentElementCount(); i++)
				{
				CXMLElement *pShip = pSovTemplate->GetContentElement(i);
				if (strCompare(pShip->GetTag(), CONSTLIT("Unit")) == 0)
					{
					//	Create the fleet, if needed

					if (pFleet == NULL)
						if (error = CreateFleet(pNP, pSovereign, &pFleet))
							return error;

					//	Add the ship to the fleet

					CNPUnit Unit(pShip->GetAttributeInteger(CONSTLIT("Class")), 0, 0);
					pFleet->GetAssetList().AddUnit(Unit);
					}
				}
			}
		}

	//	Done

	if (retpSovereign)
		*retpSovereign = pSovereign;

	return NOERROR;
	}
int main(void) {
	const int magic_number = 13017;

	/* test min */
	int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
	printf("the smallest of the first 10 natural numbers is: %d\n", minIt(a, 10));
	printf("the smallest of the first 10 natural numbers is: %d\n", minRec1(a, 10));
	printf("the smallest of the first 10 natural numbers is: %d\n", minRec2(a, 10));
	a[3] = -1;
	printf("now the smallest is %d\n", minIt(a, 10));
	printf("now the smallest is %d\n", minRec1(a, 10));
	printf("now the smallest is %d\n", minRec2(a, 10));
	
	/* test sqrt */
	printf("the sqrt of 25 is %g\n", sqrtIt(25.0, 0, 25.0));
	printf("the sqrt of 26 is %g\n", sqrtIt(26.0, 0, 26.0));
	printf("the sqrt of 2 is %g\n", sqrtIt(2.0, 0, 2.0));
	printf("the sqrt of 25 is %g\n", sqrtRec(25.0, 0, 25.0));
	printf("the sqrt of 26 is %g\n", sqrtRec(26.0, 0, 26.0));
	printf("the sqrt of 2 is %g\n", sqrtRec(2.0, 0, 2.0));

	/* test strCompare */
	char* s1; char* s2;
	s1 = "apple"; s2 = "apricot";
	if (strCompare(s1, s2) < 0) { 
		printf("\"%s\" is less than \"%s\", very good\n", s1, s2);
	} else {
		printf("oops, \"%s\" should be less than \"%s\"\n", s1, s2);
	}
			
	s1 = "Apple"; s2 = "apple";
	if (strCompare(s1, s2) < 0) { 
		printf("\"%s\" is less than \"%s\", very good\n", s1, s2);
	} else {
		printf("oops, \"%s\" should be less than \"%s\"\n", s1, s2);
	}

	s1 = "baby boy"; s2 = "banana";
	if (strCompare(s1, s2) < 0) { 
		printf("\"%s\" is less than \"%s\", very good\n", s1, s2);
	} else {
		printf("oops, \"%s\" should be less than \"%s\"\n", s1, s2);
	}

	s1 = "a rather silly string"; s2 = "a rather silly string";
	if (strCompare(s1, s2) == 0) { 
		printf("\"%s\" is equal to \"%s\", very good\n", s1, s2);
	} else {
		printf("oops, \"%s\" should be equal to \"%s\"\n", s1, s2);
	}

	s1 = "12345"; s2 = "12345";
	if (strCompare(s1, s2) == 0) { 
		printf("\"%s\" is equal to \"%s\", very good\n", s1, s2);
	} else {
		printf("oops, \"%s\" should be equal to \"%s\"\n", s1, s2);
	}

	s1 = "Numbers: 12345"; s2 = "12345";
	if (strCompare(s1, s2) > 0) { 
		printf("\"%s\" is greater than \"%s\", very good\n", s1, s2);
	} else {
		printf("oops, \"%s\" should be greater than \"%s\"\n", s1, s2);
	}

	s1 = "Texas"; s2 = "California";
	if (strCompare(s1, s2) > 0) { 
		printf("\"%s\" is greater than \"%s\", very good\n", s1, s2);
	} else {
		printf("oops, \"%s\" should be greater than \"%s\"\n", s1, s2);
	}

	/* test strCompare2 */
	s1 = "apple"; s2 = "Apricot";
	if (strCompare2(s1, s2) < 0) { 
		printf("\"%s\" is less than \"%s\", very good\n", s1, s2);
	} else {
		printf("oops, \"%s\" should be less than \"%s\"\n", s1, s2);
	}

	s1 = "Batman!"; s2 = "bat man";
	if (strCompare2(s1, s2) == 0) { 
		printf("\"%s\" is equal to \"%s\", very good\n", s1, s2);
	} else {
		printf("oops, \"%s\" should be equal to \"%s\"\n", s1, s2);
	}

	s1 = "OMG, WTF?"; s2 = "oh my goodness, what the heck?";
	if (strCompare2(s1, s2) > 0) { 
		printf("\"%s\" is greater than \"%s\", very good\n", s1, s2);
	} else {
		printf("oops, \"%s\" should be greater than \"%s\"\n", s1, s2);
	}

	/* test maze */		
	srand(magic_number);
	makeMaze();
	recodeMaze();
	printf("recursive solution to the maze\n");
	printMaze();
	solveMazeRec(0, start_col);	
	printMaze();
	printf("\n\n\n");
	
	printf("iterative solution to the maze\n");
	srand(magic_number);
	makeMaze();
	recodeMaze();
	printMaze();
	solveMazeIt(0, start_col);
	printMaze();


	/* test Martian */
	Martian change1 = changeIt(15);
	printf("change 1 should be 0d, 3n, 0p and is: %dd %dn %dp\n", change1.dodeks, change1.nicks, change1.pennies);

	Martian change2 = changeIt(0);
	printf("change 2 should be 0d, 0n, 0p and is: %dd %dn %dp\n", change2.dodeks, change2.nicks, change2.pennies);

	Martian change3 = changeIt(17);
	printf("change 3 should be 1d, 1n, 0p and is: %dd %dn %dp\n", change3.dodeks, change3.nicks, change3.pennies);

	Martian change4 = changeIt(25);
	printf("change 4 should be 2d, 0n, 1p and is: %dd %dn %dp\n", change4.dodeks, change4.nicks, change4.pennies);

	/* A very simple and obvious test of the general form of Martian
	 * be sure and test your solution more thoroughly!!!! */
	change4 = changeIt(25, 5, 12);
	printf("change 4 should be 2d, 0n, 1p and is: %dd %dn %dp\n", change4.dodeks, change4.nicks, change4.pennies);
}
Beispiel #23
0
int HelperCompareItems (ICCItem *pFirst, ICCItem *pSecond)

//	HelperCompareItems
//
//	Compares two items and returns:
//
//		1	if pFirst > pSecond
//		0	if pFirst = pSecond
//		-1	if pFirst < pSecond
//		-2	if pFirst is not the same type as pSecond

	{
	//	Compare this with the first expression

	if (pFirst->GetValueType() == pSecond->GetValueType())
		{
		switch (pFirst->GetValueType())
			{
			case ICCItem::Boolean:
				{
				if (pFirst->IsNil() == pSecond->IsNil())
					return 0;
				else if (pFirst->IsNil())
					return -1;
				else
					return 1;
				}

			case ICCItem::Integer:
				{
				if (pFirst->GetIntegerValue() == pSecond->GetIntegerValue())
					return 0;
				else if (pFirst->GetIntegerValue() > pSecond->GetIntegerValue())
					return 1;
				else
					return -1;
				}

			case ICCItem::String:
				return strCompare(pFirst->GetStringValue(), pSecond->GetStringValue());

			case ICCItem::List:
				{
				if (pFirst->GetCount() == pSecond->GetCount())
					{
					int i;

					for (i = 0; i < pFirst->GetCount(); i++)
						{
						ICCItem *pItem1 = pFirst->GetElement(i);
						ICCItem *pItem2 = pSecond->GetElement(i);
						int iCompare;

						iCompare = HelperCompareItems(pItem1, pItem2);
						if (iCompare != 0)
							return iCompare;
						}

					return 0;
					}
				else if (pFirst->GetCount() > pSecond->GetCount())
					return 1;
				else
					return -1;
				break;
				}

			default:
				return -2;
			}
		}
	else
		return -2;
	}
Beispiel #24
0
int main(void) {
	const int magic_number = time(NULL);

	/* test min */
	int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
//	printf("the smallest of the first 10 natural numbers is: %d\n", minIt(a, 10));
	printf("the smallest of the first 10 natural numbers is: %d\n", minRec1(a, 10));
	printf("the smallest of the first 10 natural numbers is: %d\n", minRec2(a, 10));
	a[3] = -1;
//	printf("now the smallest is %d\n", minIt(a, 10));
	printf("now the smallest is %d\n", minRec1(a, 10));
	printf("now the smallest is %d\n", minRec2(a, 10));
	
	/* test sqrt */
//	printf("the sqrt of 25 is %g\n", sqrtIt(25.0, 0, 25.0));
//	printf("the sqrt of 26 is %g\n", sqrtIt(26.0, 0, 26.0));
//	printf("the sqrt of 2 is %g\n", sqrtIt(2.0, 0, 2.0));
	// printf("the sqrt of 25 is %g\n", sqrtRec(25.0, 0, 25.0));
	// printf("the sqrt of 26 is %g\n", sqrtRec(26.0, 0, 26.0));
	// printf("the sqrt of 2 is %g\n", sqrtRec(2.0, 0, 2.0));
	//printf("sqrt of 2e60 is %.17g\n", sqrtRec(2.0 * pow10(60), 1.4142135623731, 1.5 * pow10(30)));

	/* test strCompare */
	char* s1; char* s2;
	s1 = "apple"; s2 = "apricot";
	if (strCompare(s1, s2) < 0) { 
		printf("\"%s\" is less than \"%s\", very good\n", s1, s2);
	} else {
		printf("oops, \"%s\" should be less than \"%s\"\n", s1, s2);
	}
			
	s1 = "Apple"; s2 = "apple";
	if (strCompare(s1, s2) < 0) { 
		printf("\"%s\" is less than \"%s\", very good\n", s1, s2);
	} else {
		printf("oops, \"%s\" should be less than \"%s\"\n", s1, s2);
	}

	s1 = "baby boy"; s2 = "banana";
	if (strCompare(s1, s2) < 0) { 
		printf("\"%s\" is less than \"%s\", very good\n", s1, s2);
	} else {
		printf("oops, \"%s\" should be less than \"%s\"\n", s1, s2);
	}

	s1 = "a rather silly string"; s2 = "a rather silly string";
	if (strCompare(s1, s2) == 0) { 
		printf("\"%s\" is equal to \"%s\", very good\n", s1, s2);
	} else {
		printf("oops, \"%s\" should be equal to \"%s\"\n", s1, s2);
	}

	s1 = "12345"; s2 = "12345";
	if (strCompare(s1, s2) == 0) { 
		printf("\"%s\" is equal to \"%s\", very good\n", s1, s2);
	} else {
		printf("oops, \"%s\" should be equal to \"%s\"\n", s1, s2);
	}

	s1 = "Numbers: 12345"; s2 = "12345";
	if (strCompare(s1, s2) > 0) { 
		printf("\"%s\" is greater than \"%s\", very good\n", s1, s2);
	} else {
		printf("oops, \"%s\" should be greater than \"%s\"\n", s1, s2);
	}

	s1 = "Texas"; s2 = "California";
	if (strCompare(s1, s2) > 0) { 
		printf("\"%s\" is greater than \"%s\", very good\n", s1, s2);
	} else {
		printf("oops, \"%s\" should be greater than \"%s\"\n", s1, s2);
	}

	/* test strCompare2 */
	s1 = "apple"; s2 = "Apricot";
	if (strCompare2(s1, s2) < 0) { 
		printf("\"%s\" is less than \"%s\", very good\n", s1, s2);
	} else {
		printf("oops, \"%s\" should be less than \"%s\"\n", s1, s2);
	}

	s1 = "Batman!"; s2 = "bat man";
	if (strCompare2(s1, s2) == 0) { 
		printf("\"%s\" is equal to \"%s\", very good\n", s1, s2);
	} else {
		printf("oops, \"%s\" should be equal to \"%s\"\n", s1, s2);
	}

	s1 = "OMG, WTF?"; s2 = "oh my goodness, what the heck?";
	if (strCompare2(s1, s2) > 0) { 
		printf("\"%s\" is greater than \"%s\", very good\n", s1, s2);
	} else {
		printf("oops, \"%s\" should be greater than \"%s\"\n", s1, s2);
	}

	printf("********************************************\n");


	s1 = "!79857#*#*b*&atm#@@an 989^";
	s2 = "     b   a   t   m   a   ! n";

	if (strCompare2(s1, s2) == 0) {
		printf("Good\n");
	}
	else {
		printf("Bad\n");
	}

	s1 = "CAPITAL LETTERS DON'T MATTER FOR STRCOMPARE2";
	s2 = "capital letters don't matter for strcompare2";

	if (strCompare2(s1, s2) == 0) {
		printf("Good\n");
	}
	else {
		printf("Bad\n");
	}

	s1 = "asdf ASDF jkl JKL a   *&@#^&^#";
	s2 = "asdf ASDF jkl JKL b   *&@#^&^#";
	if (strCompare2(s1, s2) == -1) {
		printf("Good\n");
	}
	else {
		printf("Bad\n");
	}

	printf("Strong test case:\n");
	s1 = "strongg";
	s2 = "strong";
	printf("%d\n", strCompare(s1, s2));
	printf("%d\n", strCompare2(s1, s2));

	/* test maze */		
	srand(magic_number);
	makeMaze();
	recodeMaze();
	printf("recursive solution to the maze\n");
	fflush(stdout);
	solveMazeRec(0, start_col);
	printMaze();
	printf("\n\n\n");
	
//	printf("iterative solution to the maze\n");
//	srand(magic_number);
//	makeMaze();
//	recodeMaze();
//	solveMazeIt(0, start_col);
//	printMaze();
/*
	printf("\n");
	printf("\n");
	printf("\n");
	printf("\n");
	printf("\n");

	// for (double j = 3; j < 2e3; j+= 2) {
	// 	printf("the sqrt of %g is %g expected: %g\n", j, sqrtRec(j, 0, 9000), sqrt(j));
	// 	double_equals(sqrtRec(j, 0, 9000), sqrt(j));
	// }


	printf("\n");
	printf("\n");
	printf("\n");
	printf("\n");
	printf("\n");

	//printf("%.17g\n", sqrtRec(27.0, 0.0, 50.0));
*/
	/* test Martian */
/*	Martian change1 = change(15);
	printf("change 1 should be 0d, 3n, 0p and is: %dd %dn %dp\n", change1.dodeks, change1.nicks, change1.pennies);

	int c = 0;
int d = 0;
int n = 0;
int p = 0;
int i = 0;
int iterate = 20;
FILE *fp;
fp = fopen("output.txt", "r");

while (!feof(fp) && i < iterate) {
  change1 = change(i);
  fscanf(fp, "%d", &c);
  fscanf(fp, "%d", &d);
  fscanf(fp, "%d", &n);
  fscanf(fp, "%d", &p);
  printf("change: %d %d %d %d\n", i ,change1.dodeks, change1.nicks, change1.pennies);
  printf("python: %d %d %d %d\n", c, d, n, p);
  assert(change1.pennies == p);
  assert(change1.nicks == n);
  assert(change1.dodeks == d);
  i++;
}
fclose(fp);

	Martian change2 = change(0);
	printf("change 2 should be 0d, 0n, 0p and is: %dd %dn %dp\n", change2.dodeks, change2.nicks, change2.pennies);

	Martian change3 = change(17);
	printf("change 3 should be 1d, 1n, 0p and is: %dd %dn %dp\n", change3.dodeks, change3.nicks, change3.pennies);

	Martian change4 = change(25);
	printf("change 4 should be 2d, 0n, 1p and is: %dd %dn %dp\n", change4.dodeks, change4.nicks, change4.pennies);
*/
    //************************************************* PERSONAL TESTS *****************************************************//
    Martian change5 = change(16);
    printf("change 5 should be 0d, 3n, 1p and is: %dd %dn %dp\n", change5.dodeks, change5.nicks, change5.pennies);

	/* A very simple and obvious test of the general form of Martian
	 * be sure and test your solution more thoroughly!!!! */
	Martian change6 = change(25, 5, 12);
	printf("change 6 should be 2d, 0n, 1p and is: %dd %dn %dp\n", change6.dodeks, change6.nicks, change6.pennies);

    Martian change7 = change(16, 5, 12);
    printf("change 7 should be 0d, 3n, 1p and is: %dd %dn %dp\n", change7.dodeks, change7.nicks, change7.pennies);

    Martian change8 = change(20, 5, 10);
    printf("change 8 should be 2d, 0n, 0p and is: %dd %dn %dp\n", change8.dodeks, change8.nicks, change8.pennies);

    Martian change9 = change(21, 5, 10);
    printf("change 9 should be 2d, 0n, 1p and is: %dd %dn %dp\n", change9.dodeks, change9.nicks, change9.pennies);

/*
    printf("\n");
	printf("\n");
	printf("\n");
	printf("\n");
	printf("\n");
	printf("\n");
	printf("\n");
	printf("\n");
	printf("\n");
	printf("\n");
	printf("\n");
	printf("\n");
	printf("\n");
	n = 5;
	int z[] = {0, 0, 0, 0, 0};
	printf("Min of z: %d\n", minRec1(z, n));
	printf("Min of z: %d\n", minRec2(z, n));
	int oi[] = {-5, 0, 0, 0, -4};
	printf("Min of oi: %d\n", minRec1(oi, n));
	printf("Min of oi: %d\n", minRec2(oi, n));
	int koi[] = {-5, -234, -2525, 2, 4};
	printf("Min of koi: %d\n", minRec1(koi, n));
	printf("Min of koi: %d\n", minRec2(koi, n));
	char* str1 = "Genji";
	char* str2 = "GENJI";
	printf("%d\n", strCompare(str1, str2));
	printf("%d\n", strCompare2(str1, str2));
	str1 = " hehe xD";
	str2 = "hehe xD";
	printf("%d\n", strCompare(str1, str2));
	printf("%d\n", strCompare2(str1, str2));
	printf("\n");
	printf("\n");
	printf("\n");
	printf("\n");
	printf("\n");
	printf("\n");
	printf("\n");
	printf("\n");
	printf("\n");
	printf("\n");
	printf("\n");
	printf("\n");
	printf("\n");

	Martian change45 = change(28);
    printf("%dd %dn %dp\n", change45.dodeks, change45.nicks, change45.pennies);

    */
}