示例#1
0
int checkNewPoint(int *match, int *xs, int *ys, int len) {
	for (int i = -20; i < 20; i++) {
		for (int j = -20; j < 20; j++) {
			if (inArray((match[0]+i),xs,len) && inArray((match[1]+j),ys,len)) {
				return 0;
			}
		}
	}
	return 1;
}
示例#2
0
/* 2.1 Write code to remove duplicates from an unsorted linked list*/
Node *RemoveDup(Node *list){
   Node *c = list;
   Node *head, *temp;
   head = NULL;
   int buffer[50];
   int index = 0, size = 50;

   for (int i = 0; i < size; ++i){ 
         //initialize array 
         buffer[i] = -1;
   }
   while(c->next != NULL){
      if (inArray(buffer, c->val, size) < 1){
         temp = (Node *)malloc(sizeof(Node));
         temp->val = c->val;
         temp->next = head;
         head = temp;
      }
      buffer[index] = c->val;    
      c = c->next; 
      index++;
   }
   return head;

}
示例#3
0
/* Refers to RFC 1945 5. Request (page 22)
*  Method + URI + HTTP-Version
*/
static int checkHttpRequest(char * requestLine, char ** url, char ** method, status * st)
{
	char * pch;
	pch = strtok (requestLine,sp);
	char *res[3];
    bzero(res,sizeof(res));
	int i=0;
	// We split the request using a space as delimiter
	while ((pch != NULL)&&(i<3))
	{
		res[i]= pch;
        // printf("%s%s\n","RES", res[i] );
		pch = strtok (NULL, sp);
		i++;
	}
	
	if(i<3) // If the request has less than the mandatory arguments
	{
		st->code = 400;
        st->reason =  "Bad Request";
		return 0;
	}
	// We check that the method and the version are correct
	if((inArray(res[0])) && (versionHTTP(res[2])))
	{
		// We save the method and the url in a variable
		*method = res[0];
		*url = res[1];
		return 1;
	}
	st->code = 400;
    st->reason =  "Bad Request";
	return 0;
}
示例#4
0
void addElement(char *el, char ***array, unsigned *count)
/* Add a new element to a array of elements */
{
  char *arrayCurr, arrayNew[MAX_ID_LIST];
  int sizeOne, size;
  char **cArray, **rArray=NULL, ***dArray;

  /* Check if already present in array */
  if (!inArray(el, *array, *count))
    {
      size = *count;
      arrayCurr = sqlStringArrayToString(*array, *count);
      safef(arrayNew, ArraySize(arrayNew), "%s%s,", arrayCurr, el);
      size++;
      dArray = array;
      /* if (*dArray) 
	 freeMem(dArray); */
      sqlStringDynamicArray(arrayNew, &cArray, &sizeOne);
      assert(sizeOne == size);
      *count = size;
      AllocArray(rArray, size);
      CopyArray(cArray, rArray, size);
      *array = rArray;
    }
}
/**
 * renvoie l'élément qui a pour clé key
 **/
function getItem(key, dict) {
	for (var item in dict) {
		if (inArray(item, key)) {
			return item[1];
		}
	}
	return null;
}
/**
 * supprime l'élément qui a la clé key
 **/
function deleteItem(key, dict) {
	for (var i = 0; i < count(dict); i++) {
		if (inArray(dict[i], key)) {
			remove(dict, i);
			return 1;
		}
	}
	return -1;
}
	void ScriptFontImportOptions::internal_SetFontSizes(ScriptFontImportOptions* thisPtr, MonoArray* value)
	{
		ScriptArray inArray(value);

		Vector<UINT32> fontSizes(inArray.size());
		for (UINT32 i = 0; i < inArray.size(); i++)
			fontSizes[i] = inArray.get<UINT32>(i);

		thisPtr->getFontImportOptions()->setFontSizes(fontSizes);
	}
示例#8
0
    Status HashIndexCursor::seek(const BSONObj& position) {
        //Use FieldRangeSet to parse the query into a vector of intervals
        //These should be point-intervals if this cursor is ever used
        //So the FieldInterval vector will be, e.g. <[1,1], [3,3], [6,6]>
        FieldRangeSet frs( "" , position, true, true );
        const vector<FieldInterval>& intervals = frs.range( _hashedField.c_str() ).intervals();

        //Construct a new query based on the hashes of the previous point-intervals
        //e.g. {a : {$in : [ hash(1) , hash(3) , hash(6) ]}}
        BSONObjBuilder newQueryBuilder;
        BSONObjBuilder inObj( newQueryBuilder.subobjStart( _hashedField ) );
        BSONArrayBuilder inArray( inObj.subarrayStart("$in") );
        vector<FieldInterval>::const_iterator i;
        for( i = intervals.begin(); i != intervals.end(); ++i ){
            if ( ! i->equality() ){
                _oldCursor.reset(
                        BtreeCursor::make( nsdetails( _descriptor->parentNS()),
                            _descriptor->getOnDisk(),
                            BSON( "" << MINKEY ) ,
                            BSON( "" << MAXKEY ) ,
                            true ,
                            1 ) );
                return Status::OK();
            }
            inArray.append(HashAccessMethod::makeSingleKey(i->_lower._bound, _seed, _hashVersion));
        }
        inArray.done();
        inObj.done();
        BSONObj newQuery = newQueryBuilder.obj();

        // FieldRangeVector needs an IndexSpec so we make it one.
        BSONObjBuilder specBuilder;
        BSONObjIterator it(_descriptor->keyPattern());
        while (it.more()) {
            BSONElement e = it.next();
            specBuilder.append(e.fieldName(), 1);
        }
        BSONObj spec = specBuilder.obj();
        IndexSpec specForFRV(spec);

        //Use the point-intervals of the new query to create a Btree cursor
        FieldRangeSet newfrs( "" , newQuery , true, true );
        shared_ptr<FieldRangeVector> newVector(
                new FieldRangeVector( newfrs , specForFRV, 1 ) );

        _oldCursor.reset(
                BtreeCursor::make(nsdetails(_descriptor->parentNS()),
                    _descriptor->getOnDisk(),
                    newVector,
                    0,
                    1));

        return Status::OK();
    }
	void ScriptFontImportOptions::internal_SetCharRanges(ScriptFontImportOptions* thisPtr, MonoArray* value)
	{
		ScriptArray inArray(value);

		thisPtr->getFontImportOptions()->clearCharIndexRanges();
		for (UINT32 i = 0; i < inArray.size(); i++)
		{
			CharRange range = inArray.get<CharRange>(i);
			thisPtr->getFontImportOptions()->addCharIndexRange(range.start, range.end);
		}
	}
示例#10
0
	void ScriptAnimationCurve::internal_Create(MonoObject* instance, MonoArray* keyFrames)
	{
		ScriptArray inArray(keyFrames);
		
		UINT32 numKeyframes = inArray.size();
		Vector<TKeyframe<float>> nativeKeyframes(numKeyframes);

		memcpy(nativeKeyframes.data(), (UINT8*)inArray.getRawPtr<TKeyframe<float>>(), 
			numKeyframes * sizeof(TKeyframe<float>));

		SPtr<TAnimationCurve<float>> curve = bs_shared_ptr_new<TAnimationCurve<float>>(nativeKeyframes);
		new (bs_alloc<ScriptAnimationCurve>()) ScriptAnimationCurve(instance, curve);
	}
示例#11
0
///////////////////////////////////////////////////////////////////////////
// result[n] will be initialized with a set of random numbers, no duplicates
//           Values between 0 and max.
// 
void UniqRandInt(int max, int n, int result[]) {
    int cntr = 0, r;
    
    while(cntr < n) {
        r = rand();  //Get random number
        r = r % (max + 1);
        if (!inArray(result, cntr, r)) {
            result[cntr] =  r;
            cntr++;
        }
    }
    return;
}
示例#12
0
文件: hashindex.cpp 项目: Bamco/mongo
    shared_ptr<Cursor> HashedIndexType::newCursor( const BSONObj& query ,
            const BSONObj& order , int numWanted ) const {

        //Use FieldRangeSet to parse the query into a vector of intervals
        //These should be point-intervals if this cursor is ever used
        //So the FieldInterval vector will be, e.g. <[1,1], [3,3], [6,6]>
        FieldRangeSet frs( "" , query , true, true );
        const vector<FieldInterval>& intervals = frs.range( _hashedField.c_str() ).intervals();

        //Force a match of the query against the actual document by giving
        //the cursor a matcher with an empty indexKeyPattern.  This insures the
        //index is not used as a covered index.
        //NOTE: this forcing is necessary due to potential hash collisions
        const shared_ptr< CoveredIndexMatcher > forceDocMatcher(
                new CoveredIndexMatcher( query , BSONObj() ) );

        //Construct a new query based on the hashes of the previous point-intervals
        //e.g. {a : {$in : [ hash(1) , hash(3) , hash(6) ]}}
        BSONObjBuilder newQueryBuilder;
        BSONObjBuilder inObj( newQueryBuilder.subobjStart( _hashedField ) );
        BSONArrayBuilder inArray( inObj.subarrayStart("$in") );
        vector<FieldInterval>::const_iterator i;
        for( i = intervals.begin(); i != intervals.end(); ++i ){
            if ( ! i->equality() ){
                const shared_ptr< BtreeCursor > exhaustiveCursor(
                        BtreeCursor::make( nsdetails( _spec->getDetails()->parentNS().c_str()),
                                           *( _spec->getDetails() ),
                                           BSON( "" << MINKEY ) ,
                                           BSON( "" << MAXKEY ) ,
                                           true ,
                                           1 ) );
                exhaustiveCursor->setMatcher( forceDocMatcher );
                return exhaustiveCursor;
            }
            inArray.append( makeSingleKey( i->_lower._bound , _seed , _hashVersion ) );
        }
        inArray.done();
        inObj.done();
        BSONObj newQuery = newQueryBuilder.obj();

        //Use the point-intervals of the new query to create a Btree cursor
        FieldRangeSet newfrs( "" , newQuery , true, true );
        shared_ptr<FieldRangeVector> newVector(
                new FieldRangeVector( newfrs , *_spec , 1 ) );

        const shared_ptr< BtreeCursor > cursor(
                BtreeCursor::make( nsdetails( _spec->getDetails()->parentNS().c_str()),
                        *( _spec->getDetails() ),  newVector , 1 ) );
        cursor->setMatcher( forceDocMatcher );
        return cursor;
    }
