void printMatrixHost( T * host, int n, int m, const char * msg){
  std::cout << msg;
  int maxn,maxm;
  if (false){
    maxm=mymin(1000,m);
    maxn=mymin(1000,n);
  } else {
    int sym = mymin(m,n);
    maxm=mymin(1000,sym);
    maxn=mymin(1000,sym);
  }
  if ( m<=0 || n<=0){
    return;
  }
  std::cout << "\nA=[";
  for (int j=0; j < maxm;j++){
    std::cout <<"[";
    std::cout << std::setw(12)<< host[n*j];
    for (int i =1; i<maxn;i++){
      std::cout << " , " <<std::setw(12) << std::setprecision(4)<< host[n*j+i];
      //printf(",\t%20.15e",host[j]);
    }
    //std::cerr << j <<" (" <<n<<","<<m<<") " << std::endl;
    if (j==n-1){
      std::cout << "]";
    } else {
      std::cout << "]\n   ";
    }
  }
  std::cout << "];\neig(A)\n";
}
Пример #2
0
static int min_index(const RFunction::coord_type& p) // index with |p[i]| = min p.dim() = 3
{
  double p1 =fabs(p[1]), p2 = fabs(p[2]), p3 = fabs(p[3]);
  if(p1 <= mymin(p2,p3))
    return 1;
  else if (p2 <= mymin(p1,p3))
    return 2;
  else 
    return 3;
}
static int dump_entry (FILE * f, struct ConfigVTable * h, SectionHandle s, 
      unsigned int indent, const SectionEntry * entry)
{
   int ret = 1;
   switch (entry->type)
   {
      case SE_SECTION:
         {
            SectionHandle newsec;

            fprintf (f, "%s { \n", entry->name);

            ret = mymin(ret, cf_openSection (h, s, entry->name, &newsec));
            if (ret >= 0) 
            {
               ret = mymin (dump_section (f, h, newsec, indent + 2), ret);
               show_indent (f, indent);
               fprintf (f, "}\n");
               ret = mymin (ret, cf_closeSection (h, newsec));
            }
            break;
         }
      case SE_KEY:
         {
            char buf[255];
            ret = mymin (ret, cf_getKey (h, s, entry->name, &buf[0], sizeof(buf)));
            if (ret >= 0)
            {
                fprintf (f, "%s = \"%s\";\n", entry->name, buf); 
            }
            break;
         }
      case SE_MULTIKEY:
         {
            char ** ptrs;
            size_t size;
            size_t j;
            ret = mymin (ret, cf_getMultiKey (h, s, entry->name, &ptrs, &size));
            if (ret >= 0)
            {
               fprintf (f,"%s = (", entry->name);
               for (j=0; j<size; ++j)
               {
                  fprintf (f,"\"%s\" ", (ptrs[j] ? ptrs[j] : ""));
                  free (ptrs[j]);
                  if ((j+1) < size)
                     fprintf (f,", ");
               }
               fprintf (f, ");\n");
               free (ptrs);
            }
         }
   }
   return ret;
}
Пример #4
0
void NoiseBandSynthesizer::SynthesizeSample(std::vector<double> *instantParams)
{
    if(firstRun)
    {
        phase=0.0;
        phaseAdd=0.0;
        lastfreq=(*instantParams)[eCenterFrequency];
        lastamp=(*instantParams)[eAmplitude];
        lastbw=(*instantParams)[eBandwidth];
        targetfreq=lastfreq;
        instfreq=lastfreq;
        samplesTillNextTarget =-1;
        firstRun=false;
    }
    float lowFreq,highFreq,centerFreq,maxFreq;
    float freq,amp,bw;

    maxFreq = 44100.0/2.0;

    freq=(*instantParams)[eCenterFrequency];
    amp=(*instantParams)[eAmplitude];
    bw=mymin(1.0,mymax(0.0,(*instantParams)[eBandwidth]));

    lowFreq = freq*(1.0-bw);
    highFreq = mymin(maxFreq,freq*(1.0+bw) );
    centerFreq = (lowFreq+highFreq)/2.0;


    //see if we need a new target
    if(samplesTillNextTarget <0)
    {
        targetfreq = randfloat(highFreq-lowFreq)+lowFreq;  //assumes bw <1.0
        samplesTillNextTarget = randint(44100.0/mymax(2.0,centerFreq))+1.0;
    } else
    {
        samplesTillNextTarget = mymin(44100.0/mymax(2.0,centerFreq),samplesTillNextTarget);
        samplesTillNextTarget--;
    }

    instfreq = instfreq + (targetfreq-instfreq)/mymax(1.0,samplesTillNextTarget);

    phaseAdd = instfreq*2.0*3.141592/44100.0;
    //phaseAdd += phaseAdd* (randfloat(bw*2)-bw);

    phase += phaseAdd;
    while(phase>2.0*3.141592)
        phase-=2.0*3.141592;

    buffer->SetFrame(currentSample++,amp*sin(phase)*SHORTLIMITF);

    lastfreq=freq;
    lastamp=amp;
    lastbw=bw;
}
Пример #5
0
void Interpolation::Truncate(double startTime, double duration, std::vector<TreeNode*> *activeNodes,  std::vector<ParameterList*> *parameters, int layerNum,  int topLayer, int numControlledLayers)
{
   
   mStartTime = startTime;
	mDuration = duration;
   
   //make sure we fit within all parameter boundries for all associated paramter lists.
   double startValue = (*parameters)[layerNum]->GetValue(mParam);
   //- we don't know where it will be at the end of the leaf.  
   //now check to see where the parameter will be at upon the end of the leaf.  
   //we do this by asking each of the active nodes what their value will be at the end of THIS leaf
   //and multiply them against the start value
   
   double topValue = startValue;
   double bottomValue = startValue;
   
   for(int i =0;i<numControlledLayers;i++)
   {
      topValue = mymax(topValue, (*parameters)[topLayer+i]->GetValue(mParam));
      bottomValue = mymin(bottomValue, (*parameters)[topLayer+i]->GetValue(mParam));
   }
   
   for(int i=0;i<activeNodes->size();i++)
   {
      for(int j=0;j<((*activeNodes)[i])->GetNumInterpolations();j++)
      {
         
         if(((*activeNodes)[i])->GetInterpolation(j)->GetParameter() == mParam)
         {
            //we use this node's start time, and the parent node's end time (since we can't push them to overstep their boundries.)
            topValue = mymax(topValue,topValue*((*activeNodes)[i])->GetInterpolation(j)->MaxValueInTimeRange(mStartTime,((*activeNodes)[i])->GetInterpolation(j)->GetStartTime()+((*activeNodes)[i])->GetInterpolation(j)->GetDuration()));
            bottomValue = mymin(bottomValue,bottomValue*((*activeNodes)[i])->GetInterpolation(j)->MinValueInTimeRange(mStartTime,((*activeNodes)[i])->GetInterpolation(j)->GetStartTime()+((*activeNodes)[i])->GetInterpolation(j)->GetDuration()));
         }
      }
   }
   
   assert(topValue >= bottomValue);
   while(topValue*mEndCoef> (*parameters)[layerNum]->GetMaxValue(mParam))
      mEndCoef= randfloat(mEndCoef-1.0)+1.0;
   
   while(bottomValue*mEndCoef<(*parameters)[layerNum]->GetMinValue(mParam))
      mEndCoef = randfloat(1.0-mEndCoef)+mEndCoef;

   if((topValue*mEndCoef>(*parameters)[layerNum]->GetMaxValue(mParam)) ||
         (bottomValue*mEndCoef<(*parameters)[layerNum]->GetMinValue(mParam)) )
         mEndCoef=1.0;
      
}
Пример #6
0
bool LineSegment::containPointClose(Point pt)
{
	double minx = mymin(start.x, end.x);
	double maxx = mymax(start.x, end.x);
	double miny = mymin(start.y, end.y);
	double maxy = mymax(start.y, end.y);

	if (containPointOpen(pt) && 
		(pt.x > minx || DOUBLE_EQUAL(pt.x, minx)) && 
		(pt.x < maxx || DOUBLE_EQUAL(pt.x, maxx)) &&
		(pt.y > miny || DOUBLE_EQUAL(pt.y, miny)) && 
		(pt.y < maxy || DOUBLE_EQUAL(pt.y, maxy))) 
		return true;
	else
		return false;
}
Пример #7
0
int main()
{
	int i,j,len1,len2;
	while(~scanf("%s%s",s1,s2))
	{
		len1=strlen(s1);len2=strlen(s2);
	//	memset(dp,-1,sizeof(dp));
		for (i=0;i<=len1;++i) dp[i][0]=i;
		for (i=0;i<=len2;++i) dp[0][i]=i;
		for (i=1;i<=len1;++i)
		{
			for (j=1;j<=len2;++j)
			{
				if (s1[i-1]==s2[j-1])
				{
					dp[i][j]=dp[i-1][j-1];
				}else
				{
					dp[i][j]=mymin(dp[i-1][j-1],dp[i-1][j],dp[i][j-1])+1;
				}
			}
		}
		printf("%d\n",dp[len1][len2]);
	}
	
}
Пример #8
0
uint gamebuy(uint i, uint a)
 /* Try to buy ammount a  of good i  Return ammount bought */
 /* Cannot buy more than is availble, can afford, or will fit in hold */
{   uint t;
    if(cash<0) t=0;
    else
    {	t=mymin(localmarket.quantity[i],a);
    	if ((commodities[i].units)==tonnes) {t = mymin(holdspace,t);}
    	t = mymin(t, (uint)floor((double)cash/(localmarket.price[i])));
    }
		shipshold[i]+=t;
    localmarket.quantity[i]-=t;
    cash-=t*(localmarket.price[i]);
    if ((commodities[i].units)==tonnes) {holdspace-=t;}
		return t;
}
Пример #9
0
void CSubFile::Read(Byte * buffer, UInt uiStart, UInt uiCount) const
{
	// We start with no data yet
	UInt uiHaveRead = 0;
	// Iterate through all our blocks
	std::list<BlockInfo>::const_iterator it;
	for (it = m_Blocks.begin(); it != m_Blocks.end(); ++it)
	{
		// If the end of the block is earlier than start of data we want to read
		UInt uiBlockStart = it->m_uiBlockStart;
		UInt uiBlockLen = it->m_uiBlockLen;
		if ((uiBlockStart + uiBlockLen) > (uiStart + uiHaveRead))
		{
			// Then we should read some data
			// It's not more than amount left to read
			// And not more amount left from reading position to end of block
			UInt uiToRead = mymin(uiCount - uiHaveRead, it->m_uiBlockStart + it->m_uiBlockLen - (uiStart + uiHaveRead));
			// We read to the current position in buffer
			// Starting from current reading position relative to start of file
			// The amount calculated earlier
			it->m_pBlock->Read(buffer + uiHaveRead, uiStart + uiHaveRead - it->m_uiBlockStart, uiToRead);
			// And advance our reading position
			uiHaveRead += uiToRead;
			// Check if reading is complete
			if (uiHaveRead == uiCount)
				break;
		}
	}
	// Check if we've read all
	Check(uiHaveRead == uiCount);
}
Пример #10
0
	/// Returns the time in us since the last call to reset or since 
	/// the Clock was created.
