Ejemplo n.º 1
0
// Pass One
int ParseFile(FILE * pFile, MODULE_t ** pMT)
{
    if (!pFile)
    {
        // file pointer invalid?
        printf("File access error, exit.\n");
        return -1;
    }

    size_t line_num = 0;
    unsigned int offset;
    char * token = NULL;
    char symbol[17];
    int addr = 0;
    STATE_t state = DEF_COUNT;
    MODULE_t * MT;
    int count, code_size = 0;

    for (;;)
    {
        token = GetToken(pFile, &line_num, &offset);
        switch (state)
        {
            case DEF_COUNT:
                if (!token)
                    return 0;       // EOF when expecting a defcount, 
                                    // regarded as success
                if (!isNum(token))  // if token is not presenting a number
                    return __parseerror(NUM_EXPECTED, line_num, offset);

                count = atoi(token);
                if (count > 16)
                    return __parseerror(TO_MANY_DEF_IN_MODULE, line_num, offset);

                NewModule(pMT, code_size);
                MT = *pMT;
                if (count == 0)
                    state = USE_COUNT;
                else
                    state = DEF_S;
                break;

            case DEF_S:
                if (isValidSymbol(token) == SYM_INVALID)
                    return __parseerror(SYM_EXPECTED, line_num, offset);
                if (isValidSymbol(token) == SYM_LONG)
                    return __parseerror(SYM_TOLONG, line_num, offset);

                strcpy(symbol, token);  // preserve symbol name
                state = DEF_R;
                break;

            case DEF_R:
                if (!isNum(token))
                    return __parseerror(NUM_EXPECTED, line_num, offset);

                addr = atoi(token);
                AddSymbol(MT, symbol, code_size+addr);
                count--;
                if (count == 0)
                    state = USE_COUNT;
                else
                    state = DEF_S;

                break;

            case USE_COUNT:
                if (!isNum(token))  // if token is not presenting a number
                    return __parseerror(NUM_EXPECTED, line_num, offset);

                count = atoi(token);
                if (count > 16)
                    return __parseerror(TO_MANY_USE_IN_MODULE, line_num, offset);

                if (count == 0)
                    state = CODE_COUNT;
                else
                    state = USE_LIST;
                break;

            case USE_LIST:
                if (isValidSymbol(token) == SYM_INVALID)
                    return __parseerror(SYM_EXPECTED, line_num, offset);
                if (isValidSymbol(token) == SYM_LONG)
                    return __parseerror(SYM_TOLONG, line_num, offset);

                AddUse(MT, token);
                count--;
                if (count == 0)
                    state = CODE_COUNT;
                else
                    state = USE_LIST;
                break;

            case CODE_COUNT:
                if (!isNum(token))  // if token is not presenting a number
                    return __parseerror(NUM_EXPECTED, line_num, offset);

                count = atoi(token);
                if (count + code_size > 512)
                    return __parseerror(TO_MANY_INSTR, line_num, offset);

                SetModuleSize(MT, count);

                if (count == 0)
                    state = DEF_COUNT;
                else
                {
                    code_size += count;     // keep calculating code size
                    state = CODE_TYPE;
                }
                break;

            case CODE_TYPE:
                if(!isAddrType(token))
                    return __parseerror(ADDR_EXPECTED, line_num, offset);
                state = CODE_INSTR;
                break;

            case CODE_INSTR:
                if (!isNum(token))  // if token is not presenting a number
                    return __parseerror(NUM_EXPECTED, line_num, offset);
                count--;
                if (count == 0)
                    state = DEF_COUNT;
                else
                    state = CODE_TYPE;
                break;

            default:
                break;
        }   // switch
    }   // for
}
Ejemplo n.º 2
0
std::vector<Token> Lexer::lex(std::istream &input) {
  std::vector<Token> tokens;

  while (input.good()) {
    int pos = input.tellg();
    int c = input.get(); 
    if (c < 0)
      break;

    switch (c) {
      // Whitespaces
      case ' ':
      case '\n':
      case '\0':
        break;

      // numbers
      case '0': case '1': case '2': case '3': case '4':
      case '5': case '6': case '7': case '8': case '9':
        while (input.good() && isNum(input.peek()) ) {
          input.get();
        }
        tokens.push_back(Token(Number, pos, int(input.tellg()) - pos));
        break;

      case 'a': case 'b': case 'c': case 'd': case 'e':
      case 'f': case 'g': case 'h': case 'i': case 'j':
      case 'k': case 'l': case 'm': case 'n': case 'o':
      case 'p': case 'q': case 'r': case 's': case 't':
      case 'u': case 'v': case 'w': case 'x': case 'y': case 'z':
      case 'A': case 'B': case 'C': case 'D': case 'E':
      case 'F': case 'G': case 'H': case 'I': case 'J':
      case 'K': case 'L': case 'M': case 'N': case 'O':
      case 'P': case 'Q': case 'R': case 'S': case 'T':
      case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z':
      case '_': {
        std::string s;
        s += (char)c;
        while (input.good() && isLetterOrNum(input.peek()) ) {
          c = input.get();
          s += (char)c;
        }
        TokenKind kind = Identifier;
        if (keywords.find(s) != keywords.end())
          kind = keywords[s];
        tokens.push_back(Token(kind, pos, int(input.tellg()) - pos));
        break;
      }
      case ';':
        tokens.push_back(Token(SemiColon, pos, 1));
        break;

      case '=':
        tokens.push_back(Token(Equal, pos, 1));
        break;

      case '+':
        tokens.push_back(Token(Plus, pos, 1));
        break;

      case '*':
        tokens.push_back(Token(Star, pos, 1));
        break;

      case '(':
        tokens.push_back(Token(LParam, pos, 1));
        break;

      case ')':
        tokens.push_back(Token(RParam, pos, 1));
        break;

      case '{':
        tokens.push_back(Token(LBrace, pos, 1));
        break;

      case '}':
        tokens.push_back(Token(RBrace, pos, 1));
        break;

      default:
        std::cerr << "Warning: unhandled token " << c << " '" << char(c) << "'\n";
    }
  }

  tokens.push_back(Token(EndOfFile, input.tellg(), 0));

  return tokens;
}
Ejemplo n.º 3
0
//aqui recebe uma string e são tratados todos os chars para o proposito do programa
int calcular(char g_char[], pilha *p){

	if( isEnter(g_char[0]) || !isEmpty(p)){
		int i = 0;
		
		while(g_char[i] != '\0'){
			
			//insere o estado dos calculos
			if(!isClear(g_char[i]) && !isConsulta(g_char[i])){
				if(isEmpty(p))
					printf("- ");
				consulta_inversa(p);
				printf("\n");
			}
			
			//se for numero insere na pilha
			if(isNum(g_char[i])){
				insertNum(p, g_char[i] - 48);
				
				//se o char anterior tbm for numero faz calculo para fazer dos 2 um numero
				if(isNum(g_char[i-1] )|| isEnter(g_char[i-1]))
					faz_calculo(p);
				else{
					clear_calc(p);
					if(!RUN_CODES){
						exibeHeader();
						printf("\nErro! Voce deve usar necessariamente \'E\' para informar a entrada de um numero\n");
					}
				}
				i++;
				continue;
			}
			
			//se for um E insere 0 na pilha
			if(isEnter(g_char[i])){
        		insertNum(p, 0);
        		i++;
        		continue;
			}
			
			//se for '-' faz uma subtração
			if(g_char[i] == '-'){
				faz_sub(p);
				i++;
				continue;
			}
			
			//se for '+' faz uma adição
			if(g_char[i] == '+'){
				faz_soma(p);
				i++;
				continue;
			}
			
			//se for '/' faz uma divisão
            if(g_char[i] == '/'){
				faz_div(p);
				i++;
				continue;
			}
			
			//se for '*' faz uma multiplicação
            if(g_char[i] == '*'){
				faz_mult(p);
				i++;
				continue;
			}
			
			//se for '^' faz uma potencia
            if(g_char[i] == '^'){
				faz_pow(p);
				i++;
				continue;
			}
			
			//se for '!' faz um fatorial
            if(g_char[i] == '!'){
				faz_fatorial(p);
				i++;
				continue;
			}
			
			//se for C limpa a pilha
			if(isClear(g_char[i])){
				clear_calc(p);
				if(!RUN_CODES){
					exibeHeader();
					printf("\nPilha Vazia\n");
				}
				i++;
				continue;
			}
			
			//se for V faz uma consulta na pilha
			if(isConsulta(g_char[i]) && strlen(g_char) == 1){
				if(!RUN_CODES)
					consulta(p);
				i++;
			}
				
		}
		if(!isConsulta(g_char[i-1]))
			//consulta que exibe a pilha ao contrario
			consulta_inversa(p);
		if(!RUN_CODES)
			printf("\n");
		return 0;
	}else{
		//se o char indice 0 for V exibe a consulta
		if(isConsulta(g_char[0]))
			if(!RUN_CODES)
				consulta(p);
				
		else{
			//se o char indice 0 for C limpa a pilha
			if(isClear(g_char[0]))
				clear_calc(p);
				
			else
				return 1;
		}
	}
		
	
}
void handleExcludeFile(tree *tr, analdef *adef, rawdata *rdta)
{
  FILE *f;  
  char buf[256];
  int
    ch,
    j, value, i,
    state = 0,
    numberOfModels = 0,
    l = -1,
    excludeRegion   = 0,
    excludedColumns = 0,
    modelCounter    = 1;
  int
    *excludeArray, *countArray, *modelList;
  int
    **partitions;

  printf("\n\n");

  f = myfopen(excludeFileName, "rb");    

  while((ch = getc(f)) != EOF)
  {
    if(ch == '-')
      numberOfModels++;
  } 

  excludeArray = (int*)malloc(sizeof(int) * (rdta->sites + 1));
  countArray   = (int*)malloc(sizeof(int) * (rdta->sites + 1));
  modelList    = (int *)malloc((rdta->sites + 1)* sizeof(int));

  partitions = (int **)malloc(sizeof(int *) * numberOfModels);  
  for(i = 0; i < numberOfModels; i++)
    partitions[i] = (int *)malloc(sizeof(int) * 2);

  rewind(f);

  while((ch = getc(f)) != EOF)
  {     
    switch(state)
    {
      case 0: /* get first number */
        if(!whitechar(ch))
        {
          if(!isNum(ch))
          {
            printf("exclude file must have format: number-number [number-number]*\n");
            exit(-1);
          }
          l = 0;
          buf[l++] = ch;
          state = 1;
        }
        break;
      case 1: /*get the number or detect - */
        if(!isNum(ch) && ch != '-')
        {
          printf("exclude file must have format: number-number [number-number]*\n");
          exit(-1);
        }
        if(isNum(ch))
        {
          buf[l++] = ch;
        }
        else
        {
          buf[l++] = '\0';	     
          value = atoi(buf);
          partitions[excludeRegion][0] = value;
          state = 2;
        }
        break;
      case 2: /*get second number */
        if(!isNum(ch))
        {
          printf("exclude file must have format: number-number [number-number]*\n");
          exit(-1);
        }
        l = 0;
        buf[l++] = ch;
        state = 3;
        break;
      case 3: /* continue second number or find end */	 
        if(!isNum(ch) && !whitechar(ch))
        {
          printf("exclude file must have format: number-number [number-number]*\n");
          exit(-1);
        }
        if(isNum(ch))
        {
          buf[l++] = ch;
        }
        else
        {	      
          buf[l++] = '\0';	     
          value = atoi(buf);
          partitions[excludeRegion][1] = value;
          excludeRegion++;
          state = 0;
        }
        break;
      default:
        assert(0);
    }
  }

  if(state == 3)
  {
    buf[l++] = '\0';     
    value = atoi(buf);
    partitions[excludeRegion][1] = value;
    excludeRegion++;
  }

  assert(excludeRegion == numberOfModels);

  for(i = 0; i <= rdta->sites; i++)
  {
    excludeArray[i] = -1;
    countArray[i] = 0;      
    modelList[i] = -1;
  }  

  for(i = 0; i < numberOfModels; i++)
  {
    int lower = partitions[i][0];
    int upper = partitions[i][1];

    if(lower > upper)
    {
      printf("Misspecified exclude region %d\n", i);
      printf("lower bound %d is greater than upper bound %d\n", lower, upper);
      exit(-1);
    }

    if(lower == 0)
    {
      printf("Misspecified exclude region %d\n", i);
      printf("lower bound must be greater than 0\n");
      exit(-1);
    }

    if(upper > rdta->sites)
    {
      printf("Misspecified exclude region %d\n", i);
      printf("upper bound %d must be smaller than %d\n", upper, (rdta->sites + 1));
      exit(-1);
    }	
    for(j = lower; j <= upper; j++)
    {
      if(excludeArray[j] != -1)
      {
        printf("WARNING: Exclude regions %d and %d overlap at position %d (already excluded %d times)\n", 
            excludeArray[j], i, j, countArray[j]);
      }
      excludeArray[j] = i;
      countArray[j]   =  countArray[j] + 1;	 
    }
  }

  for(i = 1; i <= rdta->sites; i++)
  {
    if(excludeArray[i] != -1)
      excludedColumns++;
    else
    {
      modelList[modelCounter] = tr->model[i];
      modelCounter++;
    }
  }

  printf("You have excluded %d out of %d columns\n", excludedColumns, rdta->sites);

  if(excludedColumns == rdta->sites)
  {
    printf("Error: You have excluded all sites\n");
    exit(-1);
  }

  if(adef->useSecondaryStructure && (excludedColumns > 0))
  {
    char mfn[2048];
    int countColumns;
    FILE *newFile;

    assert(adef->useMultipleModel);

    strcpy(mfn, secondaryStructureFileName);
    strcat(mfn, ".");
    strcat(mfn, excludeFileName);

    newFile = myfopen(mfn, "wb");

    printBothOpen("\nA secondary structure file with analogous structure assignments for non-excluded columns is printed to file %s\n", mfn);        	     	    

    for(i = 1, countColumns = 0; i <= rdta->sites; i++)
    {		  
      if(excludeArray[i] == -1)
        fprintf(newFile, "%c", tr->secondaryStructureInput[i - 1]);
      else
        countColumns++;
    }

    assert(countColumns == excludedColumns);

    fprintf(newFile,"\n");

    fclose(newFile);
  }


  if(adef->useMultipleModel && (excludedColumns > 0))
  {      
    char mfn[2048];
    FILE *newFile;

    strcpy(mfn, modelFileName);
    strcat(mfn, ".");
    strcat(mfn, excludeFileName);

    newFile = myfopen(mfn, "wb");

    printf("\nA partition file with analogous model assignments for non-excluded columns is printed to file %s\n", mfn);     

    for(i = 0; i < tr->NumberOfModels; i++)
    {
      boolean modelStillExists = FALSE;

      for(j = 1; (j <= rdta->sites) && (!modelStillExists); j++)
      {
        if(modelList[j] == i)
          modelStillExists = TRUE;
      }

      if(modelStillExists)
      {	  	      
        int k = 1;
        int lower, upper;
        int parts = 0;

        switch(tr->partitionData[i].dataType)
        {
          case AA_DATA:		      		     
            {
              char AAmodel[1024];

              strcpy(AAmodel, protModels[tr->partitionData[i].protModels]);
              if(tr->partitionData[i].protFreqs)
                strcat(AAmodel, "F");		  

              fprintf(newFile, "%s, ", AAmodel);
            }
            break;
          case DNA_DATA:
            fprintf(newFile, "DNA, ");
            break;
          case BINARY_DATA:
            fprintf(newFile, "BIN, ");
            break;
          case GENERIC_32:
            fprintf(newFile, "MULTI, ");
            break;
          case GENERIC_64:
            fprintf(newFile, "CODON, ");
            break;
          default:
            assert(0);
        }

        fprintf(newFile, "%s = ", tr->partitionData[i].partitionName);

        while(k <= rdta->sites)
        {
          if(modelList[k] == i)
          {
            lower = k;
            while((modelList[k + 1] == i) && (k <= rdta->sites))		      			
              k++;
            upper = k;

            if(lower == upper)		  
            {
              if(parts == 0)
                fprintf(newFile, "%d", lower);
              else
                fprintf(newFile, ",%d", lower);
            }
            else
            {
              if(parts == 0)
                fprintf(newFile, "%d-%d", lower, upper);
              else
                fprintf(newFile, ",%d-%d", lower, upper);
            }		  
            parts++;
          }
          k++;
        }
        fprintf(newFile, "\n");
      }		  
    }	
    fclose(newFile);
  }


  {
    FILE *newFile;
    char mfn[2048];


    strcpy(mfn, seq_file);
    strcat(mfn, ".");
    strcat(mfn, excludeFileName);

    newFile = myfopen(mfn, "wb");

    printf("\nAn alignment file with excluded columns is printed to file %s\n\n\n", mfn);

    fprintf(newFile, "%d %d\n", tr->mxtips, rdta->sites - excludedColumns);

    for(i = 1; i <= tr->mxtips; i++)
    {   
      unsigned char *tipI =  &(rdta->y[i][1]);
      fprintf(newFile, "%s ", tr->nameList[i]);

      for(j = 0; j < rdta->sites; j++)
      {
        if(excludeArray[j + 1] == -1)	      
          fprintf(newFile, "%c", getInverseMeaning(tr->dataVector[j + 1], tipI[j]));	       	  
      }

      fprintf(newFile, "\n");
    }

    fclose(newFile);
  }


  fclose(f);
  for(i = 0; i < numberOfModels; i++)
    free(partitions[i]);
  free(partitions);  
  free(excludeArray);
  free(countArray);
  free(modelList);
}
Ejemplo n.º 5
0
static bool isIdent (char c)
{
	return isNum (c) || isAlpha (c) || c == '_';
}
Ejemplo n.º 6
0
static inline bool	isIdentifierChar	(char c) { return isAlpha(c) || isNum(c) || c == '_'; }
Ejemplo n.º 7
0
bool Lexer::GetToken(Token&obj)
{
	string strBuf;
	int id;
	DataValue dv;
	while (!isEOF())
	{
		skipWS();
		/////////////
		//  Check for chr/strlit
		//
		if (nextChar() == '-')
			bool b=true;
		if (nextChar() == '\'' || nextChar() == '\"')
		{
			char ch = getChar();
			strBuf =  "";
			while (!isEOF())
			{
				if  (nextChar() == '\r' || nextChar() == '\n')
				{
					dv.SetStrData("Newline in constant.");
					throw Token(Token::LEX_ERROR,dv);
				}
				if (nextChar() == ch)
				{
					getChar();
					if (ch == '\'')
					{
						if (strBuf.length() != 1)
						{
							dv.SetStrData("Character literals must have exactly one character.");
							throw Token(Token::LEX_ERROR,dv);
						}
						dv.SetCharData(strBuf[0]);
						obj=Token(Token::LEX_CHRLIT,dv);
						return true;
					}
					else
					{
						dv.SetStrData(strBuf);
						obj=Token(Token::LEX_STRLIT,dv);
						return true;
					}
				}
				strBuf += getChar();
			}
			dv.SetStrData("EOF in constant.");
			throw Token(Token::LEX_ERROR,dv);
		}
		/////////////
		//  Check for Operators, then keywords
		//
		StorePosition();
		
		id = dfaOperators.GetString(strBuf);
		if (id == 0)
		{
			ResetPosition();
			id = dfaKeywords.GetString(strBuf);
			if (id == 0)
			{

				/////////////
				//  Check for numbers/idents
				//
				while (!isEOF() && !isWS(nextChar()) && !dfaOperators.ValidFirst(nextChar()))
				{
					strBuf += toLower(getChar());
				}
				//if it's all numbers
				if (strBuf.find_first_not_of("0123456789",0,10) == string::npos)
				{
					//read in anything, including dots  (will cover floats and invalid idents)
					while (!isEOF() && !isWS(nextChar()) && (nextChar() == '.' || !dfaOperators.ValidFirst(nextChar())))
					{
						strBuf += toLower(getChar());
					}
				}
				bool found = false;
				if (strBuf.find_first_not_of("0123456789.",0,11) == string::npos)
				{
					string::size_type off;
					off = strBuf.find('.',0);
					if (off == string::npos)
					{
						dv.SetIntData(atoi(strBuf.c_str()));
						obj=Token(Token::LEX_INTLIT,dv);
						return true;
					}
					else
					{
						if (strBuf.find('.',off+1) == string::npos)
						{
							dv.SetFloatData(atof(strBuf.c_str()));
							obj=Token(Token::LEX_FLOLIT,dv);
							return true;
						}
					}
				}
				//validate identifier
				try
				{
					if (strBuf.length() > 20)
						throw 2;
					for (string::iterator it = strBuf.begin();it != strBuf.end();++it)
					{
						if (it == strBuf.begin())
						{
							if (!isAlpha(*it))
							{
								throw 0;
							}
						}
						if (!isAlpha(*it) && *it != '_' && !isNum(*it))
						{
							throw 1;
						}
					}
				} catch(int iError)
				{
					switch (iError)
					{
						case 0:
							dv.SetStrData("Unrecognized lexeme ("+strBuf+"): identifiers must begin with a letter.");
							throw Token(Token::LEX_ERROR,dv);
						case 1:
							dv.SetStrData("Unrecognized lexeme ("+strBuf+"): identifiers can only contain underscores and alphanumeric characters.");
							throw Token(Token::LEX_ERROR,dv);
						case 2:
							dv.SetStrData("Unrecognized lexeme ("+strBuf+"): identifiers can be at most 20 characters long.");
							throw Token(Token::LEX_ERROR,dv);
					}
				}
				dv.SetStrData(strBuf);
				obj=Token(Token::LEX_IDENT,dv);
				return true;
			}
		}
		if (id)
		{
			dv.Clear();
			obj=Token((Token::TokenType)id,dv);
			return true;
		}
		dv.SetStrData("Undefined error.");
		throw Token(Token::LEX_ERROR,dv);
	}
	//int 0 means eof
	dv.SetStrData("EOF");
	obj=Token(Token::LEX_ERROR,dv);
	return false;
}
Ejemplo n.º 8
0
static Tree simplification (Tree sig)
{
	assert(sig);
	int		opnum;
	Tree	t1, t2, t3, t4;

	xtended* xt = (xtended*) getUserData(sig);
	// primitive elements
	if (xt)
	{
		//return 3;
		vector<Tree> args;
		for (int i=0; i<sig->arity(); i++) { args.push_back( sig->branch(i) ); }

        // to avoid negative power to further normalization
        if (xt != gPowPrim) {
            return xt->computeSigOutput(args);
        } else {
            return normalizeAddTerm(xt->computeSigOutput(args));
        }

	} else if (isSigBinOp(sig, &opnum, t1, t2)) {

		BinOp* op = gBinOpTable[opnum];

		Node n1 = t1->node();
		Node n2 = t2->node();

		if (isNum(n1) && isNum(n2)) 		return tree(op->compute(n1,n2));

		else if (op->isLeftNeutral(n1)) 	return t2;

		else if (op->isRightNeutral(n2)) 	return t1;

		else 								return normalizeAddTerm(sig);

	} else if (isSigDelay1(sig, t1)) {

		return normalizeDelay1Term (t1);

	} else if (isSigFixDelay(sig, t1, t2)) {

		return normalizeFixedDelayTerm (t1, t2);

	} else if (isSigIntCast(sig, t1)) {

		Tree 	tx;
		int		i;
		double 	x;
		Node 	n1 = t1->node();

		if (isInt(n1, &i)) 			return t1;
		if (isDouble(n1, &x)) 		return tree(int(x));
		if (isSigIntCast(t1, tx)) 	return t1;

		return sig;

	} else if (isSigFloatCast(sig, t1)) {

		Tree 	tx;
		int		i;
		double 	x;
		Node 	n1 = t1->node();

		if (isInt(n1, &i)) 				return tree(double(i));
		if (isDouble(n1, &x)) 			return t1;
		if (isSigFloatCast(t1, tx)) 	return t1;

		return sig;

     } else if (isSigSelect2(sig, t1, t2, t3)){

        Node n1 = t1->node();

        if (isZero(n1)) return t2;
        if (isNum(n1))  return t3;

        if (t2==t3) return t2;

        return sig;

    } else if (isSigSelect3(sig, t1, t2, t3, t4)){

        Node n1 = t1->node();

        if (isZero(n1)) return t2;
        if (isOne(n1))  return t3;
        if (isNum(n1))  return t4;

        if (t3==t4) return simplification(sigSelect2(t1,t2,t3));

        return sig;

	} else {

		return sig;
	}
}
Ejemplo n.º 9
0
int main(int argc, char *argv[])
{
  lprec *lp = NULL;
  char *filen, *wlp = NULL, *wmps = NULL, *wfmps = NULL, plp = FALSE;
  int i;
  int verbose = IMPORTANT /* CRITICAL */;
  int debug = -1;
  MYBOOL report = FALSE;
  MYBOOL nonames = FALSE, norownames = FALSE, nocolnames = FALSE;
  MYBOOL write_model_after = FALSE;
  MYBOOL noint = FALSE;
  int print_sol = -1;
  MYBOOL print_stats = FALSE;
  int floor_first = -1;
  MYBOOL do_set_bb_depthlimit = FALSE;
  int bb_depthlimit = 0;
  MYBOOL do_set_solutionlimit = FALSE;
  int solutionlimit = 0;
  MYBOOL break_at_first = FALSE;
  int scaling = 0;
  double scaleloop = 0;
  MYBOOL tracing = FALSE;
  short filetype = filetypeLP;
  int anti_degen1 = -1;
  int anti_degen2 = -1;
  short print_timing = FALSE;
  short parse_only = FALSE;
  int do_presolve = -1;
  short objective = 0;
  short PRINT_SOLUTION = 2;
  int improve = -1;
  int pivoting1 = -1;
  int pivoting2 = -1;
  int bb_rule1 = -1;
  int bb_rule2 = -1;
  int max_num_inv = -1;
  int scalemode1 = -1;
  int scalemode2 = -1;
  int crashmode = -1;
  char *guessbasis = NULL;
  /* short timeoutok = FALSE; */
  long sectimeout = -1;
  int result;
  MYBOOL preferdual = AUTOMATIC;
  int simplextype = -1;
  MYBOOL do_set_obj_bound = FALSE;
  REAL obj_bound = 0;
  REAL mip_absgap = -1;
  REAL mip_relgap = -1;
  REAL epsperturb = -1;
  REAL epsint = -1;
  REAL epspivot = -1;
  REAL epsd = -1;
  REAL epsb = -1;
  REAL epsel = -1;
  MYBOOL do_set_break_at_value = FALSE;
  REAL break_at_value = 0;
  REAL accuracy_error0, accuracy_error = -1;
  FILE *fpin = stdin;
  char *bfp = NULL;
  char *rxliname = NULL, *rxli = NULL, *rxlidata = NULL, *rxlioptions = NULL, *wxliname = NULL, *wxlisol = NULL, *wxli = NULL, *wxlioptions = NULL, *wxlisoloptions = NULL;
  char *rbasname = NULL, *wbasname = NULL;
  char *debugdump_before = NULL;
  char *debugdump_after = NULL;
  char *rparname = NULL;
  char *rparoptions = NULL;
  char *wparname = NULL;
  char *wparoptions = NULL;
  char obj_in_basis = -1;
  char mps_ibm = FALSE;
  char mps_negobjconst = FALSE;
  char mps_free = FALSE;
  MYBOOL ok;
# define SCALINGTHRESHOLD 0.03

  /* read command line arguments */

# if defined FORTIFY
   Fortify_EnterScope();
# endif

  for(i = 1; i < argc; i++) {
    ok = FALSE;
    if(strncmp(argv[i], "-v", 2) == 0) {
      if (argv[i][2])
        verbose = atoi(argv[i] + 2);
      else
        verbose = NORMAL;
    }
    else if(strcmp(argv[i], "-d") == 0)
      debug = TRUE;
    else if(strcmp(argv[i], "-R") == 0)
      report = TRUE;
    else if(strcmp(argv[i], "-i") == 0)
      print_sol = TRUE;
    else if(strcmp(argv[i], "-ia") == 0)
      print_sol = AUTOMATIC;
    else if(strcmp(argv[i], "-stat") == 0)
      print_stats = TRUE;
    else if(strcmp(argv[i], "-nonames") == 0)
      nonames = TRUE;
    else if(strcmp(argv[i], "-norownames") == 0)
      norownames = TRUE;
    else if(strcmp(argv[i], "-nocolnames") == 0)
      nocolnames = TRUE;
    else if((strcmp(argv[i], "-c") == 0) || (strcmp(argv[i], "-cc") == 0))
      floor_first = BRANCH_CEILING;
    else if(strcmp(argv[i], "-cf") == 0)
      floor_first = BRANCH_FLOOR;
    else if(strcmp(argv[i], "-ca") == 0)
      floor_first = BRANCH_AUTOMATIC;
    else if((strcmp(argv[i], "-depth") == 0) && (i + 1 < argc)) {
      do_set_bb_depthlimit = TRUE;
      bb_depthlimit = atoi(argv[++i]);
    }
    else if(strcmp(argv[i], "-Bw") == 0)
      or_value(&bb_rule2, NODE_WEIGHTREVERSEMODE);
    else if(strcmp(argv[i], "-Bb") == 0)
      or_value(&bb_rule2, NODE_BRANCHREVERSEMODE);
    else if(strcmp(argv[i], "-Bg") == 0)
      or_value(&bb_rule2, NODE_GREEDYMODE);
    else if(strcmp(argv[i], "-Bp") == 0)
      or_value(&bb_rule2, NODE_PSEUDOCOSTMODE);
    else if(strcmp(argv[i], "-BR") == 0)
      or_value(&bb_rule2, NODE_PSEUDORATIOSELECT);
    else if(strcmp(argv[i], "-Bf") == 0)
      or_value(&bb_rule2, NODE_DEPTHFIRSTMODE);
    else if(strcmp(argv[i], "-Br") == 0)
      or_value(&bb_rule2, NODE_RANDOMIZEMODE);
    else if(strcmp(argv[i], "-BG") == 0)
      or_value(&bb_rule2, 0 /* NODE_GUBMODE */); /* doesn't work yet */
    else if(strcmp(argv[i], "-Bd") == 0)
      or_value(&bb_rule2, NODE_DYNAMICMODE);
    else if(strcmp(argv[i], "-Bs") == 0)
      or_value(&bb_rule2, NODE_RESTARTMODE);
    else if(strcmp(argv[i], "-BB") == 0)
      or_value(&bb_rule2, NODE_BREADTHFIRSTMODE);
    else if(strcmp(argv[i], "-Bo") == 0)
      or_value(&bb_rule2, NODE_AUTOORDER);
    else if(strcmp(argv[i], "-Bc") == 0)
      or_value(&bb_rule2, NODE_RCOSTFIXING);
    else if(strcmp(argv[i], "-Bi") == 0)
      or_value(&bb_rule2, NODE_STRONGINIT);
    else if(strncmp(argv[i], "-B", 2) == 0) {
      if (argv[i][2])
        set_value(&bb_rule1, atoi(argv[i] + 2));
      else
        set_value(&bb_rule1, NODE_FIRSTSELECT);
    }
    else if((strcmp(argv[i], "-n") == 0) && (i + 1 < argc)) {
      do_set_solutionlimit = TRUE;
      solutionlimit = atoi(argv[++i]);
    }
    else if((strcmp(argv[i], "-b") == 0) && (i + 1 < argc)) {
      obj_bound = atof(argv[++i]);
      do_set_obj_bound = TRUE;
    }
    else if(((strcmp(argv[i], "-g") == 0) || (strcmp(argv[i], "-ga") == 0)) && (i + 1 < argc))
      mip_absgap = atof(argv[++i]);
    else if((strcmp(argv[i], "-gr") == 0) && (i + 1 < argc))
      mip_relgap = atof(argv[++i]);
    else if((strcmp(argv[i], "-e") == 0) && (i + 1 < argc)) {
      epsint = atof(argv[++i]);
      if((epsint <= 0.0) || (epsint >= 0.5)) {
        fprintf(stderr, "Invalid tolerance %g; 0 < epsilon < 0.5\n",
                (double)epsint);
        EndOfPgr(FORCED_EXIT);
      }
    }
    else if((strcmp(argv[i], "-r") == 0) && (i + 1 < argc))
      max_num_inv = atoi(argv[++i]);
    else if((strcmp(argv[i], "-o") == 0) && (i + 1 < argc)) {
      break_at_value = atof(argv[++i]);
      do_set_break_at_value = TRUE;
    }
    else if(strcmp(argv[i], "-f") == 0)
      break_at_first = TRUE;
    else if(strcmp(argv[i], "-timeoutok") == 0)
      /* timeoutok = TRUE */; /* option no longer needed, but still accepted */
    else if(strcmp(argv[i], "-h") == 0) {
      print_help(argv);
      EndOfPgr(EXIT_SUCCESS);
    }
    else if(strcmp(argv[i], "-prim") == 0)
      preferdual = FALSE;
    else if(strcmp(argv[i], "-dual") == 0)
      preferdual = TRUE;
    else if(strcmp(argv[i], "-simplexpp") == 0)
      simplextype = SIMPLEX_PRIMAL_PRIMAL;
    else if(strcmp(argv[i], "-simplexdp") == 0)
      simplextype = SIMPLEX_DUAL_PRIMAL;
    else if(strcmp(argv[i], "-simplexpd") == 0)
      simplextype = SIMPLEX_PRIMAL_DUAL;
    else if(strcmp(argv[i], "-simplexdd") == 0)
      simplextype = SIMPLEX_DUAL_DUAL;
    else if(strcmp(argv[i], "-sp") == 0)
      or_value(&scalemode2, SCALE_POWER2);
    else if(strcmp(argv[i], "-si") == 0)
      or_value(&scalemode2, SCALE_INTEGERS);
    else if(strcmp(argv[i], "-se") == 0)
      or_value(&scalemode2, SCALE_EQUILIBRATE);
    else if(strcmp(argv[i], "-sq") == 0)
      or_value(&scalemode2, SCALE_QUADRATIC);
    else if(strcmp(argv[i], "-sl") == 0)
      or_value(&scalemode2, SCALE_LOGARITHMIC);
    else if(strcmp(argv[i], "-sd") == 0)
      or_value(&scalemode2, SCALE_DYNUPDATE);
    else if(strcmp(argv[i], "-sr") == 0)
      or_value(&scalemode2, SCALE_ROWSONLY);
    else if(strcmp(argv[i], "-sc") == 0)
      or_value(&scalemode2, SCALE_COLSONLY);
    else if(strncmp(argv[i], "-s", 2) == 0) {
      set_value(&scalemode1, SCALE_NONE);
      scaling = SCALE_MEAN;
      if (argv[i][2]) {
        switch (atoi(argv[i] + 2)) {
        case 0:
          scaling = SCALE_NONE;
          break;
        case 1:
          set_value(&scalemode1, SCALE_GEOMETRIC);
          break;
        case 2:
          set_value(&scalemode1, SCALE_CURTISREID);
          break;
        case 3:
          set_value(&scalemode1, SCALE_EXTREME);
          break;
        case 4:
          set_value(&scalemode1, SCALE_MEAN);
          break;
        case 5:
          set_value(&scalemode1, SCALE_MEAN | SCALE_LOGARITHMIC);
          break;
        case 6:
          set_value(&scalemode1, SCALE_RANGE);
          break;
        case 7:
          set_value(&scalemode1, SCALE_MEAN | SCALE_QUADRATIC);
          break;
        }
      }
      else
        set_value(&scalemode1, SCALE_MEAN);
      if((i + 1 < argc) && (isNum(argv[i + 1])))
        scaleloop = atoi(argv[++i]);
    }
    else if(strncmp(argv[i], "-C", 2) == 0)
      crashmode = atoi(argv[i] + 2);
    else if((strcmp(argv[i],"-gbas") == 0) && (i + 1 < argc))
      guessbasis = argv[++i];
    else if(strcmp(argv[i], "-t") == 0)
      tracing = TRUE;
    else if(strncmp(argv[i], "-S", 2) == 0) {
      if (argv[i][2])
        PRINT_SOLUTION = (short) atoi(argv[i] + 2);
      else
        PRINT_SOLUTION = 2;
    }
    else if(strncmp(argv[i], "-improve", 8) == 0) {
      if (argv[i][8])
        or_value(&improve, atoi(argv[i] + 8));
    }
    else if(strcmp(argv[i], "-pivll") == 0)
      or_value(&pivoting2, PRICE_LOOPLEFT);
    else if(strcmp(argv[i], "-pivla") == 0)
      or_value(&pivoting2, PRICE_LOOPALTERNATE);
#if defined EnablePartialOptimization
    else if(strcmp(argv[i], "-pivpc") == 0)
      or_value(&pivoting2, PRICE_AUTOPARTIALCOLS);
    else if(strcmp(argv[i], "-pivpr") == 0)
      or_value(&pivoting2, PRICE_AUTOPARTIALROWS);
    else if(strcmp(argv[i], "-pivp") == 0)
      or_value(&pivoting2, PRICE_AUTOPARTIAL);
#endif
    else if(strcmp(argv[i], "-pivf") == 0)
      or_value(&pivoting2, PRICE_PRIMALFALLBACK);
    else if(strcmp(argv[i], "-pivm") == 0)
      or_value(&pivoting2, PRICE_MULTIPLE);
    else if(strcmp(argv[i], "-piva") == 0)
      or_value(&pivoting2, PRICE_ADAPTIVE);
    else if(strcmp(argv[i], "-pivr") == 0)
      or_value(&pivoting2, PRICE_RANDOMIZE);
    else if(strcmp(argv[i], "-pivh") == 0)
      or_value(&pivoting2, PRICE_HARRISTWOPASS);
    else if(strcmp(argv[i], "-pivt") == 0)
      or_value(&pivoting2, PRICE_TRUENORMINIT);
    else if(strncmp(argv[i], "-piv", 4) == 0) {
      if (argv[i][4])
        set_value(&pivoting1, atoi(argv[i] + 4));
      else
    set_value(&pivoting1, PRICER_DEVEX | PRICE_ADAPTIVE);
    }
#if defined PARSER_LP
    else if(strcmp(argv[i],"-lp") == 0)
      filetype = filetypeLP;
#endif
    else if((strcmp(argv[i],"-wlp") == 0) && (i + 1 < argc))
      wlp = argv[++i];
    else if(strcmp(argv[i],"-plp") == 0)
      plp = TRUE;
    else if(strcmp(argv[i],"-mps") == 0)
      filetype = filetypeMPS;
    else if(strcmp(argv[i],"-mps_ibm") == 0)
      mps_ibm = TRUE;
    else if(strcmp(argv[i],"-mps_negobjconst") == 0)
      mps_negobjconst = TRUE;
    else if(strcmp(argv[i],"-mps_free") == 0)
      mps_free = TRUE;
    else if(strcmp(argv[i],"-fmps") == 0)
      filetype = filetypeFREEMPS;
    else if((strcmp(argv[i],"-wmps") == 0) && (i + 1 < argc))
      wmps = argv[++i];
    else if((strcmp(argv[i],"-wfmps") == 0) && (i + 1 < argc))
      wfmps = argv[++i];
    else if(strcmp(argv[i],"-wafter") == 0)
      write_model_after = TRUE;
    else if(strcmp(argv[i],"-degen") == 0)
      set_value(&anti_degen1, ANTIDEGEN_DEFAULT);
    else if(strcmp(argv[i],"-degenf") == 0)
      or_value(&anti_degen2, ANTIDEGEN_FIXEDVARS);
    else if(strcmp(argv[i],"-degenc") == 0)
      or_value(&anti_degen2, ANTIDEGEN_COLUMNCHECK);
    else if(strcmp(argv[i],"-degens") == 0)
      or_value(&anti_degen2, ANTIDEGEN_STALLING);
    else if(strcmp(argv[i],"-degenn") == 0)
      or_value(&anti_degen2, ANTIDEGEN_NUMFAILURE);
    else if(strcmp(argv[i],"-degenl") == 0)
      or_value(&anti_degen2, ANTIDEGEN_LOSTFEAS);
    else if(strcmp(argv[i],"-degeni") == 0)
      or_value(&anti_degen2, ANTIDEGEN_INFEASIBLE);
    else if(strcmp(argv[i],"-degend") == 0)
      or_value(&anti_degen2, ANTIDEGEN_DYNAMIC);
    else if(strcmp(argv[i],"-degenb") == 0)
      or_value(&anti_degen2, ANTIDEGEN_DURINGBB);
    else if(strcmp(argv[i],"-degenr") == 0)
      or_value(&anti_degen2, ANTIDEGEN_RHSPERTURB);
    else if(strcmp(argv[i],"-degenp") == 0)
      or_value(&anti_degen2, ANTIDEGEN_BOUNDFLIP);
    else if(strcmp(argv[i],"-time") == 0) {
      if(clock() == -1)
        fprintf(stderr, "CPU times not available on this machine\n");
      else
        print_timing = TRUE;
    }
    else if((strcmp(argv[i],"-bfp") == 0) && (i + 1 < argc))
      bfp = argv[++i];
    else if((strcmp(argv[i],"-rxli") == 0) && (i + 2 < argc)) {
      rxliname = argv[++i];
      rxli = argv[++i];
      fpin = NULL;
      filetype = filetypeXLI;
    }
    else if((strcmp(argv[i],"-rxlidata") == 0) && (i + 1 < argc))
      rxlidata = argv[++i];
    else if((strcmp(argv[i],"-rxliopt") == 0) && (i + 1 < argc))
      rxlioptions = argv[++i];
    else if((strcmp(argv[i],"-wxli") == 0) && (i + 2 < argc)) {
      wxliname = argv[++i];
      wxli = argv[++i];
    }
    else if((strcmp(argv[i],"-wxliopt") == 0) && (i + 1 < argc))
      wxlioptions = argv[++i];
    else if((strcmp(argv[i],"-wxlisol") == 0) && (i + 2 < argc)) {
      wxliname = argv[++i];
      wxlisol = argv[++i];
    }
    else if((strcmp(argv[i],"-wxlisolopt") == 0) && (i + 1 < argc))
      wxlisoloptions = argv[++i];
    else if((strcmp(argv[i],"-rbas") == 0) && (i + 1 < argc))
      rbasname = argv[++i];
    else if((strcmp(argv[i],"-wbas") == 0) && (i + 1 < argc))
      wbasname = argv[++i];
    else if((strcmp(argv[i],"-Db") == 0) && (i + 1 < argc))
      debugdump_before = argv[++i];
    else if((strcmp(argv[i],"-Da") == 0) && (i + 1 < argc))
      debugdump_after = argv[++i];
    else if((strcmp(argv[i],"-timeout") == 0) && (i + 1 < argc))
      sectimeout = atol(argv[++i]);
    else if((strcmp(argv[i],"-trej") == 0) && (i + 1 < argc))
      epspivot = atof(argv[++i]);
    else if((strcmp(argv[i],"-epsp") == 0) && (i + 1 < argc))
      epsperturb = atof(argv[++i]);
    else if((strcmp(argv[i],"-epsd") == 0) && (i + 1 < argc))
      epsd = atof(argv[++i]);
    else if((strcmp(argv[i],"-epsb") == 0) && (i + 1 < argc))
      epsb = atof(argv[++i]);
    else if((strcmp(argv[i],"-epsel") == 0) && (i + 1 < argc))
      epsel = atof(argv[++i]);
    else if(strcmp(argv[i],"-parse_only") == 0)
      parse_only = TRUE;
    else
      ok = TRUE;

    if(!ok)
      ;
    else if(strcmp(argv[i],"-presolverow") == 0)
      or_value(&do_presolve, PRESOLVE_ROWS);
    else if(strcmp(argv[i],"-presolvecol") == 0)
      or_value(&do_presolve, PRESOLVE_COLS);
    else if(strcmp(argv[i],"-presolve") == 0)
      or_value(&do_presolve, PRESOLVE_ROWS | PRESOLVE_COLS);
    else if(strcmp(argv[i],"-presolvel") == 0)
      or_value(&do_presolve, PRESOLVE_LINDEP);
    else if(strcmp(argv[i],"-presolves") == 0)
      or_value(&do_presolve, PRESOLVE_SOS);
    else if(strcmp(argv[i],"-presolver") == 0)
      or_value(&do_presolve, PRESOLVE_REDUCEMIP);
    else if(strcmp(argv[i],"-presolvek") == 0)
      or_value(&do_presolve, PRESOLVE_KNAPSACK);
    else if(strcmp(argv[i],"-presolveq") == 0)
      or_value(&do_presolve, PRESOLVE_ELIMEQ2);
    else if(strcmp(argv[i],"-presolvem") == 0)
      or_value(&do_presolve, PRESOLVE_MERGEROWS);
    else if(strcmp(argv[i],"-presolvefd") == 0)
      or_value(&do_presolve, PRESOLVE_COLFIXDUAL);
    else if(strcmp(argv[i],"-presolvebnd") == 0)
      or_value(&do_presolve, PRESOLVE_BOUNDS);
    else if(strcmp(argv[i],"-presolved") == 0)
      or_value(&do_presolve, PRESOLVE_DUALS);
    else if(strcmp(argv[i],"-presolvef") == 0)
      or_value(&do_presolve, PRESOLVE_IMPLIEDFREE);
    else if(strcmp(argv[i],"-presolveslk") == 0)
      or_value(&do_presolve, PRESOLVE_IMPLIEDSLK);
    else if(strcmp(argv[i],"-presolveg") == 0)
      or_value(&do_presolve, PRESOLVE_REDUCEGCD);
    else if(strcmp(argv[i],"-presolveb") == 0)
      or_value(&do_presolve, PRESOLVE_PROBEFIX);
    else if(strcmp(argv[i],"-presolvec") == 0)
      or_value(&do_presolve, PRESOLVE_PROBEREDUCE);
    else if(strcmp(argv[i],"-presolverowd") == 0)
      or_value(&do_presolve, PRESOLVE_ROWDOMINATE);
    else if(strcmp(argv[i],"-presolvecold") == 0)
      or_value(&do_presolve, PRESOLVE_COLDOMINATE);
    else if(strcmp(argv[i],"-min") == 0)
      objective = -1;
    else if(strcmp(argv[i],"-max") == 0)
      objective =  1;
    else if(strcmp(argv[i],"-noint") == 0)
      noint =  TRUE;
    else if((strcmp(argv[i],"-rpar") == 0) && (i + 1 < argc))
      i++;
    else if((strcmp(argv[i],"-rparopt") == 0) && (i + 1 < argc))
      i++;
    else if((strcmp(argv[i],"-wpar") == 0) && (i + 1 < argc))
      i++;
    else if((strcmp(argv[i],"-wparopt") == 0) && (i + 1 < argc))
      i++;
    else if(strcmp(argv[i],"-o0") == 0)
      obj_in_basis = FALSE;
    else if(strcmp(argv[i],"-o1") == 0)
      obj_in_basis = TRUE;
    else if((strcmp(argv[i], "-ac") == 0) && (i + 1 < argc))
      accuracy_error = atof(argv[++i]);
    else if(fpin == stdin) {
      filen = argv[i];
      if(*filen == '<')
        filen++;
      if((fpin = fopen(filen, "r")) == NULL) {
        print_help(argv);
        fprintf(stderr,"\nError, Unable to open input file '%s'\n",
                argv[i]);
        EndOfPgr(FORCED_EXIT);
      }
    }
    else {
      filen = argv[i];
      if(*filen != '>') {
        print_help(argv);
        fprintf(stderr, "\nError, Unrecognized command line argument '%s'\n",
                argv[i]);
        EndOfPgr(FORCED_EXIT);
      }
    }
  }

  signal(SIGABRT,/* (void (*) OF((int))) */ SIGABRT_func);

  if ((filetype != filetypeXLI) && (fpin == NULL)) {
    lp = NULL;
    fprintf(stderr, "Cannot combine -rxli option with -lp, -mps, -fmps.\n");
  }
  else {
    switch(filetype) {
  #if defined PARSER_LP
    case filetypeLP:
      lp = read_lp(fpin, verbose, NULL);
      break;
  #endif
    case filetypeMPS:
      lp = read_mps(fpin, verbose | (mps_free ? MPS_FREE : 0) | (mps_ibm ? MPS_IBM : 0) | (mps_negobjconst ? MPS_NEGOBJCONST : 0));
      break;
    case filetypeFREEMPS:
      lp = read_freemps(fpin, verbose | (mps_ibm ? MPS_IBM : 0) | (mps_negobjconst ? MPS_NEGOBJCONST : 0));
      break;
    case filetypeXLI:
      lp = read_XLI(rxliname, rxli, rxlidata, rxlioptions, verbose);
      break;
    }
  }

  if((fpin != NULL) && (fpin != stdin))
    fclose(fpin);

  if(print_timing)
    print_cpu_times("Parsing input");

  if(lp == NULL) {
    fprintf(stderr, "Unable to read model.\n");
    EndOfPgr(FORCED_EXIT);
  }

  for(i = 1; i < argc; i++) {
    if((strcmp(argv[i],"-rpar") == 0) && (i + 1 < argc)) {
      if(rparname != NULL) {
        if(!read_params(lp, rparname, rparoptions)) {
          fprintf(stderr, "Unable to read parameter file (%s)\n", rparname);
          delete_lp(lp);
          EndOfPgr(FORCED_EXIT);
        }
      }
      rparname = argv[++i];
    }
    else if((strcmp(argv[i],"-rparopt") == 0) && (i + 1 < argc))
      rparoptions = argv[++i];
    else if((strcmp(argv[i],"-wpar") == 0) && (i + 1 < argc))
      wparname = argv[++i];
    else if((strcmp(argv[i],"-wparopt") == 0) && (i + 1 < argc))
      wparoptions = argv[++i];
  }

  if(rparname != NULL)
    if(!read_params(lp, rparname, rparoptions)) {
      fprintf(stderr, "Unable to read parameter file (%s)\n", rparname);
      delete_lp(lp);
      EndOfPgr(FORCED_EXIT);
    }

  if((nonames) || (nocolnames))
    set_use_names(lp, FALSE, FALSE);
  if((nonames) || (norownames))
    set_use_names(lp, TRUE, FALSE);

  if(objective != 0) {
    if(objective == 1)
      set_maxim(lp);
    else
      set_minim(lp);
  }

  if (obj_in_basis != -1)
    set_obj_in_basis(lp, obj_in_basis);

  if(noint) { /* remove integer conditions */
    for(i = get_Ncolumns(lp); i >= 1; i--) {
      if(is_SOS_var(lp, i)) {
        fprintf(stderr, "Unable to remove integer conditions because there is at least one SOS constraint\n");
        delete_lp(lp);
        EndOfPgr(FORCED_EXIT);
      }
      set_semicont(lp, i, FALSE);
      set_int(lp, i, FALSE);
    }
  }

  if(!write_model_after)
    write_model(lp, plp, wlp, wmps, wfmps, wxli, NULL, wxliname, wxlioptions);

  if(print_stats)
    print_statistics(lp);

  if(parse_only) {
    if(!write_model_after) {
      delete_lp(lp);
      EndOfPgr(0);
    }
    /* else if(!sectimeout) */
      sectimeout = 1;
  }

  if(PRINT_SOLUTION >= 5)
    print_lp(lp);

#if 0
  put_abortfunc(lp,(abortfunc *) myabortfunc, NULL);
#endif

  if(sectimeout > 0)
    set_timeout(lp, sectimeout);
  if(print_sol >= 0)
    set_print_sol(lp, print_sol);
  if(epsint >= 0)
    set_epsint(lp, epsint);
  if(epspivot >= 0)
    set_epspivot(lp, epspivot);
  if(epsperturb >= 0)
    set_epsperturb(lp, epsperturb);
  if(epsd >= 0)
    set_epsd(lp, epsd);
  if(epsb >= 0)
    set_epsb(lp, epsb);
  if(epsel >= 0)
    set_epsel(lp, epsel);
  if(debug >= 0)
    set_debug(lp, (MYBOOL) debug);
  if(floor_first != -1)
    set_bb_floorfirst(lp, floor_first);
  if(do_set_bb_depthlimit)
    set_bb_depthlimit(lp, bb_depthlimit);
  if(do_set_solutionlimit)
    set_solutionlimit(lp, solutionlimit);
  if(tracing)
    set_trace(lp, tracing);
  if(do_set_obj_bound)
    set_obj_bound(lp, obj_bound);
  if(do_set_break_at_value)
    set_break_at_value(lp, break_at_value);
  if(break_at_first)
    set_break_at_first(lp, break_at_first);
  if(mip_absgap >= 0)
    set_mip_gap(lp, TRUE, mip_absgap);
  if(mip_relgap >= 0)
    set_mip_gap(lp, FALSE, mip_relgap);
  if((anti_degen1 != -1) || (anti_degen2 != -1)) {
    if((anti_degen1 == -1) || (anti_degen2 != -1))
      anti_degen1 = 0;
    if(anti_degen2 == -1)
      anti_degen2 = 0;
    set_anti_degen(lp, anti_degen1 | anti_degen2);
  }
  set_presolve(lp, ((do_presolve == -1) ? get_presolve(lp): do_presolve) | ((PRINT_SOLUTION >= 4) ? PRESOLVE_SENSDUALS : 0), get_presolveloops(lp));
  if(improve != -1)
    set_improve(lp, improve);
  if(max_num_inv >= 0)
    set_maxpivot(lp, max_num_inv);
  if(preferdual != AUTOMATIC)
    set_preferdual(lp, preferdual);
  if((pivoting1 != -1) || (pivoting2 != -1)) {
    if(pivoting1 == -1)
      pivoting1 = get_pivoting(lp) & PRICER_LASTOPTION;
    if(pivoting2 == -1)
      pivoting2 = 0;
    set_pivoting(lp, pivoting1 | pivoting2);
  }
  if((scalemode1 != -1) || (scalemode2 != -1)) {
    if(scalemode1 == -1)
      scalemode1 = get_scaling(lp) & SCALE_CURTISREID;
    if(scalemode2 == -1)
      scalemode2 = 0;
    set_scaling(lp, scalemode1 | scalemode2);
  }
  if(crashmode != -1)
    set_basiscrash(lp, crashmode);
  if((bb_rule1 != -1) || (bb_rule2 != -1)) {
    if(bb_rule1 == -1)
      bb_rule1 = get_bb_rule(lp) & NODE_USERSELECT;
    if(bb_rule2 == -1)
      bb_rule2 = 0;
    set_bb_rule(lp, bb_rule1 | bb_rule2);
  }
  if(simplextype != -1)
    set_simplextype(lp, simplextype);
  if(bfp != NULL)
    if(!set_BFP(lp, bfp)) {
      fprintf(stderr, "Unable to set BFP package.\n");
      delete_lp(lp);
      EndOfPgr(FORCED_EXIT);
    }
  if(debugdump_before != NULL)
    print_debugdump(lp, debugdump_before);
  if(report)
    put_msgfunc(lp, LPMessageCB, NULL, MSG_LPFEASIBLE | MSG_LPOPTIMAL | MSG_MILPFEASIBLE | MSG_MILPBETTER | MSG_PERFORMANCE);

  if(scaling) {
    if(scaleloop <= 0)
      scaleloop = 5;
    if(scaleloop - (int) scaleloop < SCALINGTHRESHOLD)
      scaleloop = (int) scaleloop + SCALINGTHRESHOLD;
    set_scalelimit(lp, scaleloop);
  }

  if (accuracy_error != -1)
    set_break_numeric_accuracy(lp, accuracy_error);

  if(guessbasis != NULL) {
    REAL *guessvector, a;
    int *basisvector;
    int Nrows = get_Nrows(lp);
    int Ncolumns = get_Ncolumns(lp);
    int col;
    char buf[50], *ptr;
    FILE *fp;

    if ((fp = fopen(guessbasis, "r")) != NULL) {
      guessvector = (REAL *) calloc(1+Ncolumns, sizeof(*guessvector));
      basisvector = (int *) malloc((1+Nrows+Ncolumns)*sizeof(*basisvector));
      if ((guessvector != NULL) && (basisvector != NULL)) {
        while ((!feof(fp)) && (fgets(buf, sizeof(buf), fp) != NULL)) {
          ptr = strrchr(buf, ':');
          if (ptr == NULL) {
            printf("Mallformed line: %s\n", buf);
          }
          else {
            a = atof(ptr + 1);
            while ((ptr > buf) && (isspace(ptr[-1])))
              ptr--;
            *ptr = 0;
            col = get_nameindex(lp, buf, FALSE);
            if (col < 1)
              printf("guess_basis: Unknown variable name %s\n", buf);
            else
              guessvector[col] = a;
          }
        }
        if (guess_basis(lp, guessvector, basisvector)) {
          if (!set_basis(lp, basisvector, TRUE))
            printf("Unable to set guessed basis.\n");
        }
        else
          printf("Unable to guess basis from provided variables.\n");
      }
      else
        printf("guess_basis: Out of memory.\n");
      if (basisvector != NULL)
        free(basisvector);
      if (guessvector != NULL)
        free(guessvector);
      fclose(fp);
    }
    else
      printf("Unable to open file %s\n", guessbasis);
  }

  if(rbasname != NULL)
    if(!read_basis(lp, rbasname, NULL)) {
      fprintf(stderr, "Unable to read basis file.\n");
      delete_lp(lp);
      EndOfPgr(FORCED_EXIT);
    }

  result = solve(lp);

  if(wbasname != NULL)
    if(!write_basis(lp, wbasname))
      fprintf(stderr, "Unable to write basis file.\n");

  if(write_model_after)
    write_model(lp, plp, wlp, wmps, wfmps, wxli, NULL, wxliname, wxlioptions);

  write_model(lp, FALSE, NULL, NULL, NULL, NULL, wxlisol, wxliname, wxlisoloptions);

  if(PRINT_SOLUTION >= 6)
    print_scales(lp);

  if((print_timing) && (!parse_only))
    print_cpu_times("solving");

  if(debugdump_after != NULL)
    print_debugdump(lp, debugdump_after);

  if(wparname != NULL)
    if(!write_params(lp, wparname, wparoptions)) {
      fprintf(stderr, "Unable to write parameter file (%s)\n", wparname);
      delete_lp(lp);
      EndOfPgr(FORCED_EXIT);
    }

  if(parse_only) {
    delete_lp(lp);
    EndOfPgr(0);
  }

/*
  if((timeoutok) && (result == TIMEOUT) && (get_solutioncount(lp) > 0))
    result = OPTIMAL;
*/

  switch(result) {
  case SUBOPTIMAL:
  case PRESOLVED:
  case OPTIMAL:
  case PROCBREAK:
  case FEASFOUND:
    if ((result == SUBOPTIMAL) && (PRINT_SOLUTION >= 1))
      printf("Suboptimal solution\n");

    if (result == PRESOLVED)
      printf("Presolved solution\n");

    if (PRINT_SOLUTION >= 1)
      print_objective(lp);

    if (PRINT_SOLUTION >= 2)
      print_solution(lp, 1);

    if (PRINT_SOLUTION >= 3)
      print_constraints(lp, 1);

    if (PRINT_SOLUTION >= 4)
      print_duals(lp);

    if(tracing)
      fprintf(stderr,
              "Branch & Bound depth: %d\nNodes processed: %.0f\nSimplex pivots: %.0f\nNumber of equal solutions: %d\n",
              get_max_level(lp), (REAL) get_total_nodes(lp), (REAL) get_total_iter(lp), get_solutioncount(lp));
    break;
  case NOMEMORY:
    if (PRINT_SOLUTION >= 1)
      printf("Out of memory\n");
    break;
  case INFEASIBLE:
    if (PRINT_SOLUTION >= 1)
      printf("This problem is infeasible\n");
    break;
  case UNBOUNDED:
    if (PRINT_SOLUTION >= 1)
      printf("This problem is unbounded\n");
    break;
  case PROCFAIL:
   if (PRINT_SOLUTION >= 1)
      printf("The B&B routine failed\n");
    break;
  case TIMEOUT:
    if (PRINT_SOLUTION >= 1)
      printf("Timeout\n");
    break;
  case USERABORT:
    if (PRINT_SOLUTION >= 1)
      printf("User aborted\n");
    break;
  case ACCURACYERROR:
    if (PRINT_SOLUTION >= 1)
      printf("Accuracy error\n");
    break;
  default:
    if (PRINT_SOLUTION >= 1)
      printf("lp_solve failed\n");
    break;
  }

  if (PRINT_SOLUTION >= 7)
    print_tableau(lp);

  delete_lp(lp);

  EndOfPgr(result);
  return(result);
}
Ejemplo n.º 10
0
 bool isNumber(const char *s) {
     if (s == NULL)
         return false;
     int state = 0;
     int i = 0;
     while (s[i] != '\0') {
         switch (state) {
             case 0: // init
                 if (s[i] == ' ') {
                     // do nothing
                 } else if (isSign(s[i])) {
                     state = 1;
                 } else if (isNum(s[i])) {
                     state = 2;
                 } else if (s[i] == '.') {
                     state = 3;  
                 } else {
                     return false;
                 }
                 break;
             case 1: // sign
                 if (isNum(s[i])) {
                     state = 2;
                 } else if (s[i] == '.') {
                     state = 3;
                 } else {
                     return false;
                 }
                 break;
             case 2: // num
                 if (isNum(s[i])) {
                     // do nothing  
                 } else if (s[i] == '.') {
                     state = 4;
                 } else if (s[i] == 'e') {
                     state = 5;
                 } else if (s[i] == ' ') {
                     state = 9;  
                 } else {
                     return false;
                 }
                 break;
             case 3: // start with '.'
                 if (isNum(s[i])) {
                     state = 6;
                 } else {
                     return false;
                 }
                 break;
             case 4: // num + '.'
                 if (isNum(s[i])) {
                     state = 6;
                 } else if (s[i] == 'e') {
                     state = 5;
                 } else if (s[i] == ' ') {
                     state = 9;
                 } else {
                     return false;
                 }
                 break;
             case 5: // 'e'
                 if (isSign(s[i])) {
                     state = 7;
                 } else if (isNum(s[i])) {
                     state = 8;
                 } else {
                     return false;
                 }
                 break;
             case 6: // '.' + num
                 if (isNum(s[i])) {
                     // do nothing
                 } else if (s[i] == 'e') {
                     state = 5;
                 } else if (s[i] == ' ') {
                     state = 9;
                 } else {
                     return false;
                 }
                 break;
             case 7: // sign after 'e'
                 if (isNum(s[i])) {
                     state = 8;
                 } else {
                     return false;
                 }
                 break;
             case 8: // num after 'e'
                 if (isNum(s[i])) {
                     // do nothing
                 } else if (s[i] == ' ') {
                     state = 9;
                 } else {
                     return false;
                 }
                 break;
             case 9: // trailing spaces
                 if (s[i] != ' ') {
                     return false;
                 }
                 break;
         }
         i++;
     }
     return (state == 2 || state == 4 || state == 6 || state == 8 || state == 9);
 }
Ejemplo n.º 11
0
// This function is modelled after sscanf, and supports a subset of its features. See sscanf documentation
// for information about the syntax it accepts.
static void parse(const char *line, const char *fmt, int field_count, va_list va) {
	char *str = strdup(line);
	const int len = strlen(str);
	for (int i = 0; i < len; ++i) {
		if (str[i] == '\t')
			str[i] = ' ';
	}

	char *format = strdup(fmt);
	const int formatlen = strlen(format);
	for (int i = 0; i < formatlen; ++i) {
		if (format[i] == '\t')
			format[i] = ' ';
	}

	int count = 0;
	const char *src = str;
	const char *end = str + len;
	for (int i = 0; i < formatlen; ++i) {
		if (format[i] == '%') {
			char code[10];
			char width[10];
			int j = 0;
			int jw = 0;
			bool inBrackets = false;
			while (++i < formatlen && !isCodeSeparator(format[i])) {
				char c = format[i];
				if (c == '[') {
					inBrackets = true;
				} else if (inBrackets && c == ']') {
					inBrackets = false;
				}
				if (!inBrackets && isNum(c)) {
					width[jw++] = c;
				} else {
					code[j++] = c;
				}
			}
			code[j] = '\0';
			width[jw] = '\0';

			void *var = va_arg(va, void *);
			if (strcmp(code, "n") == 0) {
				*(int*)var = src - str;
				continue;
			}

			char s[2000];

			unsigned int fieldWidth = 1;
			if (width[0] != '\0') {
				fieldWidth = atoi(width);
			}

			j = 0;
			if (code[0] == 'c') {
				for (unsigned int n = 0; n < fieldWidth; ++n) {
					s[j++] = src[0];
					++src;
				}
			} else if (code[0] == '[') {
				bool isNegated;
				char *allowed = parseCharacterClass(code, &isNegated);

				while (src != end) {
					bool inSet = strchr(allowed, src[0]) != NULL;
					if ((isNegated && inSet) || (!isNegated && !inSet))
						break;

					s[j++] = src[0];
					++src;
				}

				delete[] allowed;
			} else {
				char nextChar = format[i];
				while (src[0] == ' ') { //skip initial whitespace
					++src;
				}
				while (src != end && src[0] != nextChar && !isSeparator(src[0])) {
					s[j++] = src[0];
					++src;
				}
			}

			s[j] = '\0';
			--i;

			if (width[0] == '\0') {
				fieldWidth = strlen(s);
			}

			if (strcmp(code, "d") == 0) {
				*(int*)var = atoi(s);
			} else if (strcmp(code, "x") == 0) {
				*(int*)var = strtol(s, (char **) NULL, 16);
			} else if (strcmp(code, "f") == 0) {
				*(float*)var = str2float(s);
			} else if (strcmp(code, "c") == 0) {
				*(char*)var = s[0];
			} else if (strcmp(code, "s") == 0) {
				char *string = (char*)var;
				strncpy(string, s, fieldWidth);
				if (fieldWidth <= strlen(s)) {
					// add terminating \0
					string[fieldWidth] = '\0';
				}
			} else if (code[0] == '[') {
				char *string = (char*)var;
				strncpy(string, s, fieldWidth);
				string[fieldWidth-1] = '\0';
			} else {
				error("Code not handled: \"%s\" \"%s\"\n\"%s\" \"%s\"", code, s, line, fmt);
			}

			++count;
			continue;
		}

		while (src[0] == ' ') {
			++src;
		}
		if (src == end)
			break;

		if (src[0] != format[i] && format[i] != ' ') {
			error("Expected line of format '%s', got '%s'", fmt, line);
		}

		if (src == end)
			break;
		if (format[i] != ' ') {
			++src;
			if (src == end)
				break;
		}
	}
Ejemplo n.º 12
0
/// Checks if a character is a legal identifier
bool NepParser::checkIdentifier(char ch)
{	return isChar(ch) || isNum(ch) || isSpecial(ch); }
Ejemplo n.º 13
0
// returns 1 on success
int parseString(char *cmd, opRec *oprec) {
  int parsePt = 0;
  syntaxEnum syntaxPt = CH_OPTYPE;
  int i, readLen;
  char numTmp[PARSE_MAXNUM];
  
  // discard all case information
  i = 0;
  while( cmd[i] != '\0' ) {
    cmd[i] = tolower(cmd[i]);
    i++;
  }
  
  while( cmd[parsePt] != '\0' ) {
    switch( syntaxPt ) {
    case CH_OPTYPE:
      if( cmd[parsePt] == 'e' ) oprec->opType = CH_ENCRYPT;
      else if( cmd[parsePt] == 'd' ) oprec->opType = CH_DECRYPT;
      else {
	parseError(syntaxPt, "unrecognized enc/dec token");
	return -1;
      }
      parsePt++;
      syntaxPt = CH_KEYINDEX;
      break;
      
      // this gets skipped now actually
    case CH_KEYTYPE:
      if( cmd[parsePt] == 's' ) oprec->keyType = CH_SYM;
      else if( cmd[parsePt] == 'p' ) oprec->keyType = CH_PK;
      else {
	parseError(syntaxPt, "unrecognized keytype token");
	return -1;
      }
      parsePt++;
      syntaxPt = CH_KEYINDEX;
      break;
      
    case CH_KEYINDEX:
      for( i = 0; i < PARSE_MAXNUM; i++ )
	numTmp[i] = '\0';
      i = 0;
      while( isNum(cmd[parsePt + i] ) ) {
	numTmp[i] = cmd[parsePt + i];
	i++;
      }
      numTmp[i] = '\0';
      oprec->keyIndex = atoi(numTmp);
      if( oprec->keyIndex > MAX_KEY_INDEX ) {
	parseError(syntaxPt, "keyIndex is out of bound" );
	return -1;
      }
      parsePt++;
      syntaxPt = CH_CTYPE;
      break;
      
    case CH_CTYPE:
      for( i = 0; i < 3; i++ ) {
	numTmp[i] = cmd[parsePt++];
      }
      numTmp[i] = '\0';
      if( strcmp( numTmp, "aes" ) == 0 ) { 
	oprec->cipherType = CH_AES; oprec->keyType = CH_SYM; 
      } else if( strcmp( numTmp, "sgn" ) == 0 ) { 
	oprec->cipherType = CH_SGN; oprec->keyType = CH_PK; 
      } else if( strcmp( numTmp, "vrf" ) == 0 ) { 
	oprec->cipherType = CH_VRF; oprec->keyType = CH_PK; 
      } else if( strcmp( numTmp, "sha" ) == 0 ) {
	oprec->cipherType = CH_SHA; oprec->keyType = CH_SYM;
      } else {
	parseError(syntaxPt, "cipher type is unrecognized");
	return -1;
      }
      syntaxPt = CH_DATA;
      break;
      
    case CH_DATA:
      readLen = 0;
      while( (cmd[parsePt] != '\0') && (cmd[parsePt] != '\n') ) {
	if( readLen > oprec->dataLen ) {
	  parseError(syntaxPt, "data length exceeds available buffer space");
	  return -1;
	}
	// check if this is a hex digit
	if( !isNum(cmd[parsePt]) && !(cmd[parsePt] <= 'f' && cmd[parsePt] >= 'a') ) {
	  parseError(syntaxPt, "non hex digits in data");
	  return -1;
	}
	(oprec->data)[readLen] = cmd[parsePt];
	parsePt++; readLen++;
      } // while
      (oprec->data)[readLen] = '\0';
      oprec->dataLen = readLen;
      return 1;
      break;

    default:
      fprintf(stderr, "Error in parseString()\n" );
      return(-1);
    } // switch syntaxPt
    if( (cmd[parsePt] != ':') ) {
      parseError(syntaxPt, "missing delimiter" );
      return -1;
    }
    parsePt++;
  }

  // we should never reach this point, a successful parse leaves function at CH_DATA case
  parseError(syntaxPt, "unknown error, late failure in function");
  return -1;
}
Ejemplo n.º 14
0
static void listItem(Stack s, Action parent)
{
  Tree t;

  if(s->type == 's')
  {
    if(parent == SWFACTION_GETVARIABLE ||
       parent == SWFACTION_SETVARIABLE ||
       parent == SWFACTION_GETPROPERTY ||
       parent == SWFACTION_SETPROPERTY ||
       parent == SWFACTION_DUPLICATECLIP ||
       isNum(s->data.string))
      printf(s->data.string);
    else
    {
      putchar('\'');
      printf(s->data.string);
      putchar('\'');
    }
  }
  else if(s->type == 'p')
  {
    listProperty(s->data.prop);
  }
  else if(s->type == 't')
  {
    t = s->data.tree;

    switch(t->action)
      {
      case SWFACTION_POP: /* ignore */
	break;

	/* two args */
      case SWFACTION_ADD:
      case SWFACTION_SUBTRACT:
      case SWFACTION_MULTIPLY:
      case SWFACTION_DIVIDE:
      case SWFACTION_EQUAL:
      case SWFACTION_LOGICALAND:
      case SWFACTION_LOGICALOR:
      case SWFACTION_STRINGEQ:
      case SWFACTION_STRINGCOMPARE:
	listArithmetic(s, parent);
	break;

      case SWFACTION_STRINGCONCAT:
	if(parent == SWFACTION_GETVARIABLE ||
	   parent == SWFACTION_GETPROPERTY)
	{
	  printf("valueOf(");
	  listArithmetic(s, parent);
	  putchar(')');
	}
	else
	  listArithmetic(s, parent);
	break;

      case SWFACTION_SETVARIABLE:
	listAssign(s);
	break;

      case SWFACTION_LESSTHAN:
	listLessThan(s, NONEGATE);
	break;

      case SWFACTION_GETPROPERTY:
	if(t->left->type == 's' &&
	   t->left->data.string[0] == '\0')
	  printf("this");
	else
	  listItem(t->left, SWFACTION_GETPROPERTY);

	putchar('.');
	listItem(t->right, SWFACTION_GETPROPERTY);
	break;

      case SWFACTION_SETPROPERTY:
	if(t->left->type == 's' &&
	   t->left->data.string[0] == '\0')
	  printf("this");
	else
	  listItem(t->left, SWFACTION_SETPROPERTY);

	putchar('.');
	listItem(t->right, SWFACTION_SETPROPERTY);
	break;

      case SWFACTION_MBSUBSTRING:
      case SWFACTION_SUBSTRING:
	printf("substr(");
	listItem(t->left, t->action);
	printf(", ");
	listItem(t->right->data.tree->left, t->action);
	printf(", ");
	listItem(t->right->data.tree->right, t->action);
	putchar(')');
	break;
      
	/* one-arg */
      case SWFACTION_LOGICALNOT:
	listNot(t->left, SWFACTION_LOGICALNOT);
	break;

      case SWFACTION_STRINGLENGTH:
	printf("strlen(");
	listItem(t->left, SWFACTION_STRINGLENGTH);
	putchar(')');
	break;

      case SWFACTION_INT:
	printf("int(");
	listItem(t->left, SWFACTION_INT);
	putchar(')');
	break;

      case SWFACTION_RANDOM:
	printf("random(");
	listItem(t->left, SWFACTION_RANDOM);
	putchar(')');
	break;

      case SWFACTION_MBLENGTH:
	printf("mbstrlen(");
	listItem(t->left, SWFACTION_MBLENGTH);
	putchar(')');
	break;

      case SWFACTION_ORD:
	printf("ord(");
	listItem(t->left, SWFACTION_ORD);
	putchar(')');
	break;

      case SWFACTION_CHR:
	printf("chr(");
	listItem(t->left, SWFACTION_CHR);
	putchar(')');
	break;

      case SWFACTION_MBORD:
	printf("mbord(");
	listItem(t->left, SWFACTION_MBORD);
	putchar(')');
	break;

      case SWFACTION_MBCHR:
	printf("mbchr(");
	listItem(t->left, SWFACTION_MBCHR);
	putchar(')');
	break;

      case SWFACTION_GETVARIABLE:
	listItem(t->left, SWFACTION_GETVARIABLE);
	break;

      case SWFACTION_GETTIMER:
	printf("getTimer()");
	break;

	/* statements */
      case SWFACTION_DUPLICATECLIP:
	printf("duplicateClip(");
	listItem(t->left, SWFACTION_DUPLICATECLIP);
	printf(", ");
	listItem(t->right->data.tree->left, SWFACTION_DUPLICATECLIP);
	printf(", ");
	listItem(t->right->data.tree->right, SWFACTION_DUPLICATECLIP);
	putchar(')');
	break;

      case SWFACTION_STARTDRAGMOVIE:
	printf("startDrag(");
	listItem(t->right->data.tree->right, SWFACTION_STARTDRAGMOVIE);
	printf(", ");
	listItem(t->right->data.tree->left, SWFACTION_STARTDRAGMOVIE);

	if(t->left->type == 't')
	{
	  Tree root = t->left->data.tree;
	  printf(", ");
	  listItem(root->left->data.tree->left, SWFACTION_STARTDRAGMOVIE);
	  printf(", ");
	  listItem(root->right->data.tree->left, SWFACTION_STARTDRAGMOVIE);
	  printf(", ");
	  listItem(root->left->data.tree->right, SWFACTION_STARTDRAGMOVIE);
	  printf(", ");
	  listItem(root->right->data.tree->right, SWFACTION_STARTDRAGMOVIE);
	}
	putchar(')');
	break;

      case SWFACTION_REMOVECLIP:
	printf("removeClip(");
	listItem(t->left, SWFACTION_REMOVECLIP);
	putchar(')');
	break;
      case SWFACTION_TRACE:
	printf("trace(");
	listItem(t->left, SWFACTION_TRACE);
	putchar(')');
	break;
      case SWFACTION_SETTARGETEXPRESSION:
	printf("setTarget(");
	listItem(t->left, SWFACTION_SETTARGETEXPRESSION);
	putchar(')');
	break;
      case SWFACTION_STOPDRAGMOVIE:
	printf("stopDrag()");
	break;
      case SWFACTION_NEXTFRAME:
	printf("nextFrame()");
	break;
      case SWFACTION_PREVFRAME:
	printf("prevFrame()");
	break;
      case SWFACTION_PLAY:
	printf("play()");
	break;
      case SWFACTION_STOP:
	printf("stop()");
	break;
      case SWFACTION_TOGGLEQUALITY:
	printf("toggleQuality()");
	break;
      case SWFACTION_STOPSOUNDS:
	printf("stopSounds()");
	break;

      case SWFACTION_GOTOFRAME:
	printf("gotoFrame(%i)", (int)t->left);
	break;

      case SWFACTION_GETURL:
      {
	printf("getURL('%s', '%s')", (char *)t->left, (char *)t->right);
	break;
      }

      case SWFACTION_WAITFORFRAMEEXPRESSION:
	printf("Wait For Frame Expression, skip %i", (int)t->left);
	break;

      case SWFACTION_GETURL2:
	printf("getURL(");
	listItem(t->right->data.tree->left, SWFACTION_GETURL2);
	printf(", ");
	listItem(t->right->data.tree->right, SWFACTION_GETURL2);

	switch((int)t->left)
	{
	  case 0: printf(")"); break;
	  case 1: printf(", GET)"); break;
	  case 2: printf(", POST)"); break;
	  default: printf(", 0x%x /* ??? */)", (int)t->left);
	}
	break;

      case SWFACTION_CALLFRAME:
	printf("callFrame(");
	listItem(t->left, SWFACTION_CALLFRAME);
        putchar(')');
	break;

      case SWFACTION_GOTOEXPRESSION:
	printf("gotoFrame(");
	listItem(t->left, SWFACTION_GOTOEXPRESSION);
        putchar(')');

	if((int)t->right == 1)
	  printf(";\nplay()");
	break;

      case SWFACTION_SETTARGET:
	if(((char *)t->left)[0] == '\0')
	  printf("setTarget(this)");
	else
	  printf("setTarget('%s')", (char *)t->left);
	break;

      case SWFACTION_GOTOLABEL:
	printf("gotoFrame('%s')", (char *)t->left);
	break;

	/* branches - shouldn't see these */
      case SWFACTION_BRANCHIFTRUE:
	printf("if(");
	listItem(t->left, SWFACTION_BRANCHIFTRUE);
	printf(") branch %i", (int)t->right);
	break;

      case SWFACTION_BRANCHALWAYS:
	printf("branch %i", (int)t->right);
	break;

      case SWFACTION_WAITFORFRAME:
	printf("Wait for frame %i ", (int)t->left);
	printf(" else skip %i", (int)t->right);
	break;

      default:
	break;
      }
  }
}
Ejemplo n.º 15
0
static ocamlKeyword eatNumber (lexingState * st)
{
	while (isNum (*st->cp))
		st->cp++;
	return Tok_Val;
}
Ejemplo n.º 16
0
bool isId(const std::string& s) {
	return !isNum(s);
}
Ejemplo n.º 17
0
/* The lexer is in charge of reading the file.
 * Some of sub-lexer (like eatComment) also read file.
 * lexing is finished when the lexer return Tok_EOF */
static ocamlKeyword lex (lexingState * st)
{
	int retType;
	/* handling data input here */
	while (st->cp == NULL || st->cp[0] == '\0')
	{
		st->cp = fileReadLine ();
		if (st->cp == NULL)
			return Tok_EOF;
	}

	if (isAlpha (*st->cp))
	{
		readIdentifier (st);
		retType = lookupKeyword (vStringValue (st->name), Lang_Ocaml);

		if (retType == -1)	/* If it's not a keyword */
		{
			return OcaIDENTIFIER;
		}
		else
		{
			return retType;
		}
	}
	else if (isNum (*st->cp))
		return eatNumber (st);
	else if (isSpace (*st->cp))
	{
		eatWhiteSpace (st);
		return lex (st);
	}
	/* OCaml permit the definition of our own operators
	 * so here we check all the consecuting chars which
	 * are operators to discard them. */
	else if (isOperator[*st->cp])
		return eatOperator (st);
	else
		switch (*st->cp)
		{
		case '(':
			if (st->cp[1] == '*')	/* ergl, a comment */
			{
				eatComment (st);
				return lex (st);
			}
			else
			{
				st->cp++;
				return Tok_PARL;
			}

		case ')':
			st->cp++;
			return Tok_PARR;
		case '[':
			st->cp++;
			return Tok_BRL;
		case ']':
			st->cp++;
			return Tok_BRR;
		case '{':
			st->cp++;
			return Tok_CurlL;
		case '}':
			st->cp++;
			return Tok_CurlR;
		case '\'':
			st->cp++;
			return Tok_Prime;
		case ',':
			st->cp++;
			return Tok_comma;
		case '=':
			st->cp++;
			return Tok_EQ;
		case ';':
			st->cp++;
			return Tok_semi;
		case '"':
			eatString (st);
			return Tok_Val;
		case '_':
			st->cp++;
			return Tok_Val;
		case '#':
			st->cp++;
			return Tok_Sharp;
		case '\\':
			st->cp++;
			return Tok_Backslash;

		default:
			st->cp++;
			break;
		}

	/* default return if nothing is recognized,
	 * shouldn't happen, but at least, it will
	 * be handled without destroying the parsing. */
	return Tok_Val;
}
Ejemplo n.º 18
0
// (for sym 'num ['any | (NIL 'any . prg) | (T 'any . prg) ..]) -> any
// (for sym|(sym2 . sym) 'lst ['any | (NIL 'any . prg) | (T 'any . prg) ..]) -> any
// (for (sym|(sym2 . sym) 'any1 'any2 [. prg]) ['any | (NIL 'any . prg) | (T 'any . prg) ..]) -> any
any doFor(any x) {
   any y, body, cond, a;
   cell c1;
   struct {  // bindFrame
      struct bindFrame *link;
      int i, cnt;
      struct {any sym; any val;} bnd[2];
   } f;

   f.link = Env.bind,  Env.bind = (bindFrame*)&f;
   f.i = 0;
   if (!isCell(y = car(x = cdr(x))) || !isCell(cdr(y))) {
      if (!isCell(y)) {
         f.cnt = 1;
         f.bnd[0].sym = y;
         f.bnd[0].val = val(y);
      }
      else {
         f.cnt = 2;
         f.bnd[0].sym = cdr(y);
         f.bnd[0].val = val(cdr(y));
         f.bnd[1].sym = car(y);
         f.bnd[1].val = val(car(y));
         val(f.bnd[1].sym) = Zero;
      }
      y = Nil;
      x = cdr(x),  Push(c1, EVAL(car(x)));
      if (isNum(data(c1)))
         val(f.bnd[0].sym) = Zero;
      body = x = cdr(x);
      for (;;) {
         if (isNum(data(c1))) {
            val(f.bnd[0].sym) = bigCopy(val(f.bnd[0].sym));
            digAdd(val(f.bnd[0].sym), 2);
            if (bigCompare(val(f.bnd[0].sym), data(c1)) > 0)
               break;
         }
         else {
            if (!isCell(data(c1)))
               break;
            val(f.bnd[0].sym) = car(data(c1));
            if (!isCell(data(c1) = cdr(data(c1))))
               data(c1) = Nil;
         }
         if (f.cnt == 2) {
            val(f.bnd[1].sym) = bigCopy(val(f.bnd[1].sym));
            digAdd(val(f.bnd[1].sym), 2);
         }
         do {
            if (!isNum(y = car(x))) {
               if (isSym(y))
                  y = val(y);
               else if (isNil(car(y))) {
                  y = cdr(y);
                  if (isNil(a = EVAL(car(y)))) {
                     y = prog(cdr(y));
                     goto for1;
                  }
                  val(At) = a;
                  y = Nil;
               }
               else if (car(y) == T) {
                  y = cdr(y);
                  if (!isNil(a = EVAL(car(y)))) {
                     val(At) = a;
                     y = prog(cdr(y));
                     goto for1;
                  }
                  y = Nil;
               }
               else
                  y = evList(y);
            }
         } while (isCell(x = cdr(x)));
         x = body;
      }
   for1:
      drop(c1);
      if (f.cnt == 2)
         val(f.bnd[1].sym) = f.bnd[1].val;
      val(f.bnd[0].sym) = f.bnd[0].val;
      Env.bind = f.link;
      return y;
   }
   if (!isCell(car(y))) {
      f.cnt = 1;
      f.bnd[0].sym = car(y);
      f.bnd[0].val = val(car(y));
   }
   else {
      f.cnt = 2;
      f.bnd[0].sym = cdar(y);
      f.bnd[0].val = val(cdar(y));
      f.bnd[1].sym = caar(y);
      f.bnd[1].val = val(caar(y));
      val(f.bnd[1].sym) = Zero;
   }
   y = cdr(y);
   val(f.bnd[0].sym) = EVAL(car(y));
   y = cdr(y),  cond = car(y),  y = cdr(y);
   Push(c1,Nil);
   body = x = cdr(x);
   while (!isNil(a = EVAL(cond))) {
      val(At) = a;
      if (f.cnt == 2) {
         val(f.bnd[1].sym) = bigCopy(val(f.bnd[1].sym));
         digAdd(val(f.bnd[1].sym), 2);
      }
      do {
         if (!isNum(data(c1) = car(x))) {
            if (isSym(data(c1)))
               data(c1) = val(data(c1));
            else if (isNil(car(data(c1)))) {
               data(c1) = cdr(data(c1));
               if (isNil(a = EVAL(car(data(c1))))) {
                  data(c1) = prog(cdr(data(c1)));
                  goto for2;
               }
               val(At) = a;
               data(c1) = Nil;
            }
            else if (car(data(c1)) == T) {
               data(c1) = cdr(data(c1));
               if (!isNil(a = EVAL(car(data(c1))))) {
                  val(At) = a;
                  data(c1) = prog(cdr(data(c1)));
                  goto for2;
               }
               data(c1) = Nil;
            }
            else
               data(c1) = evList(data(c1));
         }
      } while (isCell(x = cdr(x)));
      if (isCell(y))
         val(f.bnd[0].sym) = prog(y);
      x = body;
   }
for2:
   if (f.cnt == 2)
      val(f.bnd[1].sym) = f.bnd[1].val;
   val(f.bnd[0].sym) = f.bnd[0].val;
   Env.bind = f.link;
   return Pop(c1);
}
Ejemplo n.º 19
0
Archivo: bank.c Proyecto: scmilburn/ATM
void bank_process_local_command(Bank *bank, char *command, size_t len)
{
    // TODO: Implement the bank's local commands
    char *line = strtok (command," ");

    if(line != NULL){
        if(strcmp(line, "create-user") == 0){
            char *name = strtok(NULL, " ");
            char *pinStr = strtok(NULL, " ");
            char *balanceStr = strtok(NULL, " ");
            char *check = strtok(NULL, " ");

            if(name == NULL || pinStr == NULL || balanceStr == NULL || check != NULL){
                printf("Usage: create-user <user-name> <pin> <balance>\n");
            }
            else{
                if(strlen(name) > 250 || strlen(pinStr) != 4 || isChar(name, strlen(name)) == 0 || isNum(pinStr, 4) == 0 || isNum(balanceStr, strlen(balanceStr)-1) == 0){
                    printf("Usage: create-user <user-name> <pin> <balance>\n");
                }
                else{
                    unsigned int balance = atoi(balanceStr);
                    if(balance >= INT_MAX) 
                        printf("Usage: create-user <user-name> <pin> <balance>\n");
                    else{
                        Node *user = NULL;
                        if(bank->clientHead != NULL)
                            user = get_client(bank->clientHead, name);
                        if(user == NULL){
                            Node *put = malloc(sizeof(Node));
                            FILE *file;
                            char *filename = malloc(strlen(name) + 6);


                            memcpy(filename, name, strlen(name));
                            filename[strlen(name)] = '.';
                            filename[strlen(name)+1] = 'c';
                            filename[strlen(name)+2] = 'a';
                            filename[strlen(name)+3] = 'r';
                            filename[strlen(name)+4] = 'd';
                            filename[strlen(name)+5] = 0;

                            file = fopen(filename, "w+");

                            if(file != NULL){
                                EVP_MD_CTX *ctx = EVP_MD_CTX_create();
                                uint8_t thehash[32];
                                int hashlen;
                                uint32_t namelen = strlen(name);
                                uint8_t *data = malloc(4 + strlen(name) + 32);
                                put->name = malloc(strlen(name) + 1);

                                memcpy(put->name, name, namelen+1);

                                put->PIN[0] = pinStr[0];
                                put->PIN[1] = pinStr[1];
                                put->PIN[2] = pinStr[2];
                                put->PIN[3] = pinStr[3];

                                put->balance = balance;
                                put->next = bank->clientHead;
                                if(bank->clientHead != NULL)
                                    bank->clientHead->prev = put;
                                put->prev = NULL;
                                bank->clientHead = put;

                                EVP_DigestInit_ex(ctx, EVP_sha256(), NULL);

                                EVP_DigestUpdate(ctx, pinStr, 4);
                                EVP_DigestFinal_ex(ctx, thehash, &hashlen);

                                memcpy(data, &namelen, 4);
                                memcpy(data + 4, name, namelen);
                                memcpy(data + 4 + namelen, thehash, 32);

                                fwrite(data, 1, namelen + 36, file);
                                fclose(file);

                                printf("Created user %s\n", name);
                                free(data);
                                EVP_MD_CTX_destroy(ctx);
                            }
                            else
                                printf("Error creating card file for user %s\n", name);

                        
                            free(filename);
                        }
                        else{
                            printf("Error: user %s already exists\n", name);
                        }
                    }
                }
            }
        }
        else{
            if(strcmp(line, "deposit") == 0){
                char *name = strtok(NULL, " ");
                char *amtStr = strtok(NULL, " ");
                char *check = strtok(NULL, " ");
                if(name == NULL || amtStr == NULL || check != NULL)
                    printf("Usage: deposit <user-name> <amt>\n");
                else{
                    if(strlen(name) > 250 || isChar(name, strlen(name)) == 0 || isNum(amtStr, strlen(amtStr)-1) == 0){
                        printf("Usage: deposit <user-name> <amt>\n");
                    }
                    else{
                        unsigned int amt = atoi(amtStr);
                        if(amt >= INT_MAX)
                            printf("Too rich for this program\n");
                        else{  
                            Node *user = get_client(bank->clientHead, name);
                            if(user == NULL){
                                printf("No such user\n");
                            }
                            else{
                                unsigned int newbal = user->balance + amt;
                                if(newbal >= INT_MAX)
                                    printf("Too rich for this program\n");
                                else{
                                    user->balance = newbal;
                                    printf("$%u added to %s's account\n", amt, name);
                                }
                            }
                        }
                    }
                }

            }
            else{
                if(strcmp(line, "balance") == 0){
                    char *name = strtok(NULL, " ");
                    char *check = strtok(NULL, " ");
                    if(name == NULL || check != NULL)
                        printf("Usage: balance <user-name>\n");
                    else{
                        if(strlen(name) > 250 || isChar(name, strlen(name)-1) == 0){
                            printf("Usage: balance <user-name>\n");
                        }
                        else{
                            Node *user = NULL;

                            name[strlen(name)-1] = 0;

                            if(bank->clientHead != NULL)
                                user = get_client(bank->clientHead, name);

                            if(user == NULL){
                                printf("No such user\n");
                            }
                            else{
                                printf("$%u\n", user->balance);
                            }
                        }
                    }

                }
                else{
                    printf("Invalid command\n");
                }
            }
        }

    }
    else{
        printf("Invalid command\n");
    }

}
Ejemplo n.º 20
0
// (lit 'any) -> any
any doLit(any x) {
   x = cadr(x);
   if (isNum(x = EVAL(x)) || isNil(x) || x == T || isCell(x) && isNum(car(x)))
      return x;
   return cons(Quote, x);
}
void parsePartitions(analdef *adef, rawdata *rdta, tree *tr)
{
  FILE *f; 
  int numberOfModels = 0; 
  int nbytes = 0;
  char *ch;
  char *cc = (char *)NULL;
  char **p_names;
  int n, i, l;
  int lower, upper, modulo;
  char buf[256];
  int **partitions;
  int pairsCount;
  int as, j;
  int k; 

  f = myfopen(modelFileName, "rb");   


  while(myGetline(&cc, &nbytes, f) > -1)
  {     
    if(!lineContainsOnlyWhiteChars(cc))
    {
      numberOfModels++;
    }
    if(cc)
      free(cc);
    cc = (char *)NULL;
  }     

  rewind(f);

  p_names = (char **)malloc(sizeof(char *) * numberOfModels);
  partitions = (int **)malloc(sizeof(int *) * numberOfModels);



  tr->initialPartitionData = (pInfo*)malloc(sizeof(pInfo) * numberOfModels);


  for(i = 0; i < numberOfModels; i++) 
  {     
    tr->initialPartitionData[i].protModels = adef->proteinMatrix;
    tr->initialPartitionData[i].protFreqs  = adef->protEmpiricalFreqs;
    tr->initialPartitionData[i].dataType   = -1;
  }

  for(i = 0; i < numberOfModels; i++)    
    partitions[i] = (int *)NULL;

  i = 0;
  while(myGetline(&cc, &nbytes, f) > -1)
  {          
    if(!lineContainsOnlyWhiteChars(cc))
    {
      n = strlen(cc);	 
      p_names[i] = (char *)malloc(sizeof(char) * (n + 1));
      strcpy(&(p_names[i][0]), cc);
      i++;
    }
    if(cc)
      free(cc);
    cc = (char *)NULL;
  }         

  for(i = 0; i < numberOfModels; i++)
  {           
    ch = p_names[i];     
    pairsCount = 0;
    skipWhites(&ch);

    if(*ch == '=')
    {
      printf("Identifier missing prior to '=' in %s\n", p_names[i]);
      exit(-1);
    }

    analyzeIdentifier(&ch, i, tr);
    ch++;

numberPairs:
    pairsCount++;
    partitions[i] = (int *)realloc((void *)partitions[i], (1 + 3 * pairsCount) * sizeof(int));
    partitions[i][0] = pairsCount;
    partitions[i][3 + 3 * (pairsCount - 1)] = -1; 	

    skipWhites(&ch);

    if(!isNum(*ch))
    {
      printf("%c Number expected in %s\n", *ch, p_names[i]);
      exit(-1);
    }   

    l = 0;
    while(isNum(*ch))		 
    {
      /*printf("%c", *ch);*/
      buf[l] = *ch;
      ch++;	
      l++;
    }
    buf[l] = '\0';
    lower = atoi(buf);
    partitions[i][1 + 3 * (pairsCount - 1)] = lower;   

    skipWhites(&ch);

    /* NEW */

    if((*ch != '-') && (*ch != ','))
    {
      if(*ch == '\0' || *ch == '\n' || *ch == '\r')
      {
        upper = lower;
        goto SINGLE_NUMBER;
      }
      else
      {
        printf("'-' or ',' expected in %s\n", p_names[i]);
        exit(-1);
      }
    }	 

    if(*ch == ',')
    {	     
      upper = lower;
      goto SINGLE_NUMBER;
    }

    /* END NEW */

    ch++;   

    skipWhites(&ch);

    if(!isNum(*ch))
    {
      printf("%c Number expected in %s\n", *ch, p_names[i]);
      exit(-1);
    }    

    l = 0;
    while(isNum(*ch))
    {    
      buf[l] = *ch;
      ch++;	
      l++;
    }
    buf[l] = '\0';
    upper = atoi(buf);     
SINGLE_NUMBER:
    partitions[i][2 + 3 * (pairsCount - 1)] = upper;        	  

    if(upper < lower)
    {
      printf("Upper bound %d smaller than lower bound %d for this partition: %s\n", upper, lower,  p_names[i]);
      exit(-1);
    }

    skipWhites(&ch);

    if(*ch == '\0' || *ch == '\n' || *ch == '\r') /* PC-LINEBREAK*/
    {    
      goto parsed;
    }

    if(*ch == ',')
    {	 
      ch++;
      goto numberPairs;
    }

    if(*ch == '\\')
    {
      ch++;
      skipWhites(&ch);

      if(!isNum(*ch))
      {
        printf("%c Number expected in %s\n", *ch, p_names[i]);
        exit(-1);
      }     

      l = 0;
      while(isNum(*ch))
      {
        buf[l] = *ch;
        ch++;	
        l++;
      }
      buf[l] = '\0';
      modulo = atoi(buf);      
      partitions[i][3 + 3 * (pairsCount - 1)] = modulo; 	

      skipWhites(&ch);
      if(*ch == '\0' || *ch == '\n' || *ch == '\r')
      {	     
        goto parsed;
      }
      if(*ch == ',')
      {	       
        ch++;
        goto numberPairs;
      }
    }  

    if(*ch == '/')
      {
	printf("\nRAxML detected the character \"/\" in your partition file.\n");
	printf("Did you mean to write something similar to this: \"DNA, p1=1-100\\3\" ?\n");
	printf("It's actually a backslash, not a slash, the program will exit now with an error!\n\n");
      }  

    assert(0);

parsed:
    i = i;
  }

  fclose(f);

  /*********************************************************************************************************************/ 

  for(i = 0; i <= rdta->sites; i++)
    tr->model[i] = -1;

  for(i = 0; i < numberOfModels; i++)
  {   
    as = partitions[i][0];     

    for(j = 0; j < as; j++)
    {
      lower = partitions[i][1 + j * 3];
      upper = partitions[i][2 + j * 3]; 
      modulo = partitions[i][3 + j * 3];	

      if(modulo == -1)
      {
        for(k = lower; k <= upper; k++)
          setModel(i, k, tr->model);
      }
      else
      {
        for(k = lower; k <= upper; k += modulo)
        {
          if(k <= rdta->sites)
            setModel(i, k, tr->model);	      
        }
      }
    }        
  }


  for(i = 1; i < rdta->sites + 1; i++)
  {

    if(tr->model[i] == -1)
    {
      printf("ERROR: Alignment Position %d has not been assigned any model\n", i);
      exit(-1);
    }      
  }  

  for(i = 0; i < numberOfModels; i++)
  {
    free(partitions[i]);
    free(p_names[i]);
  }

  free(partitions);
  free(p_names);    

  tr->NumberOfModels = numberOfModels;     

  if(adef->perGeneBranchLengths)
  {
    if(tr->NumberOfModels != NUM_BRANCHES)
    {
      printf("You are trying to use %d partitioned models for an individual per-gene branch length estimate.\n", tr->NumberOfModels);
      printf("Currently only a number of %d models/partitions is hard-coded to improve efficiency.\n", NUM_BRANCHES);
      printf("\n");
      printf("In order to change this please replace the line \"#define NUM_BRANCHES   %d\" in file \"axml.h\" \n", NUM_BRANCHES);
      printf("by \"#define NUM_BRANCHES   %d\" and then re-compile RAxML.\n", tr->NumberOfModels);
      exit(-1);
    }
    else
    {
      tr->multiBranch = 1;
      tr->numBranches = tr->NumberOfModels;
    }
  }
}
Ejemplo n.º 22
0
// (eval 'any ['cnt ['lst]]) -> any
any doEval(any x) {
   any y;
   cell c1;
   bindFrame *p;

   x = cdr(x),  Push(c1, EVAL(car(x))),  x = cdr(x);
   if (!isNum(y = EVAL(car(x))) || !(p = Env.bind))
      data(c1) = EVAL(data(c1));
   else {
      int cnt, n, i, j;
      struct {  // bindFrame
         struct bindFrame *link;
         int i, cnt;
         struct {any sym; any val;} bnd[length(x)];
      } f;

      x = cdr(x),  x = EVAL(car(x));
      j = cnt = (int)unBox(y);
      n = f.i = f.cnt = 0;
      do {
         ++n;
         if ((i = p->i) <= 0  &&  (p->i -= cnt, i == 0)) {
            for (i = 0;  i < p->cnt;  ++i) {
               y = val(p->bnd[i].sym);
               val(p->bnd[i].sym) = p->bnd[i].val;
               p->bnd[i].val = y;
            }
            if (p->cnt  &&  p->bnd[0].sym == At  &&  !--j)
               break;
         }
      } while (p = p->link);
      while (isCell(x)) {
         for (p = Env.bind, j = n; ; p = p->link) {
            if (p->i < 0)
               for (i = 0;  i < p->cnt;  ++i) {
                  if (p->bnd[i].sym == car(x)) {
                     f.bnd[f.cnt].val = val(f.bnd[f.cnt].sym = car(x));
                     val(car(x)) = p->bnd[i].val;
                     ++f.cnt;
                     goto next;
                  }
               }
            if (!--j)
               break;
         }
next:    x = cdr(x);
      }
      f.link = Env.bind,  Env.bind = (bindFrame*)&f;
      data(c1) = EVAL(data(c1));
      while (--f.cnt >= 0)
         val(f.bnd[f.cnt].sym) = f.bnd[f.cnt].val;
      Env.bind = f.link;
      do {
         for (p = Env.bind, i = n;  --i;  p = p->link);
         if (p->i < 0  &&  (p->i += cnt) == 0)
            for (i = p->cnt;  --i >= 0;) {
               y = val(p->bnd[i].sym);
               val(p->bnd[i].sym) = p->bnd[i].val;
               p->bnd[i].val = y;
            }
      } while (--n);
   }
   return Pop(c1);
}
Ejemplo n.º 23
0
int error4(const struct command_t* command){
	if(!(isNum(command->token[0]) && isOperation(command->token[1]) && isNum(command->token[2]) && strcmp(command->token[3], "") == 0) &&
		!(isNum(command->token[1]) && isOperation(command->token[0]) && strcmp(command->token[2], "") == 0))
		return 1;
	return 0;
}
Ejemplo n.º 24
0
inline bool isAlphaNum(char c)
{
	return isAlpha(c) || isNum(c);
}
Ejemplo n.º 25
0
static bool isLetterOrNum(int c) {
  return isLetter(c) || isNum(c);
}
Ejemplo n.º 26
0
int myAtoi(char* str) 
{
	int* tempArr=NULL;
	int length=0;
	int positive=1;
	int first=-1, last=-1;
	int count=0;
	int result=0;

	//trim the string 
	tempArr=charArrToIntArr(str);
	length=strlen(str);

	//get the position of first sequence 
	for (int i=0; i<length; i++)
	{
		
		if((tempArr[i]==43 || tempArr[i]==45) && i < length-1 &&first==-1)
		{ //if there is a "-"i, then check next one, 
			//if next one is numeric then go to next circle
			//if not, mean this case is not a numeric case, jsut return 0
			
			if(isNum(tempArr[i+1]))
			{
				positive=44-tempArr[i];
				continue;
			}
			else
			{
				return 0;
			}			
		}//end of
	  else if(first==-1 &&tempArr[i]==0)
		{
			//find the next non zero numeric
			for(int ss=i;ss<length;ss++)
			{
				if(!isNum(tempArr[ss]))
				{
					//if next one is not numeric just return 0
					return 0;
				}
				else if(tempArr[ss]!=0)
				{
					//found the next non zero numeric
					i=ss-1;
					break;
				}
			}	
		
		}	
		else if(isNum(tempArr[i]) && tempArr[i]!=0 && first==-1)
		{
			//if this is the first found numeric,
			//then record the positon as start and end
			first=i;
			last=i;
		}
		else if(isNum(tempArr[i]) && first !=-1)
		{
			//if this is not the first numeric,
			//just change the index of last 
			last=i;
		}
		else if(!isNum(tempArr[i]) && first != -1)
		{	
			//if last one is numeric and this one isn't
			//meant it's the end of this sequence,
			//just break this loop
			break;
		}
		else if(!isNum(tempArr[i]) && tempArr[i]!=32 && first==-1)
		{
			//the first non-numeric is not space
			return 0;
		}

	}//end of for


	//check the overflow
	if(last-first > 9 || (last-first >= 9 && tempArr[first]>2))
	{
		if(positive == 1)
			return INT_MAX;
		else
			return INT_MIN;
	
	}
		
	//start convert
	for(int i=last; i>=first ; i--)
	{
	
		//prevent overflow more detaily here
		if(tempArr[i] >= 2 && result > 147483647)
		{
			if(positive==1)
				return INT_MAX;
			else
				return INT_MIN;	
		}
		result+=tempArr[i]*pow(10, count++);


	}//end of for

	result*=positive;

	free(tempArr);

	return result;

}
Ejemplo n.º 27
0
int main(int argc, char** argv)
{
//-------------------------------Analyse params---------------------------
	int ch;

	if(argc <= 1)
	{
		retval = NO_PARAM;
		goto EXIT;
	}
	else if(argv[1][0] != '-' && isNum(argv[1]))
	{
		programNum = atoi(argv[1]);
	}
	else if(argv[1][0] != '-' && !isNum(argv[1]))
	{
		retval = NO_PARAM;
		goto EXIT;
	}

	while((ch = getopt(argc, argv, "s:a:h")) != -1)
	{
		switch(ch)
		{
			case 's':
				if(isNum(optarg))
					freq = atoi(optarg);
				else
				{
					retval = PARAM_ERR;
					goto EXIT;
				}

				break;
			case 'a':
				break;
			case 'h':
				helpInfo();
				break;
			default:
				helpInfo();
		}
	}	


//----------------------------Init memory----------------------------
    progInfoBuffer = (char *)malloc(PROG_INFO_BUFFER_SIZE);
	if(progInfoBuffer == NULL)
	{
		printf("Erro occurred! Maybe lack of memory.");
		return MALLOC_ERR;
	}

//---------------------------Get dat from profile file----------------

	int tmpDatLen = 0;

	sprintf(progInfoBuffer, "[freq] %d\n", freq);	
	tmpDatLen = strlen(progInfoBuffer);

	if(freq > 0)
	{
		if((datFp = fopen("tmp.dat", "w+")) == NULL)
		{
			retval = DAT_OPEN_ERR;
			goto EXIT;
		}

		fwrite(progInfoBuffer, tmpDatLen,1, datFp);
	}
	else
	{
		if((datFp = fopen("tmp.dat", "r")) == NULL)
		{
			retval = DAT_OPEN_ERR;
			goto EXIT;
		}

		char* freqFromFile;
		int tmpFreq = 0;
		freqFromFile = (char*)malloc(tmpDatLen + 1);
		fread(freqFromFile, tmpDatLen, 1, datFp);

		if(sscanf(freqFromFile, "[freq] %d\n", &tmpFreq) > 0)
			freq = tmpFreq;

		free(freqFromFile);
	}

	if(datFp != NULL)
		fclose(datFp);

	if(freq == -1)
	{
		retval = FREQ_ERR;
		goto EXIT;
	}

	if(programNum != -1)
	{
		programWantToPlay = programNum;
		printf("Program Num: %d\n", programWantToPlay);
	}

	printf("Freq is %d\n", freq);

//---------------------Start to parse ts---------------------
	if(!parseTS(freq))
	{
		retval = FREQ_ERR;
		goto EXIT;
	}

EXIT:

	if(progInfoBuffer != NULL)
		free(progInfoBuffer);

	if(retval != 0)
		errInfo(retval);

	return retval;	
}
Ejemplo n.º 28
0
int main(int argc, char *argv[])
{
    /* Packet Thread */
    /* Initialize the mutex */
    pthread_mutex_init(&m, 0);

    int i;
    char *lambda = "0.5";
    char *mu = "0.35";
    char *r = "1.5";
    char *B = "10";
    char *P = "3";
    char *n = "20";
    char *FILENAME = NULL;
    AVAILABLE = 0;
    DROPPED = 0;
    DROPPED_PKT = 0;
    TOTAL = 0;
    TOTAL_SERVED = 0;
    SERVER_DIE = 0;

    /* Read Options */
    for(i=1;i<argc;i=i+2){
        if (i%2!=0 && argv[i][0]=='-'){
            if ((strcmp(argv[i]+1, "lambda") == 0) && ((i+1)<argc)){
                lambda = argv[i+1];
                if(check_num(lambda)== -1){
                    fprintf(stderr, "Value of lambda is not a number.\n");
                    exit(0);
                }
                continue;
            }
            else if ((strcmp(argv[i]+1, "mu") == 0) && ((i+1)<argc)){
                mu = argv[i+1];
                if(check_num(mu)== -1){
                    fprintf(stderr, "Value of mu is not a number.\n");
                    exit(0);
                }
                continue;
            }
            else if ((strcmp(argv[i]+1, "r") == 0) && ((i+1)<argc)){
                r = argv[i+1];
                if(check_num(r)== -1){
                    fprintf(stderr, "Value of r is not a number.\n");
                    exit(0);
                }
                continue;
            }
            else if ((strcmp(argv[i]+1, "B") == 0) && ((i+1)<argc)){
                B = argv[i+1];
                if(isNum(B)==-1){
                    fprintf(stderr, "Value of B is not a number.\n");
                    exit(0);
                }
                continue;
            }
            else if((strcmp(argv[i]+1, "P") == 0) && ((i+1)<argc)){
                P = argv[i+1];
                if(isNum(P) == -1){
                    fprintf(stderr, "Value of P is not a number.\n");
                    exit(0);
                }
                continue;
            }
            else if ((strcmp(argv[i]+1, "n") == 0) && ((i+1)<argc)){
                n = argv[i+1];
                if(isNum(n)==-1){
                    fprintf(stderr, "Value of n is not a number.\n");
                    exit(0);
                }
                continue;
            }
            else if ((strcmp(argv[i]+1, "t") == 0) && ((i+1)<argc)){
                FILENAME = argv[i+1];
                continue;
            }
        }
        fprintf(stderr, "Wrong command line argument\n");
        exit(0);
        break;
     }

    /*Allocate memory to list*/
    Q1 = malloc(sizeof(My402List));
    Q2 = malloc(sizeof(My402List));
    /*Initilialize the list*/
    My402ListInit(Q1);
    My402ListInit(Q2);

    /* Block Signal from Main thread */
    block_signal();

    if(FILENAME!=NULL){
        FILE *fp = fopen(FILENAME, "r");
        if(fp==NULL){
            perror("Error: Unable to open the file ");
            exit(0);
        }
        fclose(fp);
    }

   
    print_input(lambda, mu, FILENAME, r, B, P, n);
    /* Create packet thread */

    fprintf(stdout, "\n");
    /* Initialize the stats */ 
    init_stats();

    struct timeval current = diff_timeval(START_TIMEVAL, PKT_BEFORE);
    fprintf(stdout, "%08llu.%03ldms: emulation begins\n",
            toMilliSeconds(current), current.tv_usec%MILLI);

    /* Create threads */
    create_packet_thread(lambda, mu, FILENAME, r, B, P, n);

    /* Print statistics */
    //print_stats();

    return(0);
}
Ejemplo n.º 29
0
int main(void){
  FILE *f, *g, *h, *out;
  char c;
  char keys[NUM][4];
  char word[4];
  int keyarr[NUM];
  int len = 0, n, spam, a, b, dot, i;
  int msglen, wordnum, numnum, weirdnum, spel;
  double r;
  f = fopen("data.txt", "r");
  g = fopen("data2.txt", "r");
  h = fopen("keywords.txt", "r");
  out = fopen("out.txt", "w");

  // ucitaj rjecnik keyworda
  while (fscanf(h, "%c%c%c%c %d %d %lg ", keys[len], keys[len]+1, keys[len]+2, 
        keys[len]+3, &a, &b, &r) == 7) len++;
  
  // napisi header u out.txt
  fprintf(out,
      "spam broj_rijeci duljina nepismenost udio_brojeva udio_nealfanumerickih ");
  for (i = 0; i < len; i++){
    fprintf(out, "%c%c%c%c ", keys[i][0], keys[i][1], keys[i][2], keys[i][3]);
  }
  fprintf(out, "\n");

  for (n = 0; n < LINES; n++){
    // prvo iz neobradenog fajla izvadi broj charactera itd..
    fscanf(f, "%c", &c);
    if (c == 'h') {
      // zapamti jeli poruka ham ...
      spam = 0;
    }
    else if (c == 's'){
      // ... ili spam
      spam = 1;
    }
    else printf("nesto nevalja: linija %d\n", n);
    // ako na pocetku linije ne pise ni spam ni ham, nesto je krivo
    
    while (isAlpha(c)) fscanf(f, "%c", &c);
    // ucitaj cijelu rijec (spam/ham) do kraja
    dot = 0;
    msglen = 0;
    numnum = 0;
    weirdnum = 0;
    spel = 0;
    wordnum = 0;

    while (1){
      fscanf(f, "%c", &c);
      if (c == '\n') break;
      msglen++; // broj znakova
      if (isNum(c)) numnum++; // broji udio brojeva
      if (isWeird(c)) weirdnum++; // broji udio nealfanumerickih
      if ((isNum(c) || isAlpha(c)) && (dot == 1)) spel = 1; // nepismenost
      if (isDot(c)) dot = 1;
      else dot = 0;
    }

    // zatim iz obradenog izvadi kljucne rijeci
    fscanf(g, "%d", &a); // ucitaj jeli spam ili ham
    if (a != spam) printf("nisu konzistentni na liniji: %d\n", n);
    fscanf(g, "%c", &c); // ucitaj razmak
    for (i = 0; i < len; i++){
      keyarr[i] = 0; // ocisti niz koji cuva postojanje keyworda
    }

    while (c != '\n'){
      for (i = 0; i < 4; i++){
        fscanf(g, "%c", word+i);
      }
      wordnum++; // broj rijeci u poruci
      b = exsist(word, keys, len); // kljucna rijec
      if (b >= 0) keyarr[b] = 1;
      fscanf(g, "%c", &c); // ucitaj razmak
    }

    // zapisi feature vektor u out.txt
    fprintf(out, "%d %d %d %d %lg %lg ", spam, wordnum, msglen, spel, 
        (double)numnum/msglen, (double)weirdnum/msglen);
    for (i = 0; i < len; i++){
      fprintf(out, "%d ", keyarr[i]);
    }
    fprintf(out, "\n");
  }

  return 0;
}
Ejemplo n.º 30
0
/*
	Main function from this namespace.

	It takes InputType object reference from which it reads info list, and by that, it reads
	istream sent as first parameter, alocates memory dynamically an casts new pointer to void,
	which then store inside UserObject that it also created dynamically on beggining.

	If Stream reading fail in some point, it calls self method fail, which destroys, UserObject
	created, and throws an exception.

	@param _in -> (std::istream&) reference to stream from which it should read
	@param _it -> (const StreamReader::InputType&) reference to InputType object which describes
					how should stream be read.

	@TODO: fix memory leak with strings...
*/
StreamReader::UserObject* StreamReader::readStream(std::istream& _in, const StreamReader::InputType& _it)
{
	UserObject* ret = new UserObject();
	for (int type : _it.info)
	{
		void* p;
		switch (type)
		{
		case InputType::CHAR:
			p = new char;
			_in.get(* (char*) p);
			if (!isChar(* (char*) p) || _in.fail())
				fail(ret, p);
			ret -> addValue(p);
			break;
		case InputType::INT:
			p = new int;
			_in >> * (int*) p;
			if (_in.fail())
				fail(ret, p);
			ret -> addValue(p);
			break;
		case InputType::DIGIT:
			p = new char;
			_in.get(* (char*) p);
			if (!isNum(* (char*) p) || _in.fail())
				fail(ret, p);
			ret -> addValue(p);
			break;
		case InputType::FLOAT:
			p = new float;
			_in >> * (float*) p;
			if (_in.fail())
				fail(ret, p);
			ret -> addValue(p);
			break;
		case InputType::DOUBLE:
			p = new double;
			_in >> * (double*) p;
			if (_in.fail())
				fail(ret, p);
			ret -> addValue(p);
			break;
		case InputType::STRING:
		{
			char* buffer = new char[_it.MAX_CHAR];
			for (int i = 0; i < _it.MAX_CHAR - 1; i++)
			{
				_in.get(buffer[i]);
				if (_in.fail())
				{
					fail(ret);
					delete[] buffer;
				}
				if (buffer[i] == _it.DELIMITER)
				{
					buffer[i] = '\0';
					break;
				}
			}
			p = new std::string(buffer);
			delete[] buffer;
			ret -> addValue(p);
			break;
		}
		default:
			throw std::exception("Bad file input");
			break;
		}
	}
	return ret;
}