Esempio n. 1
0
void BandedAlign <Src1SymbolType, Src2SymbolType, DestSymbolType, ValueType, AveType, GapType>
::backtrace ()
{
#ifdef DEBUG_TRACE_MATRIX
    trace_.print (this->maxPos1_, this->maxPos2_);
#endif

    if (this->maxPos1_ == UINT_MAX) return;
    if (result_) return;
    this->result_ = new Alignment;
    unsigned pos1 = this->maxPos1_;
    unsigned pos2 = this->maxPos2_;
    unsigned batch_end = UINT_MAX;
    int prev_direction ;
    int direction = TRACE_STOP;

    while (pos1 != UINT_MAX && pos2 != UINT_MAX)
    {
        try
        {
            prev_direction = direction;
            direction  = this->trace_.get (pos1, pos2);
            switch (direction)
            {
                case ALONG_DIAG:
                    if (prev_direction != ALONG_DIAG) batch_end = pos1;
                    pos1 --;
                    pos2 --;
                    break;
                case ALONG_FIRST:
                    if (batch_end != UINT_MAX && prev_direction == ALONG_DIAG)
                        this->result_->push_front (Batch (pos1 + 1, pos2 + 1, batch_end - pos1));
                    pos1 --;
                    break;
                case ALONG_SECOND:
                    if (batch_end != UINT_MAX && prev_direction == ALONG_DIAG)
                        this->result_->push_front (Batch (pos1 + 1, pos2 + 1, batch_end - pos1));
                    pos2 --;
                    break;
                default:
                    if (batch_end != UINT_MAX && prev_direction == ALONG_DIAG)
                        this->result_->push_front (Batch (pos1 + 1, pos2 + 1, batch_end - pos1));
                    pos1 = UINT_MAX; // terminate
            }
        }
        catch (OutOfBand&)
        {
            break;
        }
    }
    if (batch_end != UINT_MAX && direction == ALONG_DIAG)
        this->result_->push_front (Batch (pos1 + 1, pos2 + 1, batch_end - pos1));
}
Esempio n. 2
0
bool Message_Service::Show_Question (char *format, ...) 
{
	if (Batch ()) {
		Show_Error ("Show_Question in 'Batch' mode (-B)");
		return (false);
	}
	if (format == NULL) {
		Show_Error ("Show_Question is NULL");
	}
	char text [STRING_BUFFER];

	va_list  args;
 	va_start (args, format);
	str_args (text, sizeof (text), format, args);
	va_end (args);

	printf ("\n\t%s (Y/N): ", text);
	fflush (stdout);

	if (fgets (text, sizeof (text), stdin) != NULL) {
		return (*text == 'Y' || *text == 'y');
	} else {
		return (false);
	}
}
Esempio n. 3
0
void Message_Service::Pause_Process (void) 
{
    if (!Quiet () && !No_Pause () && !Batch ()) {
		char pause [10];

		printf ("\n\n\tPress Enter to Continue");
		fflush (stdout);

		fgets (pause, sizeof (pause), stdin);
	}
}
Esempio n. 4
0
void Message_Service::End_Progress (char *text) 
{
    if (!Quiet ()) {
		if (Batch ()) {
			printf ("\n\tRecord: %s\n", text); 
			fflush (stdout);
		} else {
			printf (" %-16.16s\n", text);
		}
	}
}
Esempio n. 5
0
void Message_Service::End_Progress (void) 
{
    if (!Quiet ()) {
		if (Batch ()) {
			printf ("\n\tRecord: %d\n", progress); 
			fflush (stdout);
		} else {
			printf (" %d\n", progress);
		}
	}
}
Esempio n. 6
0
int     CompMain( char *parm ) {
//==============================

    int         num;

    num = 0;
    for(;;) {
        parm = Batch( parm, num );
        if( parm == NULL ) break;
        Compile( parm );
        ++num;
    }
    return( RetCode );
}
Esempio n. 7
0
void Message_Service::Show_Progress (char *text) 
{
	progress++;

	if (!Quiet ()) {
		if ((progress % progress_step) == 1) {
			if (Batch ()) {
				printf ("\n\tRecord: %s", text); 
				fflush (stdout);
			} else {
				printf (" %-16.16s\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b", text);
			}
		}
	}
}
Esempio n. 8
0
INT cmd_call (LPTSTR param)
{
    TCHAR line[CMDLINE_LENGTH + 1];
    TCHAR *first;
    BOOL bInQuote = FALSE;

    TRACE ("cmd_call: (\'%s\')\n", debugstr_aw(param));
    if (!_tcsncmp (param, _T("/?"), 2))
    {
        ConOutResPaging(TRUE,STRING_CALL_HELP);
        return 0;
    }

    /* Do a second round of %-variable substitutions */
    if (!SubstituteVars(param, line, _T('%')))
        return nErrorLevel = 1;

    /* Find start and end of first word */
    first = line;
    while (_istspace(*first))
        first++;

    for (param = first; *param; param++)
    {
        if (!bInQuote && (_istspace(*param) || _tcschr(_T(",;="), *param)))
            break;
        bInQuote ^= (*param == _T('"'));
    }

    /* Separate first word from rest of line */
    memmove(param + 1, param, (_tcslen(param) + 1) * sizeof(TCHAR));
    *param++ = _T('\0');

    if (*first == _T(':') && (bc))
    {
        /* CALL :label - call a subroutine of the current batch file */
        while (*param == _T(' '))
            param++;
        nErrorLevel = Batch(bc->BatchFilePath, first, param, NULL);
        return nErrorLevel;
    }

    nErrorLevel = DoCommand(first, param, NULL);
    return nErrorLevel;
}
Esempio n. 9
0
void Message_Service::Show_Progress (int value) 
{
	if (value < 1) {
		value = ++progress;
	} else {
		progress = value;
	}
	if (!Quiet ()) {
		if ((value % progress_step) == 0) {
			if (Batch ()) {
				printf ("\n\tRecord: %d", value); 
				fflush (stdout);
			} else {
				printf (" %-10d\b\b\b\b\b\b\b\b\b\b\b", value);
			}
		}
	}
}
Esempio n. 10
0
void Shell(COMMAND commands[],char *help[])
{
	char cmdline[STRING],argv[MAXCMD],argp[MAXCMD];
	
	int i,opcja,n=0,j,ok,len,count=0,itmp;
	
	while(commands[n].command!=NULL) n++;
	
	for( ; ; )
	{					/* Interactive mode */
		fprintf(stdout,"[%d]MP> ",count); fflush(stdout);
		argv[0]=argp[0]=0; cmdline[0]=0;
		
		if(!fgets(cmdline,sizeof(cmdline)-1,stdin))
		{
			fprintf(stderr,"Read error ! [%s]\n",cmdline);
			return;
		}
		
		i=0;
		while(cmdline[i] && isspace(cmdline[i])) i++;
		(void)sscanf(cmdline+i,"%s",argv);
		
		len=strlen(argv);
		if(len==0) continue;
		i+=len;
		while(cmdline[i] && isspace(cmdline[i])) i++;
		(void)sscanf(cmdline+i,"%[^\n]\n",argp);
		
		AppendHistory(count,argv,argp); count++;
		
		if(strcmp(argv,"history")==0)
		{
			if(strlen(argp)>0)
			{
				itmp=atoi(argp);
				ok=0;
				for(i=0 ; i<CountHist ; i++)
				{
					if(HistTable[i]->count==itmp)
					{
						ok=1;
						strcpy(argv,HistTable[i]->napis);
						strcpy(argp,HistTable[i]->opt);
						fprintf(stdout,"[%d] (HISTORY [%d]) MP> %s %s\n",
							count-1,itmp,argv,argp);
						break;
					}
				}
					
				if(!ok)
				{
					fprintf(stderr,"No such number\n");
					continue;
				}
			}
			else
			{
				fprintf(stdout,"\t\t<<< HISTORY >>>\n");
				
				for(i=0 ; i<CountHist ; i++)
				{
					fprintf(stdout,"[%d] %s %s\n",HistTable[i]->count,
						HistTable[i]->napis,
						HistTable[i]->opt);
				
					if(((i+1)%20)==0) 
						pause();
				}
				
				fprintf(stdout,"\n");
				continue;
			}
		}
		
		if(strcmp(argv,"man")==0)
		{
			fprintf(stdout,"\n\t\t<<< BUILT-IN COMMANDS >>\n"
				"exit        \t\t- leave shell\n"
				"ls          \t\t- current directory listing\n"
				"history [nr]\t\t- display entered commands or execute [nr] if given\n"
				"batch       \t\t- run commands from file\n"
				"!comd       \t\t- run a shell command comd\n"
				"man         \t\t- display all available help\n"
				"sys comd    \t\t- run shell command comd in script\n");
			
			fprintf(stdout,"<<< NEXT - ENTER q - QUIT >>> ");
		
			if(getchar()!='q')
			{
				if(help!=NULL)
					PrintAllHelp(commands,help,n); 
			}
			else 
				(void)getchar();
			
			continue;
		}
		
		if(strcmp(argv,"help")==0 || strcmp(argv,"?")==0 || strcmp(argv,"h")==0)
		{
			ok=0;
			
			if(strlen(argp)>0)
			{
				if(strcmp(argp,"help")==0 || strcmp(argp,"?")==0)
				{
					ok=1;
					fprintf(stderr,"help [arg] or ? [arg] -- info about the arg command\n");
				} 
				else if(strcmp(argp,"batch")==0)
				{
					ok=1;
					fprintf(stderr,"batch file -- run script file\n");
				}	
				else if(strcmp(argp,"sys")==0)
				{
					ok=1;
					fprintf(stderr,"sys comd -- run shell command comd (from a script only)\n");
				}
				else if(strcmp(argp,"ls")==0)
				{
					ok=1;
					fprintf(stderr,"ls adir -- listing of directory adir, regexp allowed\n"); 
				}
				else if(strcmp(argp,"history")==0)
				{
					ok=1;
					fprintf(stderr,"history [nr] -- list entered commands\n"	
						"\t\t or if [nr] given - run command No [nr]\n");
				}
				else
					for(j=0 ; j<n ; j++)
					if(strcmp(commands[j].command,argp)==0)
					{
						ok=1;
						fprintf(stdout,"%-10s - ",commands[j].command);
						if(help!=NULL)
							fprintf(stdout,"%s ",help[j]);
						fprintf(stdout,"\n");
						break;
					}
					if(!ok) 
						fprintf(stdout,"Unknown command : %s\n",argp);
			}
			else
			{ fprintf(stdout,"%s\n",firsthelp); }
			continue;
		}
		
		if(strcmp(argv,"exit")==0) {
			DeleteHistory();
			if(prn==1)
				fprintf(stdout,"<<< LEAVING MP SHELL >>>\n");
			Quit("");
			break;
		}
		
		if(strcmp(argv,"ls")==0)
		{
			ls(argp);
			continue;
		}
		
		if(strcmp(argv,"batch")==0)
		{
			char *newargv[MAXCMD];
			int i,argc;
			
			for(i=0 ; i<MAXCMD ; i++)
				newargv[i]=NULL;
			
			StrToArgv(argp,newargv,&argc);
			if(Batch(commands,newargv[0],newargv)==-1)
				fprintf(stderr,"Missing file %s !\n",argp);
			FreeArgv(newargv,argc);
			continue;
		}
		
		if(strcmp(argv,"!")==0)
		{
			if(system(argp)==-1)
				fprintf(stderr,"Error executing system command !\n");
			continue;
		}
		
		if(argv[0]=='!')
		{
			argv[0]=' ';
			(void)strcat(argv," "); (void)strcat(argv,argp);
			if(system(argv)==-1)
				fprintf(stderr,"Error executing system command !\n");
			continue;
		}
		
		opcja=-1;				/* Opcje zewnetrzne */
		
		for(i=0 ; i<n ; i++)
			if(strcmp(commands[i].command,argv)==0)
			{
				opcja=i;
				(*commands[i].func)(argp);
				break;
			}
			
			if(opcja==-1)
			{
				char name[STRING],*newargv[MAXCMD],buffor[STRING];
				int argc,i;
				
				for(i=0 ; i<MAXCMD ; i++)
					newargv[i]=NULL;
				
				sprintf(buffor,"%s %s",argv,argp);
				StrToArgv(buffor,newargv,&argc);
				
				if(Batch(commands,newargv[0],newargv)==-1)
				{	 /* Polecenia w biezacym katologu */
					int index=0,ok=0;
					
					for( ; ; index++)
					{
						if(makePathName(name,index)==NULL)
							break;
						
						strcat(name,newargv[0]);
						if(Batch(commands,name,newargv)!=-1) {
							ok=1;
							break;
						}
					}

					if(ok==0) 
						fprintf(stderr,"MP: Unknown command %s or bad script path %s\n",
						argv,BatchPath);
				}
				
				FreeArgv(newargv,argc);
			}    
      }
}
Esempio n. 11
0
int Batch(COMMAND commands[],char *filename,char *argv[])
{
	FILE *plik;
	char *cmdline,*comand,*opt;
	int i,k=0,ok,n=0,count=0;
	
	if((cmdline=(char *)malloc(MAXCMD*sizeof(char)))==NULL)
		return -1;
	
	if((comand=(char *)malloc(MAXCMD*sizeof(char)))==NULL)
	{
		free((void *)cmdline);
		return -1;
	}
	
	if((opt=(char *)malloc(MAXCMD*sizeof(char)))==NULL)
	{
		free((void *)cmdline);
		free((void *)comand);

		return -1;
	}
	
	if((plik=fopen(filename,"rt"))==NULL)
		return -1;
	
	if(prn==1)
		fprintf(stdout,"\t\t\t<<< START OF SCRIPT %s >>>\n",filename);
	
	while(commands[n].command!=NULL) 
		n++; /* Liczba dostepnych opcji */

	while(!feof(plik))
    {
		comand[0]='\0'; opt[0]='\0';
		fscanf(plik,"%[^\n]\n",cmdline);
		ok=i=0;
		
		while(cmdline[i] && isspace(cmdline[i]))
			i++;
		
		if(cmdline[i]=='#')				/* Komentarz */
			continue;
		
		sscanf(cmdline+i,"%s",comand);
		
		i+=strlen(comand);
		
		while(cmdline[i] && isspace(cmdline[i]))
			i++;

		sscanf(cmdline+i,"%[^\n]\n",opt);
		
		if(strcmp(comand,"end")==0) 			/* Zakonczenie skryptu */
		{
			if(prn==1)
				fprintf(stdout,"[%d] BATCH(%s)>end\n",count,filename);
			break;
		}
		
		if(strcmp(comand,"batch")==0)
		{
			if(strcmp(opt,filename)!=0)			/* Zapobiega rekurencji (prymitywnie) */
			{
				char **newargv,*buffor;
				int argc,i;
				
				if((newargv=(char **)malloc(MAXCMD*sizeof(char *)))==NULL)
					continue;
				
				if((buffor=(char *)malloc(MAXCMD*sizeof(char)))==NULL) {
					free((void *)newargv);
					continue;
				}
				
				if(prn==1)
					fprintf(stdout,"[%d] BATCH(%s)>batch %s\n",count,filename,opt);
				
				for(i=0 ; i<MAXCMD ; i++)
					newargv[i]=NULL;
				
				Replace(argv,opt,buffor);                     /* Rozwniecie parametrow */
				StrToArgv(buffor,newargv,&argc);
				if(Batch(commands,newargv[0],newargv)==-1)
					fprintf(stderr,"File %s is missing !\n",opt);
				FreeArgv(newargv,argc); free((void *)buffor); free((void *)newargv);
				count++;
				continue;
			}
		}
		
		if(strcmp(comand,"sys")==0)
		{
			if(prn==1)
				fprintf(stdout,"[%d] BATCH(%s)>!%s\n",count,filename,opt);
			if(system(opt)==-1)
				fprintf(stderr,"Shell command not executed properly !\n");
			count++;
			continue;
		}
		
		for(i=0 ; i<n ; i++)
		{
			/* Nieznane komedy sa ignorowane */
			if(strcmp(commands[i].command,comand)==0)
			{
				char buffor[STRING];
				
				ok=1;
				Replace(argv,opt,buffor);                   /* Rozwiniecie parametrow */
				if(prn==1)
					fprintf(stdout,"[%d] BATCH(%s)> %s %s\n",count,filename,comand,buffor);
				(*commands[i].func)(buffor);
				count++;
				break;
			}
		}
		
		if(ok!=1) 
		{
			char name[STRING],*newargv[MAXCMD],buffor[STRING],buff[STRING];
			int i,argc;
			
			for(i=0 ; i<MAXCMD ; i++)
				newargv[i]=NULL;
			
			Replace(argv,opt,buff);                       /* Rozwiniecie parametrow */
			
			sprintf(buffor,"%s %s",comand,buff);
			StrToArgv(buffor,newargv,&argc);
			
			if(Batch(commands,newargv[0],newargv)==-1)
			{	
				/* W biezacym katalogu */
				int index=0,ok=0;
				
				for( ; ; index++)
				{
					if(makePathName(name,index)==NULL)
						break;
					
					strcat(name,newargv[0]);

					if(Batch(commands,name,newargv)!=-1)
					{
						ok=1;
						break;
					}
					
					if(ok==0)
						k++;
				}
			}
			
			FreeArgv(newargv,argc);
		}
    }
    
	fclose(plik);
	
	free((void *)cmdline); 
	free((void *)comand); 
	free((void *)opt);
	
	if(prn==1)
		fprintf(stdout,"\n%4d ignored command(s)\n\t\t\t<<< END OF SCRIPT %s >>>\n",
		k,filename);
	
	return 0;  
}
Esempio n. 12
0
int main(int argc,char *argv[])
{
	char filename[STRING],*path;
	int opcja,TimeSrand=OFF,i,makebatch=OFF,OldPrn;
	
#ifdef MULTITHREAD
	/* UWAGA !
	Blokowanie sygnalu SIGCLD zapobiega powstawaniu procesow ZOMBI
	w przypadku wczesniejszego zakonczenia procesu potomnego
	konstrukcja nieprzenosna dziala pod Linux'em
	*/
	
	if(signal(SIGCLD,SIG_IGN)==SIG_ERR)
	{
		fprintf(stderr,"Problems trapping signal SIGCLD !\n");
		return 1;
	}
#endif
	
	sortAlphabetic();            /* Sortowanie polecen w kolejnosci alfabetycznej */
	OldDimRoz=32;                /* Liczba atomow do rekonstrukcji */
	DimBase=512;                 /* Wymiar sygnalu */
	epsylon=95.0F;               /* Dokladniosc rekonstrukcji */
	prn=ON;                      /* Drukowanie informacji */
	SamplingRate=1.0;            /* Czestotliwosc probkowania */
	ConvRate=1.0;                /* Wspolczynnik konwersji */
	RandomType=NOFUNCRND;        /* Sposob generacji atomow */
	DiadicStructure=OFF;         /* Diadyczna struktura slownika */
	FastMode=ON;                 /* Szybka generacja atomow (wymaga duzo pamieci) */
	VeryFastMode=ON;             /* Bardzo szybka generacja iloczynow skalarnych */
	DictionSize=70000;           /* Domyslny rozmiar slownika */
	Heuristic=OFF;               /* Wspomaganie heurystyczne */
	StartDictionSize=25000;      /* Rozmiar slownika do probkowania */
	MallatDiction=OFF;           /* Slownik Mallata */
	OverSampling=2;              /* Przeprobkowanie slownika */
	
	while((opcja=Getopt(argc,argv,"R:P:E:M:HhB:O:F:C:i:x:dsfN:TS:v:JD:X"))!=EOF)
	{
		switch(opcja)
		{
        case 'X':
			debug=1;
			break;
        case 'S':
			OverSampling=atoi(optarg);
        case 'T':
			MallatDiction=ON;
			DiadicStructure=ON;
			break;
        case 'N':
			Heuristic=ON;     /* Pozostale parametry domyslne w mp.c */
			sscanf(optarg,"%d,%d,%d,%d",&StartDictionSize,&ROctave,
				&RFreqency,&RPosition);
			break;
        case 'v':
			if(strcmp(optarg,"+")==0)
                FastMode=VeryFastMode=ON;
			else if(strcmp(optarg,"-")==0)
                VeryFastMode=OFF;
			else
			{
				fprintf(stderr,"Available options -v[-|+] !\n");
				return 1;
			}
			break;
        case 'P':
			if(strcmp(optarg,"+")==0)
                prn=ON;
			else if(strcmp(optarg,"-")==0)
                prn=OFF;
			else
			{
				fprintf(stderr,"Available options -P[-|+] !\n");
				return 1;
			}
			break;
        case 'f':
			FastMode=ON;
			break;
        case 's':
			FastMode=OFF;
			break;
        case 'd':
			DiadicStructure=ON;
			break;
        case 'R':
			DictionSize=atoi(optarg);
			break;
        case 'x':
			(void)strcpy((char *)FunctionCode,optarg);
			RandomType=FUNCRND;
			MallatDiction=OFF;
			break;
        case 'i':
			if(strcmp(optarg,"+")==0)
				TimeSrand=ON;
			else if(strcmp(optarg,"-")==0)
				TimeSrand=OFF;
			else
			{
				fprintf(stderr,"Available options -i[-|+] !\n");
				return 1;
			}
			break;
        case 'O':
			DimBase=atoi(optarg);
			break;
        case 'F':
			SamplingRate=atof(optarg);
			break;
        case 'C':
			ConvRate=atof(optarg);
			break;
        case 'B':
			(void)strcpy(filename,optarg);
			makebatch=ON;
			break;
        case 'M':
			OldDimRoz=atoi(optarg);
			break;
        case 'E':
			epsylon=atof(optarg);
			break;
        case 'J':  /* Wylaczenie buforowania */
			javaMode=ON;
			setvbuf(stdout,(char *)NULL,_IOLBF,0);
			setvbuf(stderr,(char *)NULL,_IOLBF,0);
			break;
        case 'D':
			AdaptiveConst=(float)atof(optarg);
			break;
        case 'H':
        case 'h':
        default:
			PrintHelp();
			return 0;
		}
	}
	
	SetTuneScale();

	OldPrn=prn;                           /* Blokowanie drukowanie inforamcji */
	prn=OFF;
	
	if(MallatDiction==ON)
		DictionSize=MakeMallatDictionary(DimBase,OverSampling,OFF);
	
	if((path=getenv("MP_PATH"))==NULL)       /* Sciezka dla batch'y  */
	{
		char path2[10]=".";

		if(prn==ON)
			/*PJD        fprintf(stderr,"\nWARNING: environment variable MP_PATH not set !\n");*/
			fprintf(stderr,"\nPath set to \".\" (HMPP env. var. not set)\n");
		SetBatchPath(path2);
	}
	else 
		SetBatchPath(path);
	
	if(Heuristic==ON)                     /* Poprawnosc konfiguracji */
	{
		if(StartDictionSize>=DictionSize)
			Heuristic=OFF;
		else if(FastMode==OFF)
			Heuristic=OFF;
		else if(DiadicStructure==OFF)
			Heuristic=OFF;
	}
	
	if(Heuristic==OFF)
		StartDictionSize=DictionSize;
	
	if(prn==ON && RandomType==FUNCRND)
		fprintf(stdout,"VAL= %s\n",FunctionCode);
	
	if(InicRandom(TimeSrand)==-1)
	{
		fprintf(stderr,"Problem initializing stochastic dictionary:(\n");
		return 1;
	}
	
	if((sygnal=MakeVector(3*DimBase))==NULL ||
		(OrgSygnal=MakeVector(DimBase))==NULL)
    {
		fprintf(stderr,"Memory allocation error (main:(\n");
		return 1;
    }
	
	for(i=0 ; i<3*DimBase ; i++)
		sygnal[i]=0.0F;
	
	for(i=0 ; i<DimBase ; i++)
		OrgSygnal[i]=0.0F;
	
	AllocStatus=ON;
	
	if(Batch(commands,"mp.cfg",NULL)==-1)      /* Plik konfiguracyjny */
	{
		char name[STRING];
		strcmp(name,BatchPath); strcat(name,"mp.cfg");
		if(Batch(commands,name,NULL)==-1)
			if(prn==ON)
				fprintf(stderr,"\nNo config file (mp.cfg)\n");
	}
	
	prn=OldPrn;                          /* mozna ustawic prn */

	if(makebatch==ON)
	{
		if(Batch(commands,filename,NULL)==-1)      /* Wykonanie skryptu */
		{
			fprintf(stderr,"cannot find script file %s\n",filename);
			return 1;
		}
	}
		
	if(prn==ON)
	{
		SourceVersion(NULL);
		SetMPP("");
	}
	
	Shell(commands,help);        /* Rozpoczecie trybu iteracyjnego */
	
	CloseRand2D();
	
	free((void *)sygnal);
	free((void *)OrgSygnal);

	CloseTune();
	return 0;
}
Esempio n. 13
0
    Batcher::Batcher(const std::vector<Primitive*>& primitives) { 

        FullscreenPrimitive fullscreen;

        const unsigned int numberOfPrimitives = primitives.size();
        mBatches.reserve(numberOfPrimitives);

        std::vector<Batch> batchCandidates;
        batchCandidates.reserve(numberOfPrimitives);

        for (std::vector<Primitive*>::const_iterator itr = primitives.begin(); itr != primitives.end(); ++itr) {

            // primitive completely outside viewport, no need to process it any further
            if (!Algo::intersectXY(*itr, &fullscreen))
                continue;

            // fullscreen is completely part of the primitive's bounding box,
            // no other primitive can be part of the same batch
            if (Algo::containsXY(&fullscreen, *itr)) {
                mBatches.push_back(Batch());
                Batch& batch = mBatches.back();
                batch.push_back(*itr);
            }
            else
            {
                std::vector<Batch>::iterator batchItr = batchCandidates.begin();
                std::vector<Batch>::iterator batchEnd = batchCandidates.end();

                for ( ; batchItr != batchEnd; ++batchItr) {

                    Batch & batch = *batchItr;
                    Batch::const_iterator batchPrimitives = batch.begin();
                    Batch::const_iterator batchPrimitivesEnd = batch.end();

                    // if the primitive does not intersect any of the primitives in
                    // the current batch, we can add the primitive to that batch
                    for ( ; batchPrimitives != batchPrimitivesEnd; ++batchPrimitives) {
                        if (Algo::intersectXY(*itr, *batchPrimitives)) {
                            break;
                        }
                    }
                    if (batchPrimitives == batchPrimitivesEnd) {
                        batch.push_back(*itr);
                        break;
                    }
                }

                // primitive could not added to any batch -> create a new batch
                if (batchItr == batchEnd) {
                    batchCandidates.push_back(Batch());
                    Batch& batch = batchCandidates.back();
                    batch.push_back(*itr);
                }
            }
        }

        // Could do here the following. But since since batchCandidates is not needed anymore,
        // we can use the std::vector swap trick to avoid calling of the copy constructor.
        // std::copy(batchCandidates.begin(), batchCandidates.end(), std::back_inserter(mBatches));

        std::vector<Batch>::iterator batchItr = batchCandidates.begin();
        std::vector<Batch>::iterator batchEnd = batchCandidates.end();

        for ( ; batchItr != batchEnd; ++batchItr) {
            mBatches.push_back(Batch());
            Batch& batch = mBatches.back();
            batch.swap(*batchItr);
        }
    }