unsigned long int btClock::getTimeMicroseconds()
{
#ifdef BT_USE_WINDOWS_TIMERS
		LARGE_INTEGER currentTime;
		QueryPerformanceCounter(&currentTime);
		LONGLONG elapsedTime = currentTime.QuadPart - 
			m_data->mStartTime.QuadPart;

		// Compute the number of millisecond ticks elapsed.
		unsigned long msecTicks = (unsigned long)(1000 * elapsedTime / 
			m_data->mClockFrequency.QuadPart);

		// Check for unexpected leaps in the Win32 performance counter.  
		// (This is caused by unexpected data across the PCI to ISA 
		// bridge, aka south bridge.  See Microsoft KB274323.)
		unsigned long elapsedTicks = GetTickCount() - m_data->mStartTick;
		signed long msecOff = (signed long)(msecTicks - elapsedTicks);
		if (msecOff < -100 || msecOff > 100)
		{
			// Adjust the starting time forwards.
			LONGLONG msecAdjustment = mymin(msecOff * 
				m_data->mClockFrequency.QuadPart / 1000, elapsedTime - 
				m_data->mPrevElapsedTime);
			m_data->mStartTime.QuadPart += msecAdjustment;
			elapsedTime -= msecAdjustment;
		}

		// Store the current elapsed time for adjustments next time.
		m_data->mPrevElapsedTime = elapsedTime;

		// Convert to microseconds.
		unsigned long usecTicks = (unsigned long)(1000000 * elapsedTime / 
			m_data->mClockFrequency.QuadPart);

		return usecTicks;
#else

#ifdef __CELLOS_LV2__
		uint64_t freq=sys_time_get_timebase_frequency();
		double dFreq=((double) freq)/ 1000000.0;
		typedef uint64_t  ClockSize;
		ClockSize newTime;
		//__asm __volatile__( "mftb %0" : "=r" (newTime) : : "memory");
		SYS_TIMEBASE_GET( newTime );

		return (unsigned long int)((double(newTime-m_data->mStartTime)) / dFreq);
#elif __DUETTO__
		// We don't have microsecond timing using Date
		double currentTime = client::Date.now();
		return (currentTime - m_data->mStartTime) * 1000;
#else

		struct timeval currentTime;
		gettimeofday(&currentTime, 0);
		return (currentTime.tv_sec - m_data->mStartTime.tv_sec) * 1000000 + 
			(currentTime.tv_usec - m_data->mStartTime.tv_usec);
#endif//__CELLOS_LV2__
#endif 
}
Пример #11
0
/* print the elements in the queue */
void PQ_print(PQueue* pq) {
  printf("PQ: "); fflush(stdout);
  unsigned int i;
  for (i=0; i< mymin(10, pq->cursize); i++) {
    printElem(pq->elements[i]);
  }
  printf("\n");fflush(stdout);
}
Пример #12
0
uint gamesell(uint i,uint a) /* As gamebuy but selling */
{   uint t=mymin(shipshold[i],a);
    shipshold[i]-=t;
    localmarket.quantity[i]+=t;
    if ((commodities[i].units)==tonnes) {holdspace+=t;}
    cash+=t*(localmarket.price[i]);
    return t;
}
Пример #13
0
// Посчитать, сколько памяти требуется для упаковки заданным методом
MemSize REP_METHOD::GetCompressionMem (void)
{
  // Скопировано из rep_compress
  int L = roundup_to_power_of (mymin(SmallestLen,MinMatchLen)/2, 2);  // Размер блоков, КС которых заносится в хеш
  int k = sqrtb(L*2);
  int HashSize = CalcHashSize (HashSizeLog, BlockSize, k);

  return BlockSize + HashSize*sizeof(int);
}
Пример #14
0
bool LineSegment::containPointExclusiveEnds(Point pt)
{
	double minx = mymin(start.x, end.x);
	double maxx = mymax(start.x, end.x);
	double miny = mymin(start.y, end.y);
	double maxy = mymax(start.y, end.y);

	if (containPointOpen(pt) && 
		(pt.x > minx || DOUBLE_EQUAL(pt.x, minx)) && 
		(pt.x < maxx || DOUBLE_EQUAL(pt.x, maxx)) && 
		(pt.y > miny || DOUBLE_EQUAL(pt.y, miny)) && 
		(pt.y < maxy || DOUBLE_EQUAL(pt.y, maxy)) && 
		pt.approxInequal(start) && 
		pt.approxInequal(end)) 
		return true;
	else
		return false;
}
Пример #15
0
int findMaxDistance(int v1, int v2, int t) {
    int v_1 = mymin(v1, v2);
    int v_2 = mymax(v1, v2);
    if (t == 2) {
        assert(v_2 - v_1 <= d);
        return v_1 + v_2;
    } else {
        return v_1 + findMaxDistance(v_1 + d, v_2, t - 1);
    }
}
void cSoundSourceStream::StreamBuffer(int buffer){
	int size = mymin(mpStream->RemainingBytes(),STREAM_BUFFER_SIZE);
	size = size - (size % mpStream->GetFrameSize());
	int frames = size / mpStream->GetFrameSize();
	int copied = mpStream->FillBuffer(b, size);
	//for(int i=0;i<128;++i)//printf("%i ",b[i]);//printf("\n");
	//printf("StreamBuffer frames=%d size=%d copied=%d,freq=%d\n",frames,size,copied,mpStream->GetFrequency());

	alBufferData(buffer, miBufferFormat, b, copied, mpStream->GetFrequency());
	CheckOpenAl();
}
Пример #17
0
// Посчитать, сколько памяти требуется для упаковки заданным методом
void REP_METHOD::SetCompressionMem (MemSize mem)
{
  if (mem>0)
  {
    // Скопировано из rep_compress
    int L = roundup_to_power_of (mymin(SmallestLen,MinMatchLen)/2, 2);  // Размер блоков, КС которых заносится в хеш
    int k = sqrtb(L*2);
    int HashSize = CalcHashSize (HashSizeLog, mem/5*4, k);

    BlockSize = mem - HashSize*sizeof(int);
  }
}
Пример #18
0
int main() {
	int  a;
	int  b;
	int  c;
	alarm(2);
	a = 0;
	b = 0;
	c = 0;


	mymin(a, b, c);
	return 0;
}
Пример #19
0
//write a wave file 
bool StereoBuffer16::WriteWave(const char* fname,unsigned int start, float level)
{
	//check to see if we have anything.
	if(NULL == m_left || NULL == m_right || 0 == mNumFrames)
		return false;
	
	FILE* fptr;
	fptr = WriteWaveHeader(fname, mNumFrames-start);
	
	if(NULL == fptr)
	{   //couldn't come through.
		return false;
	}
	
	//writing 1 short at a time might not be that fast- if this is 
	//an issue, we'll have to create a temp buff at the level instead
	//and do the entire buffer in one fwrite.
	short valuel,valuer;
	long *bufl = (long*)m_left->GetBuffer(0);
	long *bufr = (long*)m_right->GetBuffer(0);
	for(int i = start; i < mNumFrames;i++)
	{
		//have to pretend a short 
		valuel = mymax(mymin(bufl[i],SHORTLIMIT),-SHORTLIMIT) * level;
		valuer = mymax(mymin(bufr[i],SHORTLIMIT),-SHORTLIMIT) * level;
//#ifndef LITTLEENDIAN
#ifndef __LITTLE_ENDIAN__
		valuel = Swap_16(valuel);
		valuer = Swap_16(valuer);
#endif
		fwrite(&valuel,2,1,fptr);
		fwrite(&valuer,2,1,fptr);
	}
	fclose(fptr);
	printf("wrote the file %s\n", fname);
	return true;
	

}
static int dump_section (FILE * f, struct ConfigVTable * h, SectionHandle s, unsigned
      int indent)
{
   unsigned int sectionsize;
   size_t count;
   unsigned int i;
   int ret = 1;
   SectionEntry * entries = 0;

   ret = mymin (ret, cf_getSectionSize (h, s, &sectionsize));
   if (ret < 0)
      return ret;

   count = sectionsize;
  
   entries = (SectionEntry*)malloc (sizeof (SectionEntry) * sectionsize);

   ret = mymin(ret, cf_listSection (h, s, &entries[0], &count));

   if (ret < 0)
      goto fail;

   assert(sectionsize == count);

   for (i=0; i<count; ++i)
   {
      show_indent (f,indent);
      if (ret >= 0)
      {
         ret = mymin (ret, dump_entry (f, h, s, indent, &entries[i]));
      }
      free ((void*)entries[i].name);
   }

fail:
   free (entries);
   return ret;
}
Пример #21
0
int Colour::setcol(const double & magnitude)
{  // colour scale 0--1
	
	mag = mymax(0, mymin( 1, magnitude )); // make sure it's between 0 and 1


	// hot colormap
	//r =  mymin(  mymax( 8*mag / 3    , 0 ), 1 );
	//g =  mymin(  mymax( 8*mag / 3 - 1, 0 ), 1 );
	//b =  mymin(  mymax( 4*mag     - 3, 0 ), 1 );

	// rainbow colormap, 0 = black
//	r = mymin( mymax( -2 * fabs( mag - 1   ) + 1.3  ,0) ,1);
//	g = mymin( mymax( -2 * fabs( mag - 0.55) + 1.05 ,0) ,1);
	////b = mymin( mymax( -5 * fabs( mag - 0.25) + 1.2  ,0) ,1);
//    b = mymin( mymax( -2 * fabs( mag - 0.25) + 1.2  ,0) ,1);

	// hls, sort of
	//r =   mymin(  mymax( (4*    (mag-0.25) ) , 0 ), 1 );
	//b =   mymin(  mymax( (4*    (0.75-mag) ) , 0 ), 1 );
	//g =   mymin(  mymax( (4*fabs(mag-0.5)-1) , 0 ), 1 );

    //r = mymin( mymax( -2 * abs( mag - 1   ) + 1.3  ,0) ,1);
    //g = mymin( mymax( -2 * abs( mag - 0.4) + 1.15 ,0) ,1);
    //b = mymin( mymax( -2 * abs( mag - 0.05) + 1.2  ,0) ,1);

    

//r = mymin( mymax( -1.8* fabs( mag - 1   ) + 1.3  ,0) ,1);
//g = mymin( mymax( -2.6 * fabs( mag - 0.58) + 1.05 ,0) ,1);

//b = mymin( mymax( -3 * fabs( mag - 0.25) + 1.2  ,0) ,1);


    r = mymin( mymax( -1.8* fabs( mag - 1   ) + 1.3  ,0) ,1);
if (mag < 0.58) 
    g = mymin( mymax( -2.0 * fabs( mag - 0.58) + 1.05 ,0) ,1);
else
    g = mymin( mymax( -2.6 * fabs( mag - 0.58) + 1.05 ,0) ,1);

if (mag < 0.25) 
    b = mymin( mymax( -2.5 * fabs( mag - 0.25) + 1.2  ,0) ,1);
else
    b = mymin( mymax( -3 * fabs( mag - 0.25) + 1.2  ,0) ,1);


// gamma adjustment --- note this is applied both to the data and the scale bar, so we don't misrepresent anything
    r = pow( r , 1 / COLOUR_GAMMA);
    g = pow( g , 1 / COLOUR_GAMMA);
    b = pow( b , 1 / COLOUR_GAMMA);

	R = (unsigned char) (r*255);
	G = (unsigned char) (g*255);
	B = (unsigned char) (b*255);

	return 0;
}
Пример #22
0
void VarproFunction::computeDefaultRTheta( gsl_matrix *RTheta ) {
  size_t c_size1 = getN(), c_size2 = getNrow();
  size_t status = 0;
  size_t minus1 = -1;
  double tmp;

  gsl_matrix * tempc = gsl_matrix_alloc(c_size1, c_size2);
  if (myPhi == NULL) {
    gsl_matrix_memcpy(tempc, myMatr);
  } else {
    gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1, myMatr, myPhi, 0, tempc);
  }
  
  gsl_matrix * tempu = gsl_matrix_alloc(c_size2, c_size2);
  double *s = new double[mymin(c_size1, c_size2)];
  
  /* Determine optimal work */
  size_t lwork;
  dgesvd_("A", "N", &tempc->size2, &tempc->size1, tempc->data, &tempc->tda, s,
     tempu->data, &tempu->size2, NULL, &tempc->size1, &tmp, &minus1, &status);
  double *work = new double[(lwork = tmp)];
  /* Compute low-rank approximation */ 
  dgesvd_("A", "N", &tempc->size2, &tempc->size1, tempc->data, &tempc->tda, s,
     tempu->data, &tempu->size2, NULL, &tempc->size1, work, &lwork, &status);

  if (status) {
    delete [] s;  
    delete [] work;  
    gsl_matrix_free(tempc);
    gsl_matrix_free(tempu);
    throw new Exception("Error computing initial approximation: "
                        "DGESVD didn't converge\n");
  }

  gsl_matrix_transpose(tempu);
  gsl_matrix_view RlraT;
  RlraT = gsl_matrix_submatrix(tempu, 0, tempu->size2 - RTheta->size2, 
                               tempu->size1, RTheta->size2);
  gsl_matrix_memcpy(RTheta, &(RlraT.matrix));
    
  delete [] s;  
  delete [] work;  
  gsl_matrix_free(tempc);
  gsl_matrix_free(tempu);
}
Пример #23
0
uint32_t tor_compress(uint8_t method, uint8_t* inbuf, uint32_t inlen, uint8_t* outbuf, uint32_t outlen)
{
	PackMethod m;
	static Results r; 
	r.inbuf = inbuf;
	r.outbuf = outbuf;
	r.inlen = inlen;
    r.outlen = outlen;

	ReadWriteCallback ("init", NULL, 0, &r);
	if (method >= 20)
		m = second_Tornado_method[method-20];
	else
		m = std_Tornado_method[method];
			
	m.buffer = mymin (m.buffer, r.inlen+LOOKAHEAD*2);
	int result = tor_compress (m, ReadWriteCallback, &r, NULL, -1); 
	return r.outpos;
}
Пример #24
0
    //-----------------------------------------------------------------------
    //                       g e t M i c r o S e c o n d s
    //-----------------------------------------------------------------------
    unsigned long TTimer::getMicroSeconds()
    {
#ifdef TUBRAS_PLATFORM_WINDOWS
        LARGE_INTEGER currentTime;
        QueryPerformanceCounter(&currentTime);
        LONGLONG elapsedTime = currentTime.QuadPart - 
            mStartTime.QuadPart;

        // Compute the number of millisecond ticks elapsed.
        unsigned long msecTicks = (unsigned long)(1000 * elapsedTime / 
            mClockFrequency.QuadPart);

        // Check for unexpected leaps in the Win32 performance counter.  
        // (This is caused by unexpected data across the PCI to ISA 
        // bridge, aka south bridge.  See Microsoft KB274323.)
        unsigned long elapsedTicks = GetTickCount() - mStartTick;
        signed long msecOff = (signed long)(msecTicks - elapsedTicks);
        if (msecOff < -100 || msecOff > 100)
        {
            // Adjust the starting time forwards.
            LONGLONG msecAdjustment = mymin(msecOff * 
                mClockFrequency.QuadPart / 1000, elapsedTime - 
                mPrevElapsedTime);
            mStartTime.QuadPart += msecAdjustment;
            elapsedTime -= msecAdjustment;
        }

        // Store the current elapsed time for adjustments next time.
        mPrevElapsedTime = elapsedTime;

        // Convert to microseconds.
        unsigned long usecTicks = (unsigned long)(1000000 * elapsedTime / 
            mClockFrequency.QuadPart);

        return usecTicks;
#else
        struct timeval currentTime;
        gettimeofday(&currentTime, 0);
        return (currentTime.tv_sec - mStartTime.tv_sec) * 1000000 + 
            (currentTime.tv_usec - mStartTime.tv_usec);
#endif
    }