示例#13
0
文件: lash.c 项目: alexmaras/lash
/**
 * Evaluates each command stored in the parser struct and exeutes either the runShellCommand
 * function or the runCommand function.
 * @param  parser A constructed LashParser struct with fully populated commands
 * @return        0 if a command was "exit", 1 otherwise
 */
int executeCommand(struct LashParser *parser){
	int i;
	int nextinput = -1;
	for(i = 0; i < parser->commandNum; i++){
		struct Command *command = parser->commands[i];
		int shellCommand = inArray(command->args[0], inbuiltCommands, NUMINBUILTCOMMANDS);
		if(shellCommand){
			return runShellCommand(parser, command);
		}
		else if(strcmp(command->args[0], "") != 0){
			nextinput = runCommand(command, nextinput);
		}
	}
	return 1;
}
示例#14
0
void listOthers(char uname[USERNAME_SIZE], char **followees, int clientSock, int size){
	//Sends all usernames that uname is not following (excluding his own uname) to the clientSock
	
	FILE * fp;
	if ((fp = fopen(CREDENTIALS_FILE, "r")) == NULL)
	{
		perror("Couldn't open file");
		exit(FOPEN_FAILED);
	}
	char oneLine[CREDENTIALS_ENTRY_SIZE];
	bzero(oneLine, CREDENTIALS_ENTRY_SIZE);
	while(fgets(oneLine, CREDENTIALS_ENTRY_SIZE, fp))
	{
		char* credentialsEntryTok[NUM_FIELDS_CREDENTIALS+1];
		tokenize(credentialsEntryTok, oneLine, SEPARATOR);
		//puts(credentialsEntryTok[0]);
		//if credentialsEntryTok[0] exists, and is not in uname's followees and is not uname
		if(credentialsEntryTok[0] && !inArray(credentialsEntryTok[0], followees, size) && !(strncmp(uname, credentialsEntryTok[0], strlen(uname)) == 0 && (strlen(uname) == strlen(credentialsEntryTok[0]))))
		 {
			char temp[USERNAME_SIZE+1];
			bzero(temp, USERNAME_SIZE+1);
			if(snprintf(temp, USERNAME_SIZE+1, "%s\n", credentialsEntryTok[0]) < 0)
			{
				perror("Snprintf failed.");
				exit(SNPRINTF_FAILED);
			}
			if(send(clientSock, temp, strlen(temp), 0) == -1)
			{
				perror("Send Failed.");
				exit(SEND_FAILED);
			}
		}
		
		for(int i = 0; credentialsEntryTok[i]; i++)
		{
			free(credentialsEntryTok[i]);
		}
		bzero(oneLine, CREDENTIALS_ENTRY_SIZE);
	}
	if(fclose(fp) == EOF)
	{
		perror("Close failed.");
		exit(FCLOSE_FAILED);
	}
}
示例#15
0
	void ScriptAnimationCurve::internal_SetKeyFrames(ScriptAnimationCurve* thisPtr, MonoArray* keyFrames)
	{
		ScriptArray inArray(keyFrames);

		UINT32 numKeyframes = inArray.size();
		Vector<TKeyframe<float>> nativeKeyframes(numKeyframes);

		memcpy(nativeKeyframes.data(), (UINT8*)inArray.getRawPtr<TKeyframe<float>>(),
			numKeyframes * sizeof(TKeyframe<float>));

		std::sort(nativeKeyframes.begin(), nativeKeyframes.end(), 
			[](const TKeyframe<float>& x, const TKeyframe<float>& y)
		{
			return x.time < y.time;
		});

		thisPtr->mCurve = bs_shared_ptr_new<TAnimationCurve<float>>(nativeKeyframes);
	}