Пример #25
0
// функци¤ принадлежности точки области  // не используетс¤
static AWPBOOL IsPixelBelongArea(AWPINT NumPoints, awpPoint* P, AWPINT x, AWPINT y){
   AWPINT Count, i, j, m, x0;
   AWPBOOL F;
   AWPDOUBLE t;
   Count = 0;
   for (i = 0; i < NumPoints-1; i++)    {
      j =  (i+1);
      if (P[i].Y == P[j].Y) continue;
      if (P[i].Y > y && P[j].Y > y) continue;
      if (P[i].Y < y && P[j].Y < y) continue;

      m = mymax(P[i].Y,P[j].Y, &F);
      if (F) x0 = P[i].X; else x0 = P[j].X;
      if (m == y && x0 > x)
       Count = 1 - Count;
      else if (mymin(P[i].Y,P[j].Y)== y) continue;
      else{
      t = ((AWPDOUBLE)y - P[i].Y) / (P[j].Y - P[i].Y);
      if (t > 0 && t <1 && P[i].X + t*(P[j].X - P[i].X) >= x) Count = 1 - Count;
      }
   }
   return (Count == 0)?FALSE:TRUE;
}
Пример #26
0
//at start time it should retun 1.0 at end time mEndCoef
//the second parameter is for recursive calls since this uses incompatable static variables
double Interpolation::ValueAtTime(double time)
{
   double cursor =mymin(mymax(0.0,time-mStartTime)/mDuration,1.0);
   double phase;
   double ret;
    
   __thread static InterpolationMetaData *meta;
    if (!meta) {
        meta = new InterpolationMetaData; /*TODO:leak*/
    }
   //get the list of our local parameters and copy them.
    std::vector<double> &instantParams = meta->instantParams;
   bool &instantParamsCleared = meta->instantParamsCleared;
   
   if(instantParamsCleared)
   {
      for(int i =0;i<mInterpParams.GetNumParameters();i++)
         instantParams.push_back(mInterpParams.GetValue((Parameter)i));
      instantParamsCleared=false;
   }
   else
   {
      for(int i =0;i<mInterpParams.GetNumParameters();i++)
         instantParams[i]=mInterpParams.GetValue((Parameter)i);   
   }
   
   //check to see if we have metaInterps attached to us and apply them.
   for(int i=0;i<mAttachedMetaInterps.size();i++)
   {
	//caution - MetaInterpolation::Apply uses ValueAtTime 
      mAttachedMetaInterps[i]->Apply(time,&instantParams);
   }
   
//   assert(mStartTime <=time);
//   assert(mStartTime+mDuration>=time);
//   


   switch(mType)
   {
      
      case eLinear:
        ret= cursor*(mEndCoef-1.0) + 1.0;
        break;
      case eExp2:
         ret= exp2cursor(cursor)*mEndCoef+(1.0-exp2cursor(cursor));
         break;
	  case eStep:
          ret= (mEndCoef-1.0)*((float)(floor((cursor+0.001) * floor(instantParams[eInterpTypeVariable]))))/floor(instantParams[eInterpTypeVariable]) + 1.0;
          break;
	  case eExp2Step:
          ret= (mEndCoef-1.0)*exp2cursor(((float)(floor((cursor+0.001) * floor(instantParams[eInterpTypeVariable]))))/floor(instantParams[eInterpTypeVariable]))+1.0;
          break;
     case eSquare:
     //need to implement some fading to bandlimit the square.
//         while(phase>2*3.141592)
//            phase-=2*3.141592;
//         if(phase>(2*3.141592*interpTypeVariable) <kSquareTransitSamples/44100.0)
//            return (mEndCoef-1.0) + 1.0;
         phase=modf(     (2 * cursor * (floor(instantParams[eInterpTypeVariable])/**mDuration*/+0.5 ) - 0.5)/2.0,&phase);//we just clober the intpart with the return value
         phase = 3.141592*2* phase;
         ret= phase<3.141592?1.0:mEndCoef;
         break;
     
     case ePeriodic:
		//sinusoid that starts at -1 (-pi/2) and continues for (n+0.5)periods to end up at +1 (pi/2)
		//we also shrink it down soo that -pi/2 comes to 1.0 and pi/2 comes to mEndCoef. 
      phase=modf(     (2 * cursor * (floor(instantParams[eInterpTypeVariable])/**mDuration*/+0.5 ) - 0.5)/2.0,&phase);//we just clober the intpart with the return value
      phase = 3.141592*2* phase;
		ret=  (sin(phase)*(mEndCoef-1.0)/2.0)+(mEndCoef-1.0)/2.0 + 1.0;
		break;
      
     default:
       assert(1==0);//shouldn't reach here.
       break;
   }
   return ret;
}
Пример #27
0
//this randomize has to be clever enough to not overstep the min/max
//constraints WHILE the other nodes are interpolating the same parameter
void Interpolation::Randomize(double startTime, double duration, std::vector<TreeNode*> *activeNodes,  std::vector<ParameterList*> *parameters, int layerNum,  int topLayer, int numControlledLayers, int param)
{
	
   mType=(InterpolationType)randint(eNumInterpolationTypes);
   mDoesConcatenate = true;//randint(2);
   
	switch(mType)
	{
		case ePeriodic:
      case eSquare:
      //set the number of periods
			interpTypeVariable = (int)randfloatexp2(mymax(5,duration*kMaxPeriodsPerSecond)) + 0.5; //can't have more periods then we have samples.
         mInterpParams.SetParameter(eInterpTypeVariable, interpTypeVariable,0.001,mymax(5,duration*kMaxPeriodsPerSecond)+0.99);
			break;
         
	  case eExp2Step:
      case eStep:
         interpTypeVariable = randint(mymax(1.0,kMaxStepsPerSecond*duration))+1; //can't have more periods then we have samples.
         mInterpParams.SetParameter(eInterpTypeVariable,interpTypeVariable,interpTypeVariable,interpTypeVariable);
			break;
	}
	mStartTime = startTime;
	mDuration = duration;
   //first decide on a param if none was specified
   if(param==-1)
      mParam=(Parameter)randint((*parameters)[layerNum]->GetNumParameters());
   else
      mParam=(Parameter)param;
   
   //we know where the parameter will be at the start of the leaf 
   //here we get it from the parameter list
   
   
   double startValue = (*parameters)[layerNum]->GetValue(mParam);
   //- we don't know where it will be at the end of the leaf.  
   //now check to see where the parameter will be at upon the end of the leaf.  
   //we do this by asking each of the active nodes what their value will be at the end of THIS leaf
   //and multiply them against the start value.
   
   double topValue = startValue;
   double bottomValue = startValue;
   
   for(int i =0;i<numControlledLayers;i++)
   {
      topValue = mymax(topValue, (*parameters)[topLayer+i]->GetValue(mParam));
      bottomValue = mymin(bottomValue, (*parameters)[topLayer+i]->GetValue(mParam));
   }
   
   for(int i=0;i<activeNodes->size();i++)
   {
      for(int j=0;j<((*activeNodes)[i])->GetNumInterpolations();j++)
      {
         
         if(((*activeNodes)[i])->GetInterpolation(j)->GetParameter() == mParam)
         {
            //we use this node's start time, and the parent node's end time (since we can't push them to overstep their boundries.)
            topValue = mymax(topValue,topValue*((*activeNodes)[i])->GetInterpolation(j)->MaxValueInTimeRange(mStartTime,((*activeNodes)[i])->GetInterpolation(j)->GetStartTime()+((*activeNodes)[i])->GetInterpolation(j)->GetDuration()));
            bottomValue = mymin(bottomValue,bottomValue*((*activeNodes)[i])->GetInterpolation(j)->MinValueInTimeRange(mStartTime,((*activeNodes)[i])->GetInterpolation(j)->GetStartTime()+((*activeNodes)[i])->GetInterpolation(j)->GetDuration()));

            //this makes new nodes never overstep the boundries of what old nodes have reliquished.
            //the above two lines need to be commented out in order for it to work.
            //topValue = mymax(topValue,topValue*((*activeNodes)[i])->GetInterpolation(j)->MaxValueInTimeRange(((*activeNodes)[i])->GetInterpolation(j)->GetStartTime(),((*activeNodes)[i])->GetInterpolation(j)->GetStartTime()+((*activeNodes)[i])->GetInterpolation(j)->GetDuration()));
            //bottomValue = mymin(bottomValue,bottomValue*((*activeNodes)[i])->GetInterpolation(j)->MinValueInTimeRange(((*activeNodes)[i])->GetInterpolation(j)->GetStartTime(),((*activeNodes)[i])->GetInterpolation(j)->GetStartTime()+((*activeNodes)[i])->GetInterpolation(j)->GetDuration()));

         }
      }
   }
   
   assert(topValue >= bottomValue);
   //now decide if we are going to interpolate UP or down.
   bool up = coinflip();
    
   if(up)
   {
      if(mParam == eBandwidth || mParam==eBreathPressure || mParam == eBlowPosition || mParam == eReedStiffness ||mParam == eMultiInstNum ||
              mParam== eReedAperature || mParam ==eVibratoGain || mParam ==eNoiseGain || mParam ==eMaxBlowLength || mParam ==eInstrumentNum)
//               mEndCoef = 1.0+randfloat( mymax(0.0,parameters->GetMaxValue(mParam)/mymax(0.000001,mymax(startValue,endValue)) -1.0));
         mEndCoef = 1.0+randfloat( mymax(0.0,(*parameters)[layerNum]->GetMaxValue(mParam)/mymax(0.000001,topValue) -1.0));
      else
//         mEndCoef = 1.0+randfloatexp2( mymax(0.0,parameters->GetMaxValue(mParam)/mymax(0.000001,mymax(startValue,endValue)) -1.0));
         mEndCoef = 1.0+randfloatexp2( mymax(0.0,(*parameters)[layerNum]->GetMaxValue(mParam)/mymax(0.000001,topValue) -1.0));

   assert(topValue*mEndCoef<=(*parameters)[layerNum]->GetMaxValue(mParam)*1.02);
   }
   else
   {
	  //use the minimum to find out where the coefficient should be.  
	  //mEnd Coef can be from the ratio of min to the end, up to 1.0 
     
      if(mParam == eBandwidth || mParam==eBreathPressure || mParam == eBlowPosition || mParam == eReedStiffness || mParam == eMultiInstNum ||
         mParam== eReedAperature || mParam ==eVibratoGain || mParam ==eNoiseGain || mParam ==eMaxBlowLength || mParam ==eInstrumentNum)
         mEndCoef = 1.0- randfloat( 1.0-mymin(1.0,mymax(0.0,(*parameters)[layerNum]->GetMinValue(mParam)/mymax(0.000001,bottomValue))));
//         mEndCoef = mymax(0.0,parameters->GetMinValue(mParam)/mymax(0.000001,bottomValue))+ randfloat( 1.0-mymax(0.0,parameters->GetMinValue(mParam)/mymax(0.000001,bottomValue)));   
      else
         mEndCoef = 1.0- randfloatexp2( 1.0-mymin(1.0,mymax(0.0,(*parameters)[layerNum]->GetMinValue(mParam)/mymax(0.000001,bottomValue))));
//         mEndCoef = mymax(0.0,parameters->GetMinValue(mParam)/mymax(0.000001,bottomValue))+ randfloatexp2( 1.0-mymax(0.0,parameters->GetMinValue(mParam)/mymax(0.000001,bottomValue)));   

   assert(bottomValue*mEndCoef>=(*parameters)[layerNum]->GetMinValue(mParam)*0.98);
   }
   //fix boundries.
   //if(topValue*mEndCoef>=parameters->GetMaxValue(mParam))
   //   mEndCoef = parameters->GetMaxValue(mParam)/topValue;
  // else if(bottomValue*mEndCoef<=parameters->GetMinValue(mParam))
    //  mEndCoef=parameters->GetMinValue(mParam)/bottomValue;
   
   //we might have caused a conflict on the other side, if we did, this guy can't interpolate, and must stay at 1.0
   //it can have local non concatenating fluctuations, however.
   if((topValue*mEndCoef>=(*parameters)[layerNum]->GetMaxValue(mParam)) ||
         (bottomValue*mEndCoef<=(*parameters)[layerNum]->GetMinValue(mParam)) )
         mEndCoef=1.0;
         
//   assert(topValue*mEndCoef<=(*parameters)[layerNum]->GetMaxValue(mParam)*1.02);
 //  assert(bottomValue*mEndCoef>=(*parameters)[layerNum]->GetMinValue(mParam)*0.98);
   
   
}
Пример #28
0
void dtron(int n, double *x, double *xl, double *xu, double gtol, double frtol, double fatol, double fmin, int maxfev, double cgtol) 
{
/*
c     *********
c
c     Subroutine dtron
c
c     The optimization problem of BSVM is a bound-constrained quadratic
c     optimization problem and its Hessian matrix is positive semidefinite. 
c     We modified the optimization solver TRON by Chih-Jen Lin and
c     Jorge More' into this version which is suitable for this
c     special case.
c
c     This subroutine implements a trust region Newton method for the
c     solution of large bound-constrained quadratic optimization problems
c
c           min { f(x)=0.5*x'*A*x + g0'*x : xl <= x <= xu }
c
c     where the Hessian matrix A is dense and positive semidefinite. The
c     user must define functions which evaluate the function, gradient, 
c     and the Hessian matrix.
c
c     The user must choose an initial approximation x to the minimizer,
c     lower bounds, upper bounds, quadratic terms, linear terms, and
c     constants about termination criterion.
c
c	parameters:
c
c       n is an integer variable.
c         On entry n is the number of variables.
c         On exit n is unchanged.
c
c       x is a double precision array of dimension n.
c         On entry x specifies the vector x.
c         On exit x is the final minimizer.
c
c       xl is a double precision array of dimension n.
c         On entry xl is the vector of lower bounds.
c         On exit xl is unchanged.
c
c       xu is a double precision array of dimension n.
c         On entry xu is the vector of upper bounds.
c         On exit xu is unchanged.
c
c       gtol is a double precision variable.
c         On entry gtol specifies the relative error of the projected 
c            gradient.
c         On exit gtol is unchanged. 
c
c       frtol is a double precision variable.
c         On entry frtol specifies the relative error desired in the
c            function. Convergence occurs if the estimate of the
c            relative error between f(x) and f(xsol), where xsol
c            is a local minimizer, is less than frtol.
c         On exit frtol is unchanged.
c
c       fatol is a double precision variable.
c         On entry fatol specifies the absolute error desired in the
c            function. Convergence occurs if the estimate of the
c            absolute error between f(x) and f(xsol), where xsol
c            is a local minimizer, is less than fatol.
c         On exit fatol is unchanged.
c
c       fmin is a double precision variable.
c         On entry fmin specifies a lower bound for the function.
c            The subroutine exits with a warning if f < fmin.
c         On exit fmin is unchanged.
c
c       maxfev is an integer variable.
c         On entry maxfev specifies the limit of function evaluations.
c         On exit maxfev is unchanged.
c
c       cgtol is a double precision variable.
c         On entry gqttol specifies the convergence criteria for
c            subproblems.
c         On exit gqttol is unchanged.
c
c     **********
*/

	/* Parameters for updating the iterates. */
	double eta0 = 1e-4, eta1 = 0.25, eta2 = 0.75;
	
	/* Parameters for updating the trust region size delta. */
	double sigma1 = 0.25, sigma2 = 0.5, sigma3 = 4;

	double p5 = 0.5, one = 1;
	double gnorm, gnorm0, delta, snorm;
	double alphac = 1, alpha, f, fc, prered, actred, gs;
	int search = 1, iter = 1, info, inc = 1;	
	double *xc = (double *) xmalloc(sizeof(double)*n);
	double *s = (double *) xmalloc(sizeof(double)*n);
	double *wa = (double *) xmalloc(sizeof(double)*n); 	
	double *g = (double *) xmalloc(sizeof(double)*n);
	double *A = NULL;

	uhes(n, x, &A);
	ugrad(n, x, g);	
	ufv(n, x, &f);	
	gnorm0 = F77_CALL(dnrm2)(&n, g, &inc);
	delta = 1000*gnorm0;
	gnorm = dgpnrm(n, x, xl, xu, g);
	if (gnorm <= gtol*gnorm0)
	{
		/*
		//printf("CONVERGENCE: GTOL TEST SATISFIED\n");
		*/
		search = 0;
	}

	while (search)
	{ 

		/* Save the best function value and the best x. */   
		fc = f;
		memcpy(xc, x, sizeof(double)*n);
		
		/* Compute the Cauchy step and store in s. */		
		dcauchy(n, x, xl, xu, A, g, delta, &alphac, s, wa);
		
		/* Compute the projected Newton step. */		
		dspcg(n, x, xl, xu, A, g, delta, cgtol, s, &info);
		if (ufv(n, x, &f) > maxfev)
		{
			/*
			//printf("ERROR: NFEV > MAXFEV\n");
			*/
			search = 0;
			continue;
		}

		/* Compute the predicted reduction. */
		memcpy(wa, g, sizeof(double)*n);
		F77_CALL(dsymv)("U", &n, &p5, A, &n, s, &inc, &one, wa, &inc);
		prered = -F77_CALL(ddot)(&n, s, &inc, wa, &inc);
                        
		/* Compute the actual reduction. */
	        actred = fc - f;                
                                    
		/* On the first iteration, adjust the initial step bound. */
		snorm = F77_CALL(dnrm2)(&n, s, &inc);
		if (iter == 1)
			delta = mymin(delta, snorm);

		/* Compute prediction alpha*snorm of the step. */
		gs = F77_CALL(ddot)(&n, g, &inc, s, &inc);

		if (f - fc - gs <= 0)
			alpha = sigma3;
		else
			alpha = mymax(sigma1, -0.5*(gs/(f - fc - gs)));

		/* Update the trust region bound according to the ratio
		of actual to predicted reduction. */
		if (actred < eta0*prered)
		
			/* Reduce delta. Step is not successful. */
			delta = mymin(mymax(alpha, sigma1)*snorm, sigma2*delta);
		else 
		{
			if (actred < eta1*prered)

				/* Reduce delta. Step is not sufficiently successful. */
				delta = mymax(sigma1*delta, mymin(alpha*snorm, sigma2*delta));
			else 
				if (actred < eta2*prered)
				
					/* The ratio of actual to predicted reduction is in
					the interval (eta1,eta2). We are allowed to either
					increase or decrease delta. */
					delta = mymax(sigma1*delta, mymin(alpha*snorm, sigma3*delta));
				else
				
					/* The ratio of actual to predicted reduction exceeds eta2.
					Do not decrease delta. */
					delta = mymax(delta, mymin(alpha*snorm, sigma3*delta));
		}

		/* Update the iterate. */
		if (actred > eta0*prered) 
		{
		
			/* Successful iterate. */
			iter++;
			/*
			uhes(n, x, &A);
			*/
			ugrad(n, x, g);
			gnorm = dgpnrm(n, x, xl, xu, g);		
			if (gnorm <= gtol*gnorm0)
        		{
				/*
				//printf("CONVERGENCE: GTOL = %g TEST SATISFIED\n", gnorm/gnorm0);
				*/
				search = 0;
		                continue;
			}
		}
		else
		{

			/* Unsuccessful iterate. */
			memcpy(x, xc, sizeof(double)*n);
			f = fc;
		}
	
		/* Test for convergence */
		if (f < fmin)
		{
			//printf("WARNING: F .LT. FMIN\n");
			search = 0; /* warning */
			continue;
		}
		if (fabs(actred) <= fatol && prered <= fatol)
		{
			//printf("CONVERGENCE: FATOL TEST SATISFIED\n");
			search = 0;
			continue;
		}
		if (fabs(actred) <= frtol*fabs(f) && prered <= frtol*fabs(f))
		{
			/*
			//printf("CONVERGENCE: FRTOL TEST SATISFIED\n");		
			*/
			search = 0;
			continue;
		}
	}	

	free(g);
	free(xc);
	free(s);
	free(wa);
}
Пример #29
0
// Scale object boundings to [-5,5]
void DXFRenderer::NormalizeEntities()
{
    // calculate current min and max boundings of object
    DXFVector minv(10e20f, 10e20f, 10e20f);
    DXFVector maxv(-10e20f, -10e20f, -10e20f);
    for (DXFEntityList::compatibility_iterator node = m_entities.GetFirst(); node; node = node->GetNext())
    {
        DXFEntity *p = node->GetData();
        if (p->type == DXFEntity::Line)
        {
            DXFLine *line = (DXFLine *)p;
            const DXFVector *v[2] = { &line->v0, &line->v1 };
            for (int i = 0; i < 2; ++i)
            {
                minv.x = mymin(v[i]->x, minv.x);
                minv.y = mymin(v[i]->y, minv.y);
                minv.z = mymin(v[i]->z, minv.z);
                maxv.x = mymax(v[i]->x, maxv.x);
                maxv.y = mymax(v[i]->y, maxv.y);
                maxv.z = mymax(v[i]->z, maxv.z);
            }
        } else if (p->type == DXFEntity::Face)
        {
            DXFFace *face = (DXFFace *)p;
            const DXFVector *v[4] = { &face->v0, &face->v1, &face->v2, &face->v3 };
            for (int i = 0; i < 4; ++i)
            {
                minv.x = mymin(v[i]->x, minv.x);
                minv.y = mymin(v[i]->y, minv.y);
                minv.z = mymin(v[i]->z, minv.z);
                maxv.x = mymax(v[i]->x, maxv.x);
                maxv.y = mymax(v[i]->y, maxv.y);
                maxv.z = mymax(v[i]->z, maxv.z);
            }
       }
    }

    // rescale object down to [-5,5]
    DXFVector span(maxv.x - minv.x, maxv.y - minv.y, maxv.z - minv.z);
    float factor = mymin(mymin(10.0f / span.x, 10.0f / span.y), 10.0f / span.z);
    for (DXFEntityList::compatibility_iterator node2 = m_entities.GetFirst(); node2; node2 = node2->GetNext())
    {
        DXFEntity *p = node2->GetData();
        if (p->type == DXFEntity::Line)
        {
            DXFLine *line = (DXFLine *)p;
            DXFVector *v[2] = { &line->v0, &line->v1 };
            for (int i = 0; i < 2; ++i)
            {
                v[i]->x -= minv.x + span.x/2; v[i]->x *= factor;
                v[i]->y -= minv.y + span.y/2; v[i]->y *= factor;
                v[i]->z -= minv.z + span.z/2; v[i]->z *= factor;
            }
        } else if (p->type == DXFEntity::Face)
        {
            DXFFace *face = (DXFFace *)p;
            DXFVector *v[4] = { &face->v0, &face->v1, &face->v2, &face->v3 };
            for (int i = 0; i < 4; ++i)
            {
                v[i]->x -= minv.x + span.x/2; v[i]->x *= factor;
                v[i]->y -= minv.y + span.y/2; v[i]->y *= factor;
                v[i]->z -= minv.z + span.z/2; v[i]->z *= factor;
            }
       }
    }
}
Пример #30
0
int main (int argc, char **argv)
{
    // Optimize allocation for Tornado (2GB hash allocated after 1GB dictionary)
    AllocTopDown = FALSE;

    // Operation mode
    OPMODE global_mode=AUTO;

    // Record that stores all the info required for ReadWriteCallback
    static Results r;
    r.use_cpu_time = r.quiet_title = r.quiet_header = r.quiet_progress = r.quiet_result = FALSE;

    // Default compression parameters are equivalent to option -5
    r.method = std_Tornado_method [default_Tornado_method];

    // Delete successfully (de)compressed input files
    bool delete_input_files = FALSE;

    // Count of files to process
    int fcount=0;

    // Output path/filename
    const char *output_filename = NULL;

    // Process options until "--"
    // 1. First, process -1..-16 option if any
    for (char **argv_ptr = argv; *++argv_ptr!=NULL; ) {
        char *param = *argv_ptr;
        if (*param == '-') {
            param++;
                 if (strcasecmp(param,"-")==0)   break;   // "--" is a "stop processing" option
            else if (isdigit(*param))            r.method = std_Tornado_method[check_parse_int (param, 1, elements(std_Tornado_method)-1, param-1)];
        }
    }
    // 2. Second, process rest of options
    for (char **argv_ptr = argv; *++argv_ptr!=NULL; ) {
        char *param = *argv_ptr;
        if (param[0] != '-' || param[1]=='\0') {
            fcount++;
        } else { param++;  int error=0;
                 if (strcasecmp(param,"-")==0)      break;
            else if (strcasecmp(param,"") ==0)      continue;
            else if (strcasecmp(param,"z")==0)      global_mode=_COMPRESS;
            else if (strcasecmp(param,"d")==0)      global_mode=_DECOMPRESS;
            else if (strcasecmp(param,"delete")==0) delete_input_files=TRUE;
            else if (strcasecmp(param,"t")==0)      output_filename="";
            else if (strcasecmp(param,"q")==0)      r.quiet_title = r.quiet_header = r.quiet_progress = r.quiet_result = TRUE;
#ifndef FREEARC_NO_TIMING
            else if (strcasecmp(param,"cpu")==0)    r.use_cpu_time=TRUE;
#endif
            else if (strcasecmp(param,"h")==0)      global_mode=HELP;
            else if (strcasecmp(param,"b")==0)      r.method.buffer = MAX_BUFFER_SIZE;         // set buffer size to the maximum supported by LZ coders
            else if (strcasecmp(param,"x")==0)      r.method.caching_finder = CACHING_MF4;
            else if (strcasecmp(param,"xx")==0)     r.method.caching_finder = CYCLED_MF4;
            else if (strcasecmp(param,"x+")==0)     r.method.caching_finder = CACHING_MF4;
            else if (strcasecmp(param,"x-")==0)     r.method.caching_finder = NON_CACHING_MF;
            else if (strcasecmp(param,"t+")==0)     r.method.find_tables = TRUE;
            else if (strcasecmp(param,"t-")==0)     r.method.find_tables = FALSE;
            else if (strcasecmp(param,"t1")==0)     r.method.find_tables = TRUE;
            else if (strcasecmp(param,"t0")==0)     r.method.find_tables = FALSE;
            else if (strcasecmp(param,"s")==0)      r.method.hash3 = 1;
            else if (strcasecmp(param,"ss")==0)     r.method.hash3 = 2;
            else if (strcasecmp(param,"s+")==0)     r.method.hash3 = 1;
            else if (strcasecmp(param,"s-")==0)     r.method.hash3 = 0;
            else if (start_with(param,"fb"))        r.method.fast_bytes = check_parse_int (param+2, MIN_FAST_BYTES, MAX_FAST_BYTES, *argv_ptr);
#ifdef FREEARC_WIN
            else if (strcasecmp(param,"slp-")==0)   DefaultLargePageMode = DISABLE;
            else if (strcasecmp(param,"slp" )==0)   DefaultLargePageMode = TRY;
            else if (strcasecmp(param,"slp+")==0)   DefaultLargePageMode = FORCE;
#endif
            else if (start_with(param,"rem"))       /* ignore option */;
            else if (isdigit(*param))            ; // -1..-16 option is already processed :)
            else switch( tolower(*param++) ) {
                case 'b': r.method.buffer          = check_parse_mem (param, MIN_BUFFER_SIZE, MAX_BUFFER_SIZE,    *argv_ptr);  break;
                case 'h': r.method.hashsize        = check_parse_mem (param, MIN_HASH_SIZE,   MAX_HASH_SIZE,      *argv_ptr);  break;
                case 'l': r.method.hash_row_width  = check_parse_int (param, 1,               MAX_HASH_ROW_WIDTH, *argv_ptr);  break;
                case 'u': r.method.update_step     = check_parse_int (param, 1,               MAX_UPDATE_STEP,    *argv_ptr);  break;
                case 'c': r.method.encoding_method = check_parse_int (param, BYTECODER,       ARICODER,           *argv_ptr);  break;
                case 's': r.method.hash3           = check_parse_int (param, 0,               2,                  *argv_ptr);  break;
                case 'p': r.method.match_parser    = parseInt (param, &error);  break;
                case 'x': r.method.caching_finder  = parseInt (param, &error);  break;
                case 'o': output_filename          = param;                     break;
                case 'q':
#ifndef FREEARC_NO_TIMING
                          r.quiet_title            = strchr (param, 't');
                          r.quiet_progress         = strchr (param, 'p');
#endif
                          r.quiet_header           = strchr (param, 'h');
                          r.quiet_result           = strchr (param, 'r');
                          break;
                case 'a': switch( tolower(*param++) ) {
                            case 'h': r.method.auxhash_size      = check_parse_mem (param, MIN_HASH_SIZE, MAX_HASH_SIZE, *argv_ptr);  goto check_for_errors;
                            case 'l': r.method.auxhash_row_width = check_parse_int (param, 1,        MAX_HASH_ROW_WIDTH, *argv_ptr);  goto check_for_errors;
                          }
                          // 'a' should be the last case!
                default : fprintf (stderr, "ERROR: unknown option '%s'\n", *argv_ptr);
                          exit(FREEARC_EXIT_ERROR);
            }
check_for_errors:
            if (error) {
                fprintf (stderr, "ERROR: bad option format: '%s'\n", *argv_ptr);
                exit(FREEARC_EXIT_ERROR);
            }
            if (!(r.method.match_parser==GREEDY || r.method.match_parser==LAZY  || r.method.match_parser==OPTIMAL)) {
                fprintf (stderr, "ERROR: bad option value: '%s'\n", *argv_ptr);
                exit(FREEARC_EXIT_ERROR);
            }
            int mf = r.method.caching_finder;
            r.method.caching_finder = mf = (mf==CACHING_MF4_DUB? CACHING_MF4 : (mf==CYCLED_MF4_DUB? CYCLED_MF4 : mf));
            if (!(mf==NON_CACHING_MF || (CYCLED_MF4<=mf && mf<=CYCLED_MF7) || (CACHING_MF4<=mf && mf<=CACHING_MF7) || (BT_MF4<=mf && mf<=BT_MF7))) {
                fprintf (stderr, "ERROR: non-existing match finder: '%s'\n", *argv_ptr);
                exit(FREEARC_EXIT_ERROR);
            }
        }
    }

    // No files to compress: read from stdin and write to stdout
    if (global_mode!=HELP && fcount==0 &&
       (global_mode!=AUTO  ||  !isatty(0) && !isatty(1)) ) {

        static char *_argv[] = {argv[0], (char*)"-", NULL};
        argv = _argv;
        fcount = 1;

    } else if (global_mode==HELP || fcount==0) {
        char h[100], ah[100], b[100], MinHashSizeStr[100], MaxHashSizeStr[100], MinBufSizeStr[100], MaxBufSizeStr[100];
        showMem64 (r.method.hashsize, h);
        showMem64 (r.method.auxhash_size, ah);
        showMem64 (r.method.buffer, b);
        showMem64 (MIN_HASH_SIZE, MinHashSizeStr);
        showMem64 (MAX_HASH_SIZE+1, MaxHashSizeStr);
        showMem64 (MIN_BUFFER_SIZE, MinBufSizeStr);
        showMem64 (MAX_BUFFER_SIZE, MaxBufSizeStr);
        printf( "Tornado compressor v0.6  (c) [email protected]  http://freearc.org  2014-03-08\n"
                "\n"
                " Usage: tor [options and files in any order]\n"
                "   -#      -- compression level (1..%d), default %d\n", int(elements(std_Tornado_method))-1, default_Tornado_method);
        printf( "   -z      -- force compression\n"
                "   -d      -- force decompression\n"
                "   -oNAME  -- output filename/directory (default %s/%s)\n", COMPRESS_EXT, DECOMPRESS_EXT);
        printf( "   -t      -- test (de)compression (redirect output to nul)\n"
                "   -delete -- delete successfully (de)compressed input files\n"
#ifdef FREEARC_NO_TIMING
                "   -q      -- be quiet; -q[hr]* disables header/results individually\n"
#else
                "   -q      -- be quiet; -q[thpr]* disables title/header/progress/results individually\n"
                "   -cpu    -- compute raw CPU time (for benchmarking)\n"
#endif
#ifdef FREEARC_WIN
                "   -slp[+/-/]   -- force/disable/try(default) large pages support (2mb/4mb)\n"
#endif
                "   -rem... -- command-line remark\n"
                "   -h      -- display this help\n"
                "   --      -- stop flags processing\n"
                " \"-\" used as filename means stdin/stdout\n"
                "\n"
                " Advanced compression parameters:\n"
                "   -b#     -- buffer size (%s..%s), default %s\n", MinBufSizeStr, MaxBufSizeStr, b);
        printf( "   -h#     -- hash size (%s..%s-1), default %s\n", MinHashSizeStr, MaxHashSizeStr, h);
        printf( "   -l#     -- length of hash row (1..%d), default %d\n", int(MAX_HASH_ROW_WIDTH), r.method.hash_row_width);
        printf( "   -ah#    -- auxiliary hash size (%s..%s-1), default %s\n", MinHashSizeStr, MaxHashSizeStr, ah);
        printf( "   -al#    -- auxiliary hash row length (1..%d), default %d\n", int(MAX_HASH_ROW_WIDTH), r.method.auxhash_row_width);
        printf( "   -u#     -- update step (1..%d), default %d\n", int(MAX_UPDATE_STEP), r.method.update_step);
        printf( "   -c#     -- coder (1-bytes, 2-bits, 3-huf, 4-arith), default %d\n", r.method.encoding_method);
        printf( "   -p#     -- parser (1-greedy, 2-lazy, 4-optimal), default %d\n", r.method.match_parser);
        printf( "   -x#     -- match finder (0: non-caching ht4, 4-7: cycling cached ht4..ht7,\n"
                "                            14-17: shifting cached ht4..ht7, 24-27: bt4..bt7), default %d\n", r.method.caching_finder);
        printf( "   -s#     -- 2/3-byte hash (0-disabled, 1-fast, 2-max), default %d\n", r.method.hash3);
        printf( "   -t#     -- table diffing (0-disabled, 1-enabled), default %d\n", r.method.find_tables);
        printf( "   -fb#    -- fast bytes in the optimal parser (%d..%d), default %d\n", int(MIN_FAST_BYTES), int(MAX_FAST_BYTES), r.method.fast_bytes);
        printf( "\n"
                " Predefined methods:\n");
        for (int i=1; i<elements(std_Tornado_method); i++)
        {
            printf("   %-8d-- %s\n", -i, name(std_Tornado_method[i]));
        }
        exit(EXIT_SUCCESS);
    }



    // (De)compress all files given on cmdline
    bool parse_options=TRUE;  // options will be parsed until "--"
    Install_signal_handler(signal_handler);

    for (char **parameters = argv; *++parameters!=NULL; )
    {
        // If options are still parsed and this argument starts with "-" - it's an option
        if (parse_options && parameters[0][0]=='-' && parameters[0][1]) {
            if (strequ(*parameters,"--"))  parse_options=FALSE;
            continue;
        }

        // Save input filename
        r.filename = *parameters;

        // Select operation mode if it was not specified on cmdline
        r.mode = global_mode != AUTO?                  global_mode :
                 end_with (r.filename, COMPRESS_EXT)?  _DECOMPRESS  :
                                                       _COMPRESS;
        // Extension that should be added to output filenames
        const char *MODE_EXT  =  r.mode==_COMPRESS? COMPRESS_EXT : DECOMPRESS_EXT;

        // Construct output filename
        if (r.mode==BENCHMARK  ||  output_filename && strequ (output_filename, "")) {  // Redirect output to nul
            strcpy (r.outname, "");
        } else if (output_filename) {
            if (strequ(output_filename,"-"))
                strcpy (r.outname, output_filename);
            else if (is_path_char (last_char (output_filename)))
                {sprintf(r.outname, "%s%s", output_filename, drop_dirname(r.filename));  goto add_remove_ext;}
            else if (dir_exists (output_filename))
                {sprintf(r.outname, "%s%c%s", output_filename, PATH_DELIMITER, drop_dirname(r.filename));  goto add_remove_ext;}
            else
                strcpy (r.outname, output_filename);
        } else if (strequ(r.filename,"-")) {
            strcpy (r.outname, r.filename);
        } else {
            // No output filename was given on cmdline:
            //    on compression   - add COMPRESS_EXT
            //    on decompression - remove COMPRESS_EXT (and add DECOMPRESS_EXT if file already exists)
            strcpy (r.outname, r.filename);
add_remove_ext: // Remove COMPRESS_EXT on the end of name or add DECOMPRESS_EXT (unless we are in _COMPRESS mode)
            if (r.mode!=_COMPRESS && end_with (r.outname, COMPRESS_EXT)) {
                r.outname [strlen(r.outname) - strlen(COMPRESS_EXT)] = '\0';
                if (file_exists (r.outname))
                    strcat(r.outname, MODE_EXT);
            } else {
                strcat(r.outname, MODE_EXT);
            }
        }

        // Open input file
        r.fin = strequ (r.filename, "-")? stdin : file_open_read_binary(r.filename);
        if (r.fin == NULL) {
            fprintf (stderr, "\n Can't open %s for read\n", r.filename);
            exit(FREEARC_EXIT_ERROR);
        }
        set_binary_mode (r.fin);

        // Open output file
        if (*r.outname) {
          r.fout = strequ (r.outname, "-")? stdout : file_open_write_binary(r.outname);
          if (r.fout == NULL) {
              fprintf (stderr, "\n Can't open %s for write\n", r.outname);
              exit(FREEARC_EXIT_ERROR);
          }
          set_binary_mode (r.fout);
        } else {
          r.fout = NULL;
        }

        // Prepare to (de)compression
        int result;  char filesize_str[100];
        start_print_stats(r);

        // Perform actual (de)compression
        switch (r.mode) {
        case _COMPRESS: {
            if (!r.quiet_header && r.filesize >= 0)
                fprintf (stderr, "Compressing %s bytes with %s\n", show3(r.filesize,filesize_str), name(r.method));
            PackMethod m = r.method;
            if (r.filesize >= 0)
                m.buffer = mymin (m.buffer, r.filesize+LOOKAHEAD*2);
            result = tor_compress (m, ReadWriteCallback, &r, NULL, -1);
            break; }

        case _DECOMPRESS: {
            //if (!r.quiet_header && !strequ (r.outname, "-"))   fprintf (stderr, "Unpacking %.3lf mb\n", double(r.filesize)/1000/1000);
            result = tor_decompress (ReadWriteCallback, &r, NULL, -1);
            break; }
        }

        // Finish (de)compression
        print_final_stats(r);
        fclose (r.fin);
        if (r.fout)  fclose (r.fout);

        if (result == FREEARC_OK)  {
            if (delete_input_files && !strequ(r.filename,"-"))    delete_file(r.filename);
        } else {
            if (!strequ(r.outname,"-") && !strequ(r.outname,""))  delete_file(r.outname);
            switch (result) {
            case FREEARC_ERRCODE_INVALID_COMPRESSOR:
                fprintf (stderr, "\nThis compression mode isn't supported by small Tornado version, use full version instead!");
                break;
            case FREEARC_ERRCODE_NOT_ENOUGH_MEMORY:
                fprintf (stderr, "\nNot enough memory for (de)compression!");
                break;
            case FREEARC_ERRCODE_READ:
                fprintf (stderr, "\nRead error! Bad media?");
                break;
            case FREEARC_ERRCODE_WRITE:
                fprintf (stderr, "\nWrite error! Disk full?");
                break;
            case FREEARC_ERRCODE_BAD_COMPRESSED_DATA:
                fprintf (stderr, "\nData can't be decompressed!");
                break;
            default:
                fprintf (stderr, "\n(De)compression failed with error code %d!", result);
                break;
            }
            exit(FREEARC_EXIT_ERROR);
        }

        // going to next file...
    }

    return EXIT_SUCCESS;
}