示例#16
0
void listTweets(char uname[USERNAME_SIZE], char **followees, int clientSock, int size){
	//sends all of uname's tweets as well as all tweets of followees to the clientSock
	FILE * fp;
	if ((fp = fopen(TWEETS_FILE, "r")) == NULL)
	{
		perror("Couldn't open file");
		exit(FOPEN_FAILED);
	}
	char oneLine[TWEET_ENTRY_SIZE];
	bzero(oneLine, TWEET_ENTRY_SIZE);
	while(fgets(oneLine, TWEET_ENTRY_SIZE, fp))
	{
		char* tweetsEntryTok[NUM_FIELDS_TWEETS+1];
		tokenize(tweetsEntryTok, oneLine, SEPARATOR);
		//if author of a tweet is in uname's followees array OR author is uname
		if(tweetsEntryTok[0] && (inArray(tweetsEntryTok[0], followees, size) ||
		 (strncmp(uname, tweetsEntryTok[0], strlen(uname)) == 0 && strlen(uname) == strlen(tweetsEntryTok[0]))))
		{
			char temp[TWEET_ENTRY_SIZE];
			bzero(temp, TWEET_ENTRY_SIZE);
			if(snprintf(temp, TWEET_SIZE+3, "%s\t%s\t%s\n", tweetsEntryTok[0], tweetsEntryTok[1], tweetsEntryTok[2]) < 0)
			{
				perror("Snprintf failed.");
				exit(SNPRINTF_FAILED);
			}
			if(send(clientSock, temp, strlen(temp), 0) == -1)
			{
				perror("Send Failed.");
				exit(SEND_FAILED);
			}
		}
		
		for(int i = 0; tweetsEntryTok[i]; i++)
		{
			free(tweetsEntryTok[i]);
		}
		bzero(oneLine, TWEET_ENTRY_SIZE);
	}
	if(fclose(fp) == EOF)
	{
		perror("Close failed.");
		exit(FCLOSE_FAILED);
	}
}
示例#17
0
文件: ex012.cpp 项目: CharlzKlug/st
int main(){
  std::ifstream infile ( "input.txt" );
  if ( !infile.bad ( ) ) {
    int residentsCount; // Число дачников
    int coordinates[10];
    infile >> residentsCount;
    int accuracyResidents = 0 ; // Число точно приземлившихся
    for ( int i = 1; i <= residentsCount; i++ ) {
      for ( int j = 0 ; j < 10 ; ++j ) {
	infile >> coordinates [ j ] ;
      }
      if ( inArray ( coordinates ) )
	++accuracyResidents ;
    }
    infile.close();
    std::ofstream outfile("output.txt");
    if (!outfile.bad()) {
      outfile << accuracyResidents ;
      outfile.close();
    }
    std::cout << "Accuracy: " <<
      accuracyResidents << std::endl ;
  }
示例#18
0
文件: logger.c 项目: ALFDP/diff
/**

    Builds the logger configuration by parsing the default configuration file.

    @return The parsed logger configuration.

**/
LoggerConfig buildLoggerConfig(FILE *configFile)
{
    char buff[CONFIG_BUFF_SIZE] = "";
    char *buffPointer = NULL;
    const char *instr[CONFIG_INSTR_ARRAY_SIZE] = {"logLevel", "logFile"};
    LoggerConfig config;

    while(!feof(configFile))
    {
        fgets(buff, CONFIG_BUFF_SIZE, configFile);
        if((buffPointer = strchr(buff, '=')) != NULL)
        {
            *buffPointer = '\0';
            buffPointer++;
            LoggerConfigRoutingProc(&config, buffPointer, inArray(buffPointer, instr, CONFIG_INSTR_ARRAY_SIZE));
        }
        else
        {
            fprintf(stderr, "Warning : \"%s\" line could not be parsed !", buff);
        }
    }

    return config;
}
示例#19
0
文件: eval.c 项目: xquiet/sdlbasic
void eval( Node *node )
{
    int             i, j;
    Number          n1, n2, n3, n4;
    char            *string1;
    Symbol          *s;
    Node            *n;
    Array           *a;

/* debugging */
#ifdef __DEBUG_TRACE__
    SourceCode *sc;
#endif


/* init vars */
    n1=0;
    n2=0;
    n3=0;
    n4=0;


    if (node == NULL) {
        return;
    }

    /* test node */
    eMemTest( "eval: node is corrupt", node );
    eMemTest( "eval: node->left is corrupt", node->left );
    eMemTest( "eval: node->right is corrupt", node->right );

    /* tracing */
    if (node->trace != -1) {
        runLineId = node->trace;
#ifdef __DEBUG_TRACE__
        sc = eFindSource( runLineId );
        eConsole("%d: %s\n", sc->lineNum, sc->text );
#endif
	/* sdlBasic_debugging */
	if (debug==1){
	    screendebug(); ////////////////////////////////////
	}
    }

/* debugging */
#ifdef __DEBUG_TRACE__
    eConsole( "Op:%s\n", opcodeName[node->op] );
#endif

    switch( node->op ) {

    //case NULL:
    //    break;

    case OpAdd:
        eval( node->left );
        eval( node->right );

        /* add or concat? */
        if (getStackType( tos ) == DATA_STRING) {
            basConcat();
        } else {
            n2 = popNumber();
            n1 = popNumber();
            pushNumber( n1 + n2 );
        }
        break;

    case OpAnd:
        /* short circuit */
        eval( node->left );
        if (!popNumber()) {
            pushNumber( (Number)0 );
        } else {
            eval( node->right );
            if (popNumber()) {
                pushNumber( (Number)1 );
            } else {
                pushNumber( (Number)0 );
            }
        }
        break;

    case OpArgList:
        eval( node->left );
        eval( node->right );
        break;

    case OpArrayGet:
        eval( node->left );     /* indices and index */
        getArrayElement( node->value.symbol );
        break;

    case OpArrayPtr:
        pushArray( node->value.symbol );
        break;

    case OpArraySet:
        eval( node->right );    /* value to store */
        eval( node->left );     /* indices and index */
        setArrayElement( node->value.symbol );
        break;

    case OpAssign:

        /* value to be assigned. note the *right* node is used */
        eval( node->right );

        /* variable to assign to */
        setVar( node->value.symbol );
        break;

    case OpBuiltin:
    case OpBuiltinCall:

        /* for argcount */
        n1 = tos;

        /* mark start of created objects */
        pushCreateStack( 0 );

        /* the args */
        eval( node->left );

        /* builtin symbol */
        s = node->value.symbol;

        if (s == NULL) {
            ePrintf( Runtime, "builtin pointer is null");
        }

        /* set args */
        argCount = (int)(tos - n1);

        /* call the c function */
        (*s->builtin)();

        /* destroy created objects */
        clearCreateStack();

        /* drop result? */
        if (node->op == OpBuiltinCall) {
            dropTos();
        }

        break;

    case OpCaseSelect:
        /* top level of a case statement */

        /* value to compare */
        eval( node->left );

        /* resolve into real data */
        switch (getStackType( tos )) {

        case DATA_NUMBER:
            pushNumber( popNumber() );
            break;

        case DATA_STRING:
            pushString( popString() );
            break;

        default:
            ePrintf( Runtime, "OpCaseSelect: can't resolve type %s",
                datumName[getStackType( tos )] );
        }

        /* get first test */
        if (node == NULL) {
            /* no tests */
            break;
        } else {
            node = node->right;
        }

        /* walk the chain of cases */
        while (1) {
            /* get a test/action pair */
            n = node->left;

            /* perform the tests */
            eval( n->left );

            /* true? */
            if (popNumber()) {
                /* perform action and leave loop */
                eval( n->right );
                break;
            }

            /* move to next test */
            node = node->right;
            if (node == NULL) {
                break;
            }
        }

        /* drop the test value from the stack */
        dropTos();
        break;

    case OpCaseCmp:
    case OpCaseRange:
    case OpCaseElse:
        /* perform chain of tests until true or end */
        while (1) {
            switch (node->op) {
            case OpCaseCmp:
                /* value to compare */
                eval(node->left);

                /* what type of test? */
                switch (getStackType( tos-1 )) {
                case DATA_NUMBER:
                    numberCompare( node->value.iValue, 0 );
                    break;

                case DATA_STRING:
                    stringCompare( node->value.iValue, 0 );
                    break;

                default:
                    ePrintf( Runtime, "OpCaseCmp: bad data type" );
                }
                break;

            case OpCaseRange:
                /* values to compare */
                n = node->left;
                eval( n->left );
                eval( n->right );

                /* what type of comparison? */
                switch (getStackType( tos-2 )) {
                case DATA_NUMBER:
                    numberRangeCompare();
                    break;

                case DATA_STRING:
                    stringRangeCompare();
                    break;

                default:
                    ePrintf( Runtime, "OpCaseRange: bad data type" );
                    break;
                }
                break;

            case OpCaseElse:
                /* put true on stack */
                pushNumber( 1 );
                break;

            default:
                ePrintf( Runtime, "opcode %s found in Case test chain",
                    opcodeName[node->op] );
            }

            /* was result true? */
            if (stack[tos].value.number) {
                /* leave true flag on stack and exit */
                break;
            }

            /* move to next test */
            node = node->right;
            if (node == NULL) {
                /* exit with false flag */
                break;
            }

            /* drop test result flag */
            dropTos();
        }
        break;

    case OpClassMethod:
    case OpClassMethodCall:

        /* the args */
        n1 = tos;

        /* mark start of created objects */
        pushCreateStack( 0 );

        /* the args */
        eval( node->right );

        argCount = (int)(tos - n1);
        me = 0;
        runMethod( node->left->value.symbol->klass, node->value.string );

        /* destroy created objects */
        clearCreateStack();

        /* drop result? */
        if (node->op == OpClassMethodCall) {
            dropTos();
        }

        break;

    case OpClose:
        if (node->left == NULL) {
            fileCloseAll();
        } else {
            eval( node->left );
            i = (int)popNumber();
            fileClose( i );
        }
        break;

    case OpCmp:
        eval( node->left );
        eval( node->right );

        switch(getStackType(tos)) {
        case DATA_NUMBER:
            numberCompare( node->value.iValue, 1 );
            break;

        case DATA_STRING:
            stringCompare( node->value.iValue, 1 );
            break;

        default:
            ePrintf( Runtime, "opCmp: can't handle datatype" );

        }
        break;

    case OpComma:

        /* optimized for linked lists */
        while (1) {
            /* exit flag set? */
            if (exitForFlag != 0 ||
                exitRoutineFlag != 0 ||
                exitDoFlag != 0 ||
                exitWhileFlag != 0 ||
                continueFlag ) {
                break;
            }

            if (node->left != NULL ) {
                eval( node->left );
            }

            /* end of list? */
            if (node->right == NULL ) {
                break;

            /* linked list? */
            } else if (node->right->op == OpComma) {
                node = node->right;

            /* not a list */
            } else {
                eval( node->right );
                break;
            }
        }
        break;

    case OpConcat:
        eval( node->left );
        eval( node->right );
        basConcat();
        break;

    case OpConstGet:
        s = node->value.symbol;
        i = s->stackPos;
        /* this better not be indirected! */
        switch (stack[i].datatype) {
        case DATA_STRING:
            pushString( stack[i].value.string );
            break;

        case DATA_NUMBER:
            pushNumber( stack[i].value.number );
            break;

        default:
            ePrintf( Runtime, "Can't fetch Const type %s",
                datumName[stack[i].datatype] );
            break;
        }
        break;

    case OpConstSet:
        s = node->value.symbol;
        eval( node->left );
        switch (stack[tos].datatype) {
        case DATA_STRING:
            stack[s->stackPos].datatype = DATA_STRING;
            stack[s->stackPos].value.string = stack[tos].value.string;
            stack[tos].datatype = DATA_NUMBER;
            tos--;
            break;

        case DATA_NUMBER:
            stack[s->stackPos].datatype = DATA_NUMBER;
            stack[s->stackPos].value.number = stack[tos].value.number;
            tos--;
            break;

        default:
            ePrintf( Runtime, "Can't set Const to %s", datumName[stack[tos].datatype] );
            break;
        }
        break;

    case OpDelete:
        eval( node->left );
        runDestructor( (int)popNumber(), OpDelete );
        break;

    case OpDestroy:
        eval( node->left );
        runDestructor( (int)popNumber(), OpDestroy );
        break;

    case OpContinue:
        continueFlag = 1;
        break;

    case OpDiv:
        eval( node->left );
        eval( node->right );

        n2 = popNumber();
        n1 = popNumber();

        if (n2 == 0.0) {
            ePrintf( Runtime, "Division by zero" );
        }

        pushNumber( n1 / n2 );
        break;

    case OpDo:
        while (1) {
            /* test */
            eval( node->left );
            /*if (!popNumber()){
                break;
            }*/

            /* code */
            eval( node->right );
	    //printf("exitDoFlag:%d\n",exitDoFlag);
            if (exitDoFlag != 0) {
                exitDoFlag = 0;
                break;
            }
	    else if (continueFlag) {
                continueFlag = 0;
            }
        }
        break;

    case OpEnd:
        eShutdown(0);
        break;

    case OpErase:
        if (node->left == NULL) {
            /* erase entire array */
            eraseArray( node->value.symbol );
        } else {
            /* evaluate the indexes */
            eval( node->left );

            /* erase single element from array */
            eraseArrayElement( node->value.symbol );
        }
        break;

    case OpExitDo:
        exitDoFlag = 1;
        break;

    case OpExitFor:
        exitForFlag = 1;
        break;

    case OpExitRoutine:
	currentScope=oldScope[oldScopeP--];
        exitRoutineFlag = 1;
        break;

    case OpExitWhile:
        exitWhileFlag = 1;
        break;

    case OpFloat:
        pushNumber( node->value.fValue );
        break;

    case OpFor:
        s = node->value.symbol;
        eval( node->left );
        n2 = popNumber();
        n1 = popNumber();

        /* initial value */
        pushNumber( n3 );
        setVar( s );

        for( n3=n1; n3 <= n2; n3++ ) {
            /* set loop variable */
            pushNumber( n3 );
            setVar( s );

            /* run code */
            eval( node->right );

            /* special exit condition? */
            if (exitForFlag) {
                exitForFlag = 0;
                break;
            } else if (continueFlag) {
                continueFlag = 0;
            }

            /* get loop value (in case it changed) */
            getVar( s );
            n3 = popNumber();

        }
        break;

    case OpForEach:
        /* variable to assign */
        s = node->value.symbol;

        /* array to read from */
        a = getArray( node->left->value.symbol );

        /* iterate through keys */
        i = 0;
        /* put key on stack, or exit */
        while (getDynamicKey( a, i )) {

            /* assign to variable */
            setVar( s );

            /* run block */
            eval( node->right );

            /* next */
            i += 1;
        }
        break;


    case OpForStep:
        s = node->value.symbol;
        eval( node->left );
        n3 = popNumber();       /* step  */
        n2 = popNumber();       /* end   */
        n1 = popNumber();       /* start */

        /* which direction? */
        if (n3 > 0) {
            n2 += ALLOWABLE_ERROR;
            for( n4=n1; n2 >= n4; n4 += n3 ) {
                /* set loop variable */
                pushNumber( n4 );
                setVar( s );

                /* run code */
                eval( node->right );

                /* special exit condition? */
                if (exitForFlag) {
                    exitForFlag = 0;
                    break;
                } else if (continueFlag) {
                    continueFlag = 0;
                }

                /* get loop value (in case it changed) */
                getVar( s );
                n4 = popNumber();

            }
        } else {
            n2 -= ALLOWABLE_ERROR;
            for( n4=n1; n2 <= n4; n4 += n3 ) {
                /* set loop variable */
                pushNumber( n4 );
                setVar( s );

                /* run code */
                eval( node->right );

                /* special exit condition? */
                if (exitForFlag) {
                    exitForFlag = 0;
                    break;
                } else if (continueFlag) {
                    continueFlag = 0;
                }

                /* get loop value (in case it changed) */
                getVar( s );
                n4 = popNumber();

            }
        }

        break;

    case OpFunction:
    case OpFunctionCall:
        callFunction( node );
        break;

    case OpInitArray:
        if (node->left == NULL) {
            createDynamicArray( node->value.symbol );
        } else {
            eval( node->left );
            createStaticArray( node->value.symbol );
        }
        break;

    case OpInput:
        if (node->value.iValue == 1) {
            eval( node->left );
            i = (int)popNumber();

            string1 = fileLineInput( i );
            pushString( string1  );

        } else {
            /* command line */
            ePrintf( Runtime, "Input statement is not currently supported" );

        }
        break;

    case OpInt:
        pushNumber( node->value.iValue );
        break;

    case OpMethod:
    case OpMethodCall:

        /* the index */
        eval( node->left );
        n1 = popNumber();

        /* method name */
        string1 = node->value.string;

        /* mark start of created objects */
        pushCreateStack( 0 );

        /* args */
        n2 = tos;
        eval( node->right );
        argCount = (int)(tos - n2);

        /* resolve and run method */
        resolveMethod( (int)n1, string1 );

        /* drop result? */
        if (node->op == OpMethodCall) {
            dropTos();
        }

        /* destroy created objects */
        clearCreateStack();

        break;

    case OpMod:
        eval( node->left );
        eval( node->right );

        n2 = popNumber();
        n1 = popNumber();

        //pushNumber( (long)n1 % (long)n2 );
        pushNumber( fmod(n1,n2) );
        
        break;

    case OpMul:
        eval( node->left );
        eval( node->right );

        n2 = popNumber();
        n1 = popNumber();

        pushNumber( n1 * n2 );
        break;

    case OpOpen:
        /* file name */
        eval( node->left );
        string1 = popString();

        /* mode */
        i = node->value.iValue;

        /* file number */
        eval( node->right );
        n1 = popNumber();

        fileOpen( string1, i, (int)n1 );
        free( string1 );

        break;

    case OpOr:
        /* short circuit */
        eval( node->left );
        if (popNumber()) {
            pushNumber( (Number)1 );
        } else {
            eval( node->right );
            if (popNumber()) {
                pushNumber( (Number)1 );
            } else {
                pushNumber( (Number)0 );
            }
        }
        break;

    case OpOrBits:
        eval( node->left );
        eval( node->right);
        i = popNumber();
        j = popNumber();
        pushNumber( i | j );
        break;

    case OpIDiv:
        eval( node->left );
        eval( node->right );

        n2 = popNumber();
        n1 = popNumber();

        /* check for division by zero */
        if (n2 == 0.0) {
            ePrintf( Runtime, "Division by zero" );
        }

        pushNumber( floor(n1 / n2) );
        break;

    case OpIf:
        n = node->left;

        /* test */
        eval( n->left );
        n1 = popNumber();
        if (n1 != 0) {
            /* true portion */
            eval( n->right );
        } else {
            /* false portion */
            eval( node->right );
        }
        break;

    case OpIfTrue:
        ePrintf( Runtime, "OpIfTrue: internal error" );
        break;

    case OpIn:
        /* evaluate key */
        eval( node->left );

        /* look for it in array */
        pushNumber( inArray( node->value.symbol ) );

        break;

    case OpInv:
        ePrintf( Runtime, "Inv is not implemented yet" );
        break;

    case OpNegate:
        eval( node->left );
        n1 = popNumber();
        pushNumber( -n1 );
        break;

    case OpNew:
    case OpNewTmp:

        /* mark start of created objects */
        pushCreateStack( 0 );

        /* the args */
        n1 = tos;
        eval( node->left );
        argCount = (int)(tos - n1);
        runMethod( node->value.symbol->klass, "new" );

        /* destroy created objects *before* adding new object to stack */
        clearCreateStack();

        /* add new object to create stack? */
        if (node->op == OpNewTmp) {
            /* track on stack */
            copyStackItem( tos );
            pushCreateStack( (int)popNumber() );
        }

        break;

    case OpNoOp:
        break;

    case OpNot:
        eval( node->left );
        n1 = popNumber();
        pushNumber( !n1 );
        break;

    case OpPower:
        eval( node->left );
        eval( node->right );

        n2 = popNumber();
        n1 = popNumber();

        pushNumber( pow( n1, n2 ) );
        break;

    case OpPrint:
        if (node->left == NULL) {
            i = 0;
        } else {
            eval( node->left );
            i = (int)popNumber();
        }

        node = node->right;


        /* empty print statement */
        if (node == NULL) {
            if (i==0) {
                eConsole("\n");
            } else {
                filePrintString( i, "\n" );
            }
        }

        /* process nodes */
        while(node != NULL) {

            /* data value */
            if (node->left != NULL) {
                eval( node->left );
                string1 = popString();
                if (i==0) {
                    eConsole("%s", string1 );
                } else {
                    filePrintString( i, string1 );
                }
                eFree( string1 );
            }

            /* field delimiter */
            switch (node->value.iValue) {
            case PRINT_TAB:
                if (i==0) {
                    eConsole("\t");
                } else {
                    filePrintString( i, "\t" );
                }
                break;
            case PRINT_NEWLINE:
                if (i==0) {
                    eConsole("\n");
                } else {
                    filePrintString( i, "\n" );
                }
                break;
            default:
                /* no action */
                break;
            }

            /* link */
            node = node->right;

        }
        break;


    case OpReturnValue:
        eval( node->left );
        setReturn();
        exitRoutineFlag = 1;
        break;


    case OpReturnSetValue:
        eval( node->left );
        setReturn();
        break;

    case OpShl:
        eval( node->left );
        eval( node->right );

        n2 = popNumber();
        n1 = popNumber();

        pushNumber( (long)n1 << (long)n2 );
        break;

    case OpShr:
        eval( node->left );
        eval( node->right );

        n2 = popNumber();
        n1 = popNumber();

        pushNumber( (long)n1 >> (long)n2 );
        break;

    case OpString:
        pushStringCopy( node->value.string );
        break;

    case OpSub:

        eval( node->left );
        eval( node->right );

        n2 = popNumber();
        n1 = popNumber();

        pushNumber( n1 - n2 );
        break;

    case OpUndefined:
        ePrintf( Runtime, "Opcode is undefined" );
        break;

    case OpVar:
        /* check type */
        getVar( node->value.symbol );
        if (getStackType(tos) == DATA_UNDEFINED) {
            ePrintf( Runtime, "the value of %s is undefined",
                node->value.symbol->name );
        }
        break;

    case OpWhile:
        while (1) {
            /* test */
            eval( node->left );
            if (!popNumber()){
                break;
            }

            /* code */
            eval( node->right );

            if (exitWhileFlag != 0) {
                exitWhileFlag = 0;
                break;

            } else if (continueFlag) {
                continueFlag = 0;
            }
        }
        break;


    case OpXor:
        eval( node->left );
        eval( node->right );

        n2 = popNumber();
        n1 = popNumber();

        pushNumber( (long)n1 ^ (long)n2 );
        break;

    default:
        ePrintf( Runtime, "Unknown Opcode: %d", node->op );

    }
}
示例#20
0
bool ZCMGen::isArrayDimType(const string& t)   { return inArray(arrayDimTypes, t);  }
示例#21
0
bool ZCMGen::isLegalConstType(const string& t) { return inArray(constTypes, t);     }
示例#22
0
bool ZCMGen::isPrimitiveType(const string& t)  { return inArray(primitiveTypes, t); }
示例#23
0
int main  (int argc, char **argv)
{
  puts("Program starts");
  /* Checking command line, 
  throw exception if not complete */
  //printf("%s %s %s %s %s %s %s\n", argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6]);

  if (argc != 12)
  {
    printf("\nUsage: %s <input file 1.pdb> <input file 2.pdb> <output file> <chain1> <chain2> <start1> <end1> <start2> <end2> <file name for score> <is on server>", argv[0]);
    printf("\nExample: %s 3hdd.pdb 1puf.pdb superpos_3hdd_1puf.pdb A B 5 60 zero inf max_score.txt 0\n\n", argv[0]);
    exit (1);
  } /* end if */
  
  /* Done checking command line */

  /* Reading command line arguments */

  char *infile1, *infile2, *outfile, *max_score_filename;
  char *start1, *end1, *start2, *end2;
  char chain1, chain2;
  unsigned int SERVER;

  infile1 = (char *)malloc( sizeof(char)*(strlen(argv[1])+1) );
  sscanf(argv[1],"%s", infile1);

  infile2 = (char *)malloc( sizeof(char)*(strlen(argv[2])+1) );
  sscanf(argv[2],"%s", infile2);

  outfile = (char *)malloc( sizeof(char)*(strlen(argv[3])+1) );
  sscanf(argv[3], "%s", outfile);

  sscanf(argv[4], "%c", &chain1);
  sscanf(argv[5], "%c", &chain2);

  start1 = (char *)malloc( sizeof(char)*(strlen(argv[6])+1) );
  end1 = (char *)malloc( sizeof(char)*(strlen(argv[7])+1) );
  start2 = (char *)malloc( sizeof(char)*(strlen(argv[8])+1) );
  end2 = (char *)malloc( sizeof(char)*(strlen(argv[9])+1) );
  sscanf(argv[6], "%s", start1);
  sscanf(argv[7], "%s", end1);
  sscanf(argv[8], "%s", start2);
  sscanf(argv[9], "%s", end2);

  max_score_filename = (char *)malloc( sizeof(char)*(strlen(argv[10])+1) );
  sscanf(argv[10], "%s", max_score_filename);

  sscanf(argv[11], "%u", &SERVER);

  /* Done reading arguments */

  /* DECLARATION AND ASSIGNMENT 
  OF SOME VARIABLES */

  struct atom *atoms_prot1 = NULL, *atoms_prot2 = NULL;
  struct atom *all_atoms_dna1 = NULL, *all_atoms_dna2 = NULL;
  struct atom *atoms_wat1 = NULL, *atoms_wat2 = NULL;
  struct atom *atoms_prot_CA1 = NULL, *atoms_prot_CA2 = NULL;
  struct atom *atoms_prot_C1 = NULL, *atoms_prot_C2 = NULL;
  struct atom *atoms_prot_i1 = NULL, *atoms_prot_i2 = NULL;
  struct atom *atoms_prot_j1 = NULL, *atoms_prot_j2 = NULL;
  struct atom *C_atoms_prot_i1 = NULL, *C_atoms_prot_j2 = NULL;

  struct atomname *list1, *list2;

  unsigned int maxnumber = 256; //primary number of atoms in each groups (DNA, protein, water)
  FILE *flow_out;
  unsigned int all_m1=0, n1=0, w1=0, i, j, all_m2=0, n2=0, w2=0;
  /* m - number of DNA atoms
   * n - number of protein atoms
   * w - number of water atoms */
  char *dna_chains1 = (char *)malloc( sizeof(char)*(2+1) );
  char *prot_chains1 = (char *)malloc( sizeof(char)*(2+1) );
  char *dna_chains2 = (char *)malloc( sizeof(char)*(2+1) );
  char *prot_chains2 = (char *)malloc( sizeof(char)*(2+1) );

  /*** For server ***/
  FILE *max_score;

//printf("%s", max_score_filename);
  max_score = fopen(max_score_filename, "w");
  if (max_score == NULL) {
    perror(max_score_filename);
    exit(1);
  }
  
  /* Reading PDB file */
  
  puts("Reading 1st PDB file...");
  readerPDB(infile1, &all_m1, &n1, &w1, maxnumber, &all_atoms_dna1, &dna_chains1, &atoms_prot1, &prot_chains1, &atoms_wat1, &list1); 
    // pdb.c function, read PDB and put protein, DNA and water atoms in three different arrays
  printf("...done; %d atoms of dna, %d atoms of protein, %d atoms of water\n", all_m1, n1, w1);
  if (all_m1 == 0)
    {fprintf(max_score, "Error\nFirst structure has no DNA!");
    exit(1); }
  if (chain1=='@')
    chain1 = prot_chains1[1];
  else
    if ( inArray(chain1, prot_chains1)==0 )
      { fprintf(max_score, "Error\nChain %c is not a protein chain in first structure", chain1);
      exit(1); }
  SelectChain(atoms_prot1, n1, &atoms_prot1, &n1, chain1);
  SelectRange(atoms_prot1, n1, &atoms_prot1, &n1, start1, end1);
  // pdb.c function
  printf("Atoms in selected chain: %u\n\n", n1); 
    // print to stdout number of protein atoms in selected chain

  puts("Reading 2nd PDB file...");
  readerPDB(infile2, &all_m2, &n2, &w2, maxnumber, &all_atoms_dna2, &dna_chains2, &atoms_prot2, &prot_chains2, &atoms_wat2, &list2); 
  printf("...done; %d atoms of dna, %d atoms of protein, %d atoms of water\n", all_m2, n2, w2);
  if (all_m2 == 0)
    {fprintf(max_score, "Error\nSecond structure has no DNA!");
    exit(1); }
  if (chain2=='@')
    chain2 = prot_chains2[1];
  else
    if ( inArray(chain2, prot_chains2)==0 )
      { fprintf(max_score, "Error\nChain %c is not a protein chain in second structure!", chain2);
      exit(1); }
  SelectChain(atoms_prot2, n2, &atoms_prot2, &n2, chain2);
  SelectRange(atoms_prot2, n2, &atoms_prot2, &n2, start2, end2);
  printf("Atoms in selected chain: %u\n\n", n2);

  dna_chains1[0] = ' '; dna_chains2[0] = ' ';
  /*** For server ***/
  char dna_chain1, dna_chain2;
  //dna_chain2 = dna_chains2[1];
  
  printf("DNA1 chains: %s; DNA2 chains: %s\n", dna_chains1, dna_chains2);
  /* Done reading */

  /*** 3DNA block ***/
  
  unsigned int *compl_list1, *compl_list2, n_pairs1, n_pairs2, pair1, pair2;
  int **compl_pairs1, **compl_pairs2;
  char **pairs1, **pairs2;
  
  run_3dna(infile1, &compl_list1, &compl_pairs1, &pairs1, &n_pairs1, SERVER, max_score_filename);
  run_3dna(infile2, &compl_list2, &compl_pairs2, &pairs2, &n_pairs2, SERVER, max_score_filename);

  
  /*** 3DNA block end ***/
  
  /*** MAIN FOR CYCLE ***/
  struct atom *best_atoms_dna1 = NULL, *best_atoms_dna2 = NULL;
  struct atom *best_dna1_chain1, *best_dna1_chain2, *best_dna2_chain1, *best_dna2_chain2;
  unsigned int *best_list_P1, *best_list_C11, *best_list_OP11, *best_list_OP21, *best_list_P2, *best_list_C12, *best_list_OP12, *best_list_OP22;
  unsigned int best_n_P1, best_n_P2;
  unsigned int best_dna1_chain1_n, best_dna1_chain2_n, best_dna2_chain1_n, best_dna2_chain2_n;
  unsigned int best_i_max_measure, best_j_max_measure;
  unsigned int best_compl1, best_compl2;
  unsigned int best_n_first_chain, best_m_first_chain;
  unsigned int best_pair1, best_pair2;
  double best_S_max = -1;
  
  for (pair1=1; pair1<=n_pairs1; pair1++)
  {
  	struct atom *atoms_dna1 = NULL, *dna1_chain1 = NULL, *dna1_chain2 = NULL; 
  	unsigned int m1, dna1_chain1_n=0, dna1_chain2_n=0;
  	SelectChain(all_atoms_dna1, all_m1, &dna1_chain1, &dna1_chain1_n, pairs1[pair1][1]);
  	SelectChain(all_atoms_dna1, all_m1, &dna1_chain2, &dna1_chain2_n, pairs1[pair1][2]);
  	atomlistmerge(&atoms_dna1, &m1, dna1_chain1, dna1_chain1_n, dna1_chain2, dna1_chain2_n);
  	
  	//printf("%u/%u\n", pair1, n_pairs1);
  	/* Make lists of P, C1', OP1 atoms 
	  of dna and CA atoms of protein */
  	unsigned int *list_P1, *list_C11, *list_OP11, *list_OP21, *list_CA1, *list_C1;
  	unsigned int n_P1, n_C11, n_OP11, n_OP21, n_CA1, n_C1;
  	getAtomsNumbers(atoms_dna1, m1, &list_P1, &n_P1, "P"); 
	// pdb.c function, get only indexes of atoms
	getAtomsNumbers(atoms_dna1, m1, &list_C11, &n_C11, "C1'");
	getAtomsNumbers(atoms_dna1, m1, &list_OP11, &n_OP11, "OP1");
	getAtomsNumbers(atoms_dna1, m1, &list_OP21, &n_OP21, "OP2");
	getAtomsNumbers(atoms_prot1, n1, &list_CA1, &n_CA1, "CA");
	getAtomsNumbers(atoms_prot1, n1, &list_C1, &n_C1, "C");
	correctC1_P(atoms_dna1, &list_C11, &n_C11, list_P1, &n_P1);
	//for (i=1; i<=n_C11; i++) printf("%s.%c\n", atoms_dna1[list_C11[i]].ResNumber, atoms_dna1[list_C11[i]].Chain);
	    //corrects list_C1 to use rule list_P[i] and list_C1[i+1] are in the same nucleotide
	
	atoms_prot_CA1 = (struct atom *)malloc( sizeof(struct atom)*(n_CA1+1) );
	for (i=1; i<=n_CA1; i++) {
	    atomcpy(&atoms_prot_CA1[i], atoms_prot1[list_CA1[i]]); 
	    //pdb.c function. Copy all properties of atom
	}
	atoms_prot_C1 = (struct atom *)malloc( sizeof(struct atom)*(n_C1+1) );
	for (i=1; i<=n_C1; i++) {
		atomcpy(&atoms_prot_C1[i], atoms_prot1[list_C1[i]]);
	}
  	printf("Done atoms:\tP %u\tC1 %u\tOP1 %u\tOP2 %u\tCA %u\tC %u\n",n_P1, n_C11, n_OP11, n_OP21, n_CA1, n_C1); 	
	
  	
  	for (pair2=1; pair2<=n_pairs2; pair2++)
	{
	//printf("%u/%u\n", pair2, n_pairs2);
	printf("\nCYCLE %c:%c vs %c:%c\n", pairs1[pair1][1], pairs1[pair1][2], pairs2[pair2][1], pairs2[pair2][2]);
		struct atom *atoms_dna2 = NULL, *dna2_chain1, *dna2_chain2;
		unsigned int m2, dna2_chain1_n=0, dna2_chain2_n=0;
		SelectChain(all_atoms_dna2, all_m2, &dna2_chain1, &dna2_chain1_n, pairs2[pair2][1]);
		SelectChain(all_atoms_dna2, all_m2, &dna2_chain2, &dna2_chain2_n, pairs2[pair2][2]);
		atomlistmerge(&atoms_dna2, &m2, dna2_chain1, dna2_chain1_n, dna2_chain2, dna2_chain2_n);
		
  
	  
	  unsigned int *list_P2, *list_C12, *list_OP12, *list_OP22, *list_CA2, *list_C2;
	  unsigned int n_P2, n_C12, n_OP12, n_OP22, n_CA2, n_C2;

	  getAtomsNumbers(atoms_dna2, m2, &list_P2, &n_P2, "P");
	  getAtomsNumbers(atoms_dna2, m2, &list_C12, &n_C12, "C1'");
	  getAtomsNumbers(atoms_dna2, m2, &list_OP12, &n_OP12, "OP1");
	  getAtomsNumbers(atoms_dna2, m2, &list_OP22, &n_OP22, "OP2");
	  getAtomsNumbers(atoms_prot2, n2, &list_CA2, &n_CA2, "CA");
	  getAtomsNumbers(atoms_prot2, n2, &list_C2, &n_C2, "C");
	  correctC1_P(atoms_dna2, &list_C12, &n_C12, list_P2, &n_P2);

	  atoms_prot_CA2 = (struct atom *)malloc( sizeof(struct atom)*(n_CA2+1) );
	  for (i=1; i<=n_CA2; i++) {
	    atomcpy(&atoms_prot_CA2[i], atoms_prot2[list_CA2[i]]);
		}
	  atoms_prot_C2 = (struct atom *)malloc( sizeof(struct atom)*(n_C2+1) );
	  for (i=1; i<=n_C2; i++) {
	  	atomcpy(&atoms_prot_C2[i], atoms_prot2[list_C2[i]]);
	  }
	  printf("Done atoms:\tP %u\tC1 %u\tOP1 %u\tOP2 %u\tCA %u\tC %u\n",n_P2, n_C12, n_OP12, n_OP22, n_CA2, n_C2);  

	  /* Done making lists */

  /* Create array of measures for 
  all pairs of dna P atoms (list_measure). 
  dim(list_measure) = n_P2 x n_P1 */
  
	  double **list_measure;
	  unsigned int n_hit; 
	  unsigned int **list_hit;
	  
	  list_measure = (double **)malloc( (n_P2+1)*sizeof(double *)*(n_P1+1) );
	  for (i=1; i<=n_P1; i++)  list_measure[i] = (double *)malloc( sizeof(double)*(n_P2+1) );
	  //for (i=1; i<=n_P1; i++) for (j=1; j<=n_P2;j++)  list_measure[i][j] = (unsigned int *)malloc( sizeof(unsigned int) ); 
	    // Enable if measure function returns unsigned int 
	  
	  
	  for (i=1; i<=n_P1; i++){
	    for (j=1; j<=n_P2; j++){  
	      ChangeSystem(atoms_prot_CA1, n_CA1, &atoms_prot_i1, atoms_dna1[list_P1[i]], atoms_dna1[list_C11[i+1]], atoms_dna1[list_OP11[i]], atoms_dna1[list_OP21[i]], 'E'); 
		// pdb.c function. Change the coordinate system of protein with given nucleotide
	      ChangeSystem(atoms_prot_C1, n_C1, &C_atoms_prot_i1, atoms_dna1[list_P1[i]], atoms_dna1[list_C11[i+1]], atoms_dna1[list_OP11[i]], atoms_dna1[list_OP21[i]], 'E');
	      ChangeSystem(atoms_prot_CA2, n_CA2, &atoms_prot_j2, atoms_dna2[list_P2[j]], atoms_dna2[list_C12[j+1]], atoms_dna2[list_OP12[j]], atoms_dna2[list_OP22[j]], 'F');
	      ChangeSystem(atoms_prot_C2, n_C2, &C_atoms_prot_j2, atoms_dna2[list_P2[j]], atoms_dna2[list_C12[j+1]], atoms_dna2[list_OP12[j]], atoms_dna2[list_OP22[j]], 'F');
		    BidirectionalHit(atoms_prot_i1, C_atoms_prot_i1, n_CA1, atoms_prot_j2, C_atoms_prot_j2, n_CA2, &list_hit, &n_hit); 
		// pdb.c function.
		    Measure2_p(&(list_measure[i][j]), list_hit, n_hit, atoms_prot_i1, atoms_prot_j2); 
		// pdb.c function.
		    // printf("Measure: %f  i: %u j: %u n_P1: %u  n_P2: %u \n",(list_measure[i][j]), i,j, n_P1, n_P2); 
		// Enable in test mode
	    }
	  }

	  /* Done creation of array of measures */


	  /* Start working with diagonals */

	  unsigned int i_max, j_max, i_start, j_start, i_max_measure, j_max_measure;
	  unsigned int n_first_chain, m_first_chain;
	  unsigned int compl1, compl2;
	  double S_max;
	  struct atom *atoms_dna_P1 = NULL;
	  struct atom *atoms_dna_P2 = NULL;

	  // print measure-table
	  /*printf("  ");
	  for (j=1; j<=n_P2; j++) printf("%4d", j);
	  puts("");
	  for (i=n_P1; i>=1; i--){
	  	printf("%2d", i);
		for (j=1; j<=n_P2; j++){
			printf("%4.0f", list_measure[i][j]>0 ? list_measure[i][j] : 0);
		}
		puts("");
	  }
	  printf("  ");
	  for (j=1; j<=n_P2; j++) printf("%4d", j);
	  puts(""); */
	  
	 
	  i_max_measure=0;
	  j_max_measure=0;
	  atoms_dna_P1 = (struct atom *)malloc( sizeof(struct atom)*(n_P1+1) );
		for (i=1; i<=n_P1; i++) {
		atomcpy(&atoms_dna_P1[i], atoms_dna1[list_P1[i]]);
	  }
	  atoms_dna_P2 = (struct atom *)malloc( sizeof(struct atom)*(n_P2+1) );
		for (i=1; i<=n_P2; i++) {
		atomcpy(&atoms_dna_P2[i], atoms_dna2[list_P2[i]]);
	  }
	  
	  //find_compl(atoms_dna1, list_P1, list_C11, list_OP11, list_OP21, atoms_dna_P1, n_P1, &compl1, &n_first_chain, max_score);
	  run_find_compl(atoms_dna_P1, n_P1, &compl1, &n_first_chain, compl_pairs1[pair1]);
	  //find_compl(atoms_dna2, list_P2, list_C12, list_OP12, list_OP22, atoms_dna_P2, n_P2, &compl2, &m_first_chain, max_score);
	  run_find_compl(atoms_dna_P2, n_P2, &compl2, &m_first_chain, compl_pairs2[pair2]);
	  BestDiag(list_measure, n_P1, n_P2, &S_max, &i_max, &j_max, &i_start, &j_start, &i_max_measure, &j_max_measure,
	  	   atoms_dna1, list_P1, atoms_dna2, list_P2, compl1, compl2, n_first_chain, m_first_chain);
	  // pdb.c function 

	  /* Done diagonal search */
	  
	  if (S_max > best_S_max)
  	  {
  		best_S_max = S_max;
  		atomlistcpy(&best_dna1_chain1, dna1_chain1, dna1_chain1_n);
  		best_dna1_chain1_n = dna1_chain1_n;
  		atomlistcpy(&best_dna1_chain2, dna1_chain2, dna1_chain2_n);
  		best_dna1_chain2_n = dna1_chain2_n;
  		atomlistcpy(&best_dna2_chain1, dna2_chain1, dna2_chain1_n);
  		best_dna2_chain1_n = dna2_chain1_n;
  		atomlistcpy(&best_dna2_chain2, dna2_chain2, dna2_chain2_n);
  		best_dna2_chain2_n = dna2_chain2_n;
  		
  		best_n_P1 = n_P1;
  		best_n_P2 = n_P2;
  		
  		atomlistcpy(&best_atoms_dna1, atoms_dna1, m1);
  		best_list_P1 = (unsigned int *)malloc(sizeof(unsigned int)*(n_P1+1));
  		best_list_C11 = (unsigned int *)malloc(sizeof(unsigned int)*(n_C11+1));
  		best_list_OP11 = (unsigned int *)malloc(sizeof(unsigned int)*(n_OP11+1));
  		best_list_OP21 = (unsigned int *)malloc(sizeof(unsigned int)*(n_OP21+1));
  		memcpy(best_list_P1, list_P1, sizeof(unsigned int)*(n_P1+1));
  		memcpy(best_list_C11, list_C11, sizeof(unsigned int)*(n_C11+1));
  		memcpy(best_list_OP11, list_OP11, sizeof(unsigned int)*(n_OP11+1));
  		memcpy(best_list_OP21, list_OP21, sizeof(unsigned int)*(n_OP21+1));
  			
  		atomlistcpy(&best_atoms_dna2, atoms_dna2, m2);
  		best_list_P2 = (unsigned int *)malloc(sizeof(unsigned int)*(n_P2+1));
  		best_list_C12 = (unsigned int *)malloc(sizeof(unsigned int)*(n_C12+1));
  		best_list_OP12 = (unsigned int *)malloc(sizeof(unsigned int)*(n_OP12+1));
  		best_list_OP22 = (unsigned int *)malloc(sizeof(unsigned int)*(n_OP22+1));
  		memcpy(best_list_P2, list_P2, sizeof(unsigned int)*(n_P2+1));
  		memcpy(best_list_C12, list_C12, sizeof(unsigned int)*(n_C12+1));
  		memcpy(best_list_OP12, list_OP12, sizeof(unsigned int)*(n_OP12+1));
  		memcpy(best_list_OP22, list_OP22, sizeof(unsigned int)*(n_OP22+1));
  		best_i_max_measure = i_max_measure;
  		best_j_max_measure = j_max_measure;
  		best_compl1 = compl1;
  		best_compl2 = compl2;
  		best_n_first_chain = n_first_chain;
  		best_m_first_chain = m_first_chain;
  		best_pair1 = pair1;
  		best_pair2 = pair2;
  	  }
  	
  	//free array's memory after cycle
  	/*free(list_P2);
  	free(list_C12);
  	free(list_OP12);
  	free(list_OP22);
  	free(list_CA2);
  	free(list_C2);
  	free(atoms_prot_CA2);
  	free(atoms_prot_C2);
  	for (i=1; i<=n_P1; i++) free(list_measure[i]);
  	free(list_measure);
  	free(atoms_dna_P1);
  	free(atoms_dna_P2);
  	free(atoms_dna2);
  	free(dna2_chain1);
  	free(dna2_chain2);
  	free(atoms_prot_i1);
  	free(C_atoms_prot_i1);
  	free(atoms_prot_j2);
  	free(C_atoms_prot_j2);*/

	}
	
  /*free(list_P1);
  free(list_C11);
  free(list_OP11);
  free(list_OP21);
  free(list_CA1);
  free(list_C1);
  free(atoms_prot_CA1);
  free(atoms_prot_C1);
  free(atoms_dna1);
  free(dna1_chain1);
  free(dna1_chain2);*/
  } 
  /*** END OF MAIN CYCLE ***/
  
    /****reading DNA sequences ***/
  unsigned int dna_n11, dna_n12, dna_n21, dna_n22; //sequence length
  char *dna_seq11, *dna_seq12, *dna_seq21, *dna_seq22;
  char *dna_num_seq11, *dna_num_seq12, *dna_num_seq21, *dna_num_seq22;
  int dna1_chain1_start, dna1_chain2_start, dna2_chain1_start, dna2_chain2_start;

  	//SelectChain(atoms_dna1, m1, &dna1_chain1, &dna1_chain1_n, dna_chains1[1]);
  Seq(best_dna1_chain1, best_dna1_chain1_n, &dna_seq11, &dna_num_seq11, &dna_n11, max_score);
  sscanf(best_dna1_chain1[1].ResNumber, "%d", &dna1_chain1_start);

  Seq(best_dna1_chain2, best_dna1_chain2_n, &dna_seq12, &dna_num_seq12, &dna_n12, max_score);
  sscanf(best_dna1_chain2[1].ResNumber, "%d", &dna1_chain2_start);

  Seq(best_dna2_chain1, best_dna2_chain1_n, &dna_seq21, &dna_num_seq21, &dna_n21, max_score);
  sscanf(best_dna2_chain1[1].ResNumber, "%d", &dna2_chain1_start);

  Seq(best_dna2_chain2, best_dna2_chain2_n, &dna_seq22, &dna_num_seq22, &dna_n22, max_score);
  sscanf(best_dna2_chain2[1].ResNumber, "%d", &dna2_chain2_start);
  
  
  //printf("%c %c %c %c %c %c\n%lg\n%s\n%s", chain1, chain2, dna_chains1[1], dna_chains1[2], dna_chains2[1], dna_chains2[2], S_max, dna_string1, dna_string2);
  /*** For server work - DNA alignment making ***/
  
  if (best_S_max == 0)
  	fprintf(max_score, "Warning! The score is zero! It seems you have specified wrong parameters.\n");
  
  unsigned int i_max_measure_compl, j_max_measure_compl;
  unsigned int is_reverse1, is_reverse2;
  
  //printf("n_first_chain=%u i_max_measure=%u best_compl1=%u\n", best_n_first_chain, best_i_max_measure,  best_compl1);
  is_reverse1 = ((best_i_max_measure > best_n_first_chain) ? 1 : 0);
  is_reverse2 = ((best_j_max_measure > best_m_first_chain) ? 1 : 0);
  i_max_measure_compl = ((best_i_max_measure > best_n_first_chain) ? best_compl1-best_i_max_measure+1 : best_compl1-best_i_max_measure+1);
  j_max_measure_compl = ((best_j_max_measure > best_m_first_chain) ? best_compl2-best_j_max_measure+1 : best_compl2-best_j_max_measure+1);
  //printf("i_max_measure=%u i_max_measure_compl=%u\n", best_i_max_measure, i_max_measure_compl);
  //printf("i_max_measure=%s\n", best_atoms_dna1[best_list_P1[best_i_max_measure]].ResNumber);
  //printf("i_max_measure_compl=%s\n", best_atoms_dna1[best_list_P1[i_max_measure_compl]].ResNumber);
//puts("OK1");
  
  if (i_max_measure_compl > best_n_P1)
  {
  	//printf("i_compl=%u n11=%u n12=%u\n", i_max_measure_compl, dna_n11, dna_n12);
  	j_max_measure_compl = j_max_measure_compl-(i_max_measure_compl-best_n_P1);
  	i_max_measure_compl = best_n_P1;
  	//printf("i_compl=%u n11=%u n12=%u\n", i_max_measure_compl, dna_n11, dna_n12);
  }
  if (j_max_measure_compl > best_n_P2)
  {
  	//printf("j_compl=%u n21=%u n22=%u\n", j_max_measure_compl, dna_n21, dna_n22);
  	i_max_measure_compl = i_max_measure_compl-(j_max_measure_compl-best_n_P2);
  	j_max_measure_compl = best_n_P2;
  	//printf("j_compl=%u n21=%u n22=%u\n", j_max_measure_compl, dna_n21, dna_n22);
  }
//puts("OK2");  
  //if max_compl = 0 or less
  if (i_max_measure_compl < 1)
  {
  	i_max_measure_compl = 1;
  	j_max_measure_compl = j_max_measure_compl + 1 - i_max_measure_compl;
  }
  if (j_max_measure_compl < 1)
  {
  	j_max_measure_compl = 1;
  	i_max_measure_compl = i_max_measure_compl + 1 - j_max_measure_compl;
  }
//puts("OK3");
  int i_max_measure_compl_num, j_max_measure_compl_num;
  char *i_max_measure_compl_str, *j_max_measure_compl_str;
  i_max_measure_compl_str = (char *)malloc( sizeof(char)*7 );
  j_max_measure_compl_str = (char *)malloc( sizeof(char)*7 );

  sscanf(best_atoms_dna1[best_list_P1[i_max_measure_compl]].ResNumber, "%d", &i_max_measure_compl_num);
  sscanf(best_atoms_dna2[best_list_P2[j_max_measure_compl]].ResNumber, "%d", &j_max_measure_compl_num);
  if (i_max_measure_compl==best_i_max_measure)
  {
  	sscanf(best_atoms_dna1[best_list_P1[i_max_measure_compl+1]].ResNumber, "%d", &i_max_measure_compl_num);
  	i_max_measure_compl_num = i_max_measure_compl_num - 1;
	//puts("Here1");
  }
  if (j_max_measure_compl==best_j_max_measure)
  {
	  sscanf(best_atoms_dna2[best_list_P2[j_max_measure_compl+1]].ResNumber, "%d", &j_max_measure_compl_num);
	  j_max_measure_compl_num = j_max_measure_compl_num - 1;
	  //puts("Here2");
  }
  //printf("%d\n", j_max_measure_compl_num);
//puts("OK4"); 
  int start, i_start;
  start = (is_reverse1 == 1) ? dna1_chain1_start : dna1_chain2_start;
  i_start = (is_reverse1 == 1) ? 1 : dna_n11+1;
  if (i_max_measure_compl_num < start && i_max_measure_compl < i_start)
  {
  	//printf("ires_compl=%d start=%d\n", i_max_measure_compl_num, start);
  	j_max_measure_compl_num = j_max_measure_compl_num + start - i_max_measure_compl_num;
  	i_max_measure_compl_num = start;
  	//printf("ires_compl=%d start=%d\n", i_max_measure_compl_num, start);
  }
  start = (is_reverse2 == 1) ? dna2_chain1_start : dna2_chain2_start;
  i_start = (is_reverse2 == 1) ? 1 : dna_n21+1;
  if (j_max_measure_compl_num < start && j_max_measure_compl < i_start)
  {
  	//printf("jres_compl=%d start=%d\n", j_max_measure_compl_num, start);
  	i_max_measure_compl = i_max_measure_compl_num + start - j_max_measure_compl_num;
  	j_max_measure_compl = start;
  	//printf("jres_compl=%d start=%d\n", j_max_measure_compl_num, start);
  }
  //printf("%d\n", j_max_measure_compl_num);
  
  sprintf(i_max_measure_compl_str, "%d", i_max_measure_compl_num);
  sprintf(j_max_measure_compl_str, "%d", j_max_measure_compl_num);
  //printf("%d\n", j_max_measure_compl_num);
//puts("OK5");
  fprintf(max_score, "%c %c %c %c %c %c %s %s %s %s %u %u\n%lg\n%s %s\n%s %s\n%s %s\n%s %s", chain1, chain2, pairs1[best_pair1][1], pairs1[best_pair1][2], pairs2[best_pair2][1], pairs2[best_pair2][2], best_atoms_dna1[best_list_P1[best_i_max_measure]].ResNumber, best_atoms_dna2[best_list_P2[best_j_max_measure]].ResNumber, i_max_measure_compl_str, j_max_measure_compl_str, is_reverse1, is_reverse2, best_S_max, dna_seq11, dna_num_seq11, dna_seq12, dna_num_seq12, dna_seq21, dna_num_seq21, dna_seq22, dna_num_seq22);
  fclose(max_score); 

  struct atom *atoms_dna_i1 = NULL;
  struct atom *atoms_dna_i2 = NULL;
  struct atom *atoms_dna_j1 = NULL;
  struct atom *atoms_dna_j2 = NULL;
  /* Change the system to i and j coordinates, write the alignment to file */

  ChangeSystem(atoms_prot1, n1, &atoms_prot_i1, best_atoms_dna1[best_list_P1[best_i_max_measure]], best_atoms_dna1[best_list_C11[best_i_max_measure+1]], best_atoms_dna1[best_list_OP11[best_i_max_measure]], best_atoms_dna1[best_list_OP21[best_i_max_measure]], 'E'); 
    // Note that names of chains will be changed to 'E' and 'F' by default! Modify if required.
  ChangeSystem(atoms_prot2, n2, &atoms_prot_j2, best_atoms_dna2[best_list_P2[best_j_max_measure]], best_atoms_dna2[best_list_C12[best_j_max_measure+1]], best_atoms_dna2[best_list_OP12[best_j_max_measure]], best_atoms_dna2[best_list_OP22[best_j_max_measure]], 'F');
  ChangeSystem(best_dna1_chain1, best_dna1_chain1_n, &atoms_dna_i1, best_atoms_dna1[best_list_P1[best_i_max_measure]], best_atoms_dna1[best_list_C11[best_i_max_measure+1]], best_atoms_dna1[best_list_OP11[best_i_max_measure]], best_atoms_dna1[best_list_OP21[best_i_max_measure]], 'A'); 
  ChangeSystem(best_dna1_chain2, best_dna1_chain2_n, &atoms_dna_i2, best_atoms_dna1[best_list_P1[best_i_max_measure]], best_atoms_dna1[best_list_C11[best_i_max_measure+1]], best_atoms_dna1[best_list_OP11[best_i_max_measure]], best_atoms_dna1[best_list_OP21[best_i_max_measure]], 'B'); 
  ChangeSystem(best_dna2_chain1, best_dna2_chain1_n, &atoms_dna_j1, best_atoms_dna2[best_list_P2[best_j_max_measure]], best_atoms_dna2[best_list_C12[best_j_max_measure+1]], best_atoms_dna2[best_list_OP12[best_j_max_measure]], best_atoms_dna2[best_list_OP22[best_j_max_measure]], 'C');
  ChangeSystem(best_dna2_chain2, best_dna2_chain2_n, &atoms_dna_j2, best_atoms_dna2[best_list_P2[best_j_max_measure]], best_atoms_dna2[best_list_C12[best_j_max_measure+1]], best_atoms_dna2[best_list_OP12[best_j_max_measure]], best_atoms_dna2[best_list_OP22[best_j_max_measure]], 'D');
    
  //puts("\nFix 'nan' in pdb with this data:");
  createPDB(outfile, outfile); 
    // pdb.c function
  writetoPDB(outfile, atoms_dna_i1, best_dna1_chain1_n);
  writetoPDB(outfile, atoms_dna_i2, best_dna1_chain2_n);
  writetoPDB(outfile, 
                atoms_prot_i1, n1); 
    // pdb.c function. Write protein atoms to outfile

  writetoPDB(outfile, 
                atoms_prot_j2, n2);
  writetoPDB(outfile, atoms_dna_j1, best_dna2_chain1_n);
  writetoPDB(outfile, atoms_dna_j2, best_dna2_chain2_n);
  endPDB(outfile); 
  
  return 0;
}