Ejemplo n.º 1
0
Archivo: cron.c Proyecto: dank101/3BSD
main()
{
	register char *cp;
	char *cmp();
	time_t filetime = 0;

	setuid(1);
	if (fork())
		exit(0);
	chdir("/");
	freopen(crontab, "r", stdin);
	freopen("/", "r", stdout);
	freopen("/", "r", stderr);
	signal(SIGHUP, SIG_IGN);
	signal(SIGINT, SIG_IGN);
	signal(SIGQUIT, SIG_IGN);
	time(&itime);
	itime -= localtime(&itime)->tm_sec;
	fclose(stdin);

	for (;; itime+=60, slp()) {
		struct stat cstat;

		if (stat(crontab, &cstat) == -1)
			continue;
		if (cstat.st_mtime > filetime) {
			filetime = cstat.st_mtime;
			init();
		}
		loct = localtime(&itime);
		loct->tm_mon++;		 /* 1-12 for month */
		for(cp = list; *cp != EOS;) {
			flag = 0;
			cp = cmp(cp, loct->tm_min);
			cp = cmp(cp, loct->tm_hour);
			cp = cmp(cp, loct->tm_mday);
			cp = cmp(cp, loct->tm_mon);
			cp = cmp(cp, loct->tm_wday);
			if(flag == 0) {
				slp();
				ex(cp);
			}
			while(*cp++ != 0)
				;
		}
	}
}
Ejemplo n.º 2
0
main()
{
	register i, t;
	register char *cp;
	extern char end[];

	setuid(1);
	itime[0] = fork();
	if(itime[0])
		exit();
	setexit();
	signal(1, reset);
	time(itime);
	while(*localtime(itime))
		if(itime[1]-- == 0)
			itime[0]--;

loop:
	init();
	for(i=60; i; i--) {
		loct = localtime(itime);
		for(cp = end; *cp != EOF;) {
			flag = 0;
			cp = cmp(cp, loct[1]); /* minute */
			cp = cmp(cp, loct[2]); /* hour */
			cp = cmp(cp, loct[3]); /* day */
			cp = cmp(cp, loct[4]); /* month */
			cp = cmp(cp, loct[6]); /* day of week */
			if(flag == 0) {
				slp();
				ex(cp);
			}
			while(*cp++ != 0)
				;
		}
		t = itime[1] + 60;
		if(t < itime[1])
			itime[0]++;
		itime[1] = t;
	}
	slp();
	goto loop;
}
Ejemplo n.º 3
0
void testlockpoolset()
{
	typedef typename LIBCXX_NAMESPACE::multilockpool<std::string, starve>
		::lockpool_t stringlockpool;

	stringlockpool slp(stringlockpool::create());

	std::set<std::string> container1, container2, container3;

	container1.insert("A");
	container2.insert("A");
	container2.insert("B");
	container3.insert("B");

	typename stringlockpool::base::lockentryptr lock1=
		slp->addLockSet(container1, LIBCXX_NAMESPACE::eventfd::create());

	std::cout << "multilock1: " << lock1->locked() << std::endl;

	typename stringlockpool::base::lockentryptr lock2=
		slp->addLockSet(container2, LIBCXX_NAMESPACE::eventfd::create());

	std::cout << "multilock2: " << lock2->locked() << std::endl;

	typename stringlockpool::base::lockentryptr lock3=
		slp->addLockSet(container3, LIBCXX_NAMESPACE::eventfd::create());

	std::cout << "multilock3: " << lock3->locked() << std::endl;

	lock1=typename stringlockpool::base::lockentryptr();

	std::cout << "multilock2: " << lock2->locked() << std::endl;

	if (!lock2->locked())
	{
		std::cout << "multilock3: " << lock3->locked() << std::endl;
		lock3=typename stringlockpool::base::lockentryptr();
		std::cout << "multilock2: " << lock2->locked() << std::endl;
	}
	else
	{
		std::cout << "multilock3: " << lock3->locked() << std::endl;
		lock2=typename stringlockpool::base::lockentryptr();
		std::cout << "multilock3: " << lock3->locked() << std::endl;
	}
}
Ejemplo n.º 4
0
CSmartSocketFactory::CSmartSocketFactory(const char *_socklist, bool _retry, unsigned _retryInterval, unsigned _dnsInterval)
{
    PROGLOG("CSmartSocketFactory::CSmartSocketFactory(%s)",_socklist?_socklist:"NULL");
    SmartSocketListParser slp(_socklist);
    if (slp.getSockets(sockArray) == 0)
        throw createSmartSocketException(0, "no endpoints defined");

    shuffleEndpoints();

    nextEndpointIndex = 0;
    dnsInterval=_dnsInterval;

    retry = _retry;
    if (retry)
    {
        retryInterval = _retryInterval;
        this->start();
    }
}
Ejemplo n.º 5
0
int main(int argc, char * argv[]){
  string s,t, line, alphabet;
  vector<pair<uInt,uInt> > vars;
  // read entire file //////////////////////////////
  ifstream f(argv[1], fstream::in);
  while(f.good()){
    char c = f.get();
    if(f.good()){ s.push_back(c); }
  }
  f.close();
  //////////////////////////////////////////////////

  MFF::calc(s, alphabet, vars);
  SLP slp(alphabet, vars);
  slp.toString(t);
  if(s != t){
    cerr << "ERROR: INPUT/OUTPUT mismatch!" << endl;
    cerr << "Input : '" << s << "'" << endl;
    cerr << "Output: '" << t << "'" << endl;
  } else {
    slp.output(cout);
  }
  return 0;
}
Ejemplo n.º 6
0
void get_FdF_simple( int nlhs, mxArray *plhs[],
                     int nrhs, const mxArray *prhs[])
{
int N,M,I;

int elements, nsubs;
double *output1, *output2, *output3;
//mwIndex id, idv;

const double epsilon = 0.0000001;
const double rEpsilon = 1./epsilon;

char buffer[256];

  I     = (int) *mxGetPr(prhs[0]);
  N     = (int) *mxGetPr(prhs[1]);
  M     = (int) *mxGetPr(prhs[2]);

if (nlhs != 1 && nlhs != 2 && nlhs != 3)
  mexErrMsgTxt("Must have 1 or 2 or 3 output arguments");

//Edge-Weights W; Righthand Side B; Vertex Scales S; Init Solution D
//if (nrhs !=U+7)
//  mexErrMsgTxt("Must have amount of unknowns (U)+7 input arguments");

/* prevent you from passing a sparse matrix,
a string matrix, or a complex array. mxIsComplex
is used to determine if there is an imaginary
part of the mxArray. mxIsClass is used to determine
if the mxArray belongs to a particular class */
if ( mxIsComplex(prhs[3])|| mxIsClass(prhs[3],"sparse") || mxIsChar(prhs[3]) )
  mexErrMsgTxt("Input must be real, full, and nonstring");

// Get the number of elements in the input argument
elements=mxGetNumberOfElements(prhs[3]);

sprintf (buffer, "The amount of elements in the matrix is not equal to the amount given by the specified dimensions!\n all: %d product %d   N: %d, M: %d\n", elements, N*M, N, M);
if (elements != N*M)
  mexErrMsgTxt(buffer);

// Get the number of dimensions in array
nsubs=mxGetNumberOfDimensions(prhs[3]);

// Jacobi:
double *weightsH(NULL), *weightsV(NULL), *b1, *b2, *b3, *x1, *x2, *x3;//, *dualW, *scales;
int *validMap(NULL), *invalidMap(NULL);
validMap = (int*) mxGetPr(prhs[3]);

// could be done as well BUT NOT NEEDED CURRENTLY

#ifdef USE_INVALIDS
invalidMap = (int*) mxGetPr (prhs[4]);
#define ADD_TO 1
#else
#ifdef USE_WEIGHTS
weightsH = mxGetPr(prhs[4]); // edge weights
weightsV = mxGetPr(prhs[5]); // edge weights
#  define ADD_TO 2
#else
#  define ADD_TO 0
#endif
#endif


// confusing non-sense: b is not b but always 0
// the b is used as a initial value for x !!!

// x1 is never used as initial solution - just the masked part is filled with x1 

//dualW    = mxGetPr(prhs[8]);
b1        = mxGetPr(prhs[4+ADD_TO]);
x1        = mxGetPr(prhs[5+ADD_TO]);

int rhs = 1;

if (nrhs >= 8+ADD_TO)
  rhs = 2;
if (nrhs >= 10+ADD_TO)
  rhs = 3;

//printf("RHS: %d", nrhs);

b2 = b1;
b3 = b1;
x2 = x1;
x3 = x1;

if (rhs > 1)
{
  b2        = mxGetPr(prhs[6+ADD_TO]);
  x2        = mxGetPr(prhs[7+ADD_TO]);
}
if (rhs > 2)
{
  b3        = mxGetPr(prhs[8+ADD_TO]);
  x3        = mxGetPr(prhs[9+ADD_TO]);
}

// Create the output array(s)
plhs[0] = mxCreateDoubleMatrix(N, M, mxREAL);
output1 = mxGetPr(plhs[0]);
memcpy(output1, x1, sizeof(double)*N*M);

if (nlhs >= 2)
{
  plhs[1] = mxCreateDoubleMatrix(N, M, mxREAL);
  output2 = mxGetPr(plhs[1]);
  memcpy(output2, x2, sizeof(double)*N*M);
}
if (nlhs >= 3)
{
  plhs[2] = mxCreateDoubleMatrix(N, M, mxREAL);
  output3 = mxGetPr(plhs[2]);
  memcpy(output3, x3, sizeof(double)*N*M);
}

//printf("N %d, M %d -- nlhs %d, rhs %d \n",N, M, nlhs, rhs);

if (nlhs == 1)
{
  SolveLaplace<1> slp( N, M, b1, validMap, output1);
  if (weightsH != 0 )
    slp.setWeights( weightsH, weightsV );
  if (invalidMap != NULL)
    slp.setInvalid(invalidMap);

  slp.setup_Matrix( I );
}
if (nlhs == 2)
{
  SolveLaplace<2> slp( N, M, b1, b2, validMap, output1, output2);
  if (weightsH != 0 )
    slp.setWeights( weightsH, weightsV );
  if (invalidMap != NULL)
    slp.setInvalid(invalidMap);
  slp.setup_Matrix( I );
}
if (nlhs == 3)
{
  SolveLaplace<3> slp( N, M, b1, b2, b3, validMap, output1, output2, output3);
  if (weightsH != 0 )
    slp.setWeights( weightsH, weightsV );
  if (invalidMap != NULL)
    slp.setInvalid(invalidMap);
  slp.setup_Matrix( I );
}
}
Ejemplo n.º 7
0
int sindexcombined(char *slopefile,  char *scaterrainfile, char *scarminroadfile, char* scarmaxroadfile,
           char *tergridfile, char *terparfile, char *satfile, char* sincombinedfile, double Rminter, double Rmaxter, 
		   double *par)
{	
	MPI_Init(NULL,NULL);{
	FILE *fp;
	int i, j, mter, err, filetype, index, rno, nx, ny;
	float ndva, ndvs;
	short *ndvter;
	int nor;
	double X1, X2, cellsat, dx, dy;
	float rs, rw, g;
	float tmin, tmax, cmin, cmax, tphimin, tphimax;
  
	const double PI = 3.14159265358979;

	struct calreg{
		float tmin;
		float tmax;
		float cmin;
		float cmax;
		float tphimin;
		float tphimax;
		float r;
	} ;  /* this could be malloced or should be checked
                    to ensure fewer than 100 regions */
	g=par[0];
	rw=par[1];
	nor = 0;
	
	struct calreg *region;	

	char headers[MAXLN];

	// find number of regions
	fp = fopen(terparfile, "r");
	if (fp == NULL)return 15;

	// Pabitra (9/10/2015): the following code to count the number of lines 
	// handles if the last line does not end with end of line character
	while ( fgets ( headers, sizeof headers, fp) != NULL)
	{
		nor++;
	}
	/*while (readline(fp,headers) != EOF)
	{
		nor++;
	}*/
	(std::fclose)(fp);

	// number of regions is  total lines in the file minus 1 (for the header text line)
	nor = nor - 1;
		
	region = (calreg*)calloc(nor, sizeof(calreg));
	getRegionIndex(terparfile, nor);

	fp = fopen(terparfile, "r");	
	readline(fp,headers);
	//  i = -1;  DGT 12/31/14 Not needed
	index = 0;
	do
	{
		j = fscanf(fp,"%i,%f,%f,%f,%f,%f,%f,%f \n", &rno, &tmin,
					&tmax, &cmin, &cmax,  &tphimin, &tphimax, &rs);
		
		region[index].tmin = tmin;
		region[index].tmax = tmax;
		region[index].cmin  = cmin;
		region[index].cmax  = cmax;
		region[index].tphimin =tphimin * PI/180 ;
		region[index].tphimax = tphimax * PI/180;
		region[index].r = rw/rs;
		index++;
	}while (index < nor);

	(std::fclose)(fp);

	//MPI_Init(NULL,NULL);{

	int rank, size;
	MPI_Comm_rank(MCW, &rank);
	MPI_Comm_size(MCW, &size);
	if(rank == 0) printf("SinmapSI version %s\n", TDVERSION);

	double begin,end;
	//Begin timer
	begin = MPI_Wtime();

	//Create tiff object, read and store header info
	tiffIO slp(slopefile, FLOAT_TYPE);
	long totalX = slp.getTotalX();
	long totalY = slp.getTotalY();
	dx = slp.getdxA();
	dy = slp.getdyA();	
	
	tiffIO sca(scaterrainfile, FLOAT_TYPE);

	tiffIO *sca_min = NULL;
	if (*scarminroadfile != NULL)
	{
		sca_min = new tiffIO(scarminroadfile, FLOAT_TYPE);		
	}
	
	tiffIO *sca_max = NULL;
	if (*scarmaxroadfile != NULL)
	{
		sca_max = new tiffIO(scarmaxroadfile, FLOAT_TYPE);		
	}
		
	tiffIO cal(tergridfile, SHORT_TYPE);

	if(rank==0)
	{
		float timeestimate=(1e-7*totalX*totalY/pow((double) size,1))/60+1;  // Time estimate in minutes
		fprintf(stderr,"This run may take on the order of %.0f minutes to complete.\n",timeestimate);
		fprintf(stderr,"This estimate is very approximate. \nRun time is highly uncertain as it depends on the complexity of the input data \nand speed and memory of the computer. This estimate is based on our testing on \na dual quad core Dell Xeon E5405 2.0GHz PC with 16GB RAM.\n");
		fflush(stderr);
	}

	
	//Create partition and read data from slope file
	tdpartition *slpData;
	slpData = CreateNewPartition(slp.getDatatype(), totalX, totalY, dx, dy, slp.getNodata());
	nx = slpData->getnx();
	ny = slpData->getny();
	ndvs = *(float*)slp.getNodata();	
	int xstart, ystart;
	slpData->localToGlobal(0, 0, xstart, ystart);
	// TODO: put similar comments for the other savedxdyc() function used in this function
	// for a complete slpData partition would need to run slpData->savedxdyc(slp) to save lat variable cell sizes
	// here not done as cell size not needed
	//slpData->savedxdyc(slp);

	slp.read(xstart, ystart, ny, nx, slpData->getGridPointer());

	//Create partition and read data from clibration grid file
	tdpartition *calData;
	calData = CreateNewPartition(cal.getDatatype(), totalX, totalY, dx, dy, -1);
	calData->localToGlobal(0, 0, xstart, ystart);
	calData->savedxdyc(cal);
	cal.read(xstart, ystart, ny, nx, calData->getGridPointer());
			
	ndvter = (short*)cal.getNodata();	
			
	//Create partition and read data from sca grid file
	tdpartition *scaData;
	scaData = CreateNewPartition(sca.getDatatype(), totalX, totalY, dx, dy, sca.getNodata());
	scaData->localToGlobal(0, 0, xstart, ystart);
	scaData->savedxdyc(sca);
	sca.read(xstart, ystart, ny, nx, scaData->getGridPointer());

	//Create partition and read data from sca min grid file
	tdpartition *scaMinData = NULL;
	if (sca_min != NULL)
	{		
		scaMinData = CreateNewPartition(sca_min->getDatatype(), totalX, totalY, dx, dy, sca_min->getNodata());
		scaMinData->localToGlobal(0, 0, xstart, ystart);
		scaMinData->savedxdyc(*sca_min);
		sca_min->read(xstart, ystart, ny, nx, scaMinData->getGridPointer());
	}
	
	//Create partition and read data from sca max grid file
	tdpartition *scaMaxData = NULL;
	if(sca_max != NULL)
	{		
		scaMaxData = CreateNewPartition(sca_max->getDatatype(), totalX, totalY, dx, dy, sca_max->getNodata());
		scaMaxData->localToGlobal(0, 0, xstart, ystart);
		scaMaxData->savedxdyc(*sca_max);
		sca_max->read(xstart, ystart, ny, nx, scaMaxData->getGridPointer());
	}
	

	short cal_cell_value = 0;
	float slope_cell_value = 0;
	float sca_cell_value = 0;
	float sca_min_cell_value = 0;
	float sca_max_cell_value = 0;
	float csi_data = 0;
	int region_index = 0;

	//Create empty partition to store csi data
	tdpartition *csiData;
	csiData = CreateNewPartition(FLOAT_TYPE, totalX, totalY, dx, dy, -1.0f);

	//Create empty partition to store sat data
	tdpartition *satData;
	satData = CreateNewPartition(FLOAT_TYPE, totalX, totalY, dx, dy, -1.0f);

	//Share information and set borders to zero
	slpData->share();
	scaData->share();
	if(scaMinData != NULL)
	{
		scaMinData->share();
	}
	
	if(scaMaxData != NULL)
	{
		scaMaxData->share();
	}

	calData->share();
	csiData->clearBorders();
	satData->clearBorders();	
	
	for(j = 0; j < ny; j++) {
		for(i = 0; i < nx; i++ ) {
			calData->getData(i, j, cal_cell_value);
			slpData->getData(i, j, slope_cell_value);
			scaData->getData(i, j, sca_cell_value);
			if(scaMinData != NULL)
			{
				scaMinData->getData(i, j, sca_min_cell_value);
			}

			if(scaMaxData != NULL)
			{
				scaMaxData->getData(i, j, sca_max_cell_value);
			}
			
			region_index = findRegIndex(cal_cell_value, nor, *ndvter);
			
			//  DGT 12/31/14.  Changed the logic below from region_index < *ndvter to region_index < 0 to allow for *ndvter to be positive
			if (region_index < 0 || sca_cell_value < 0 || sca_min_cell_value < 0 || sca_max_cell_value < 0 || slope_cell_value == ndvs){
				csiData->setToNodata(i, j);
				satData->setToNodata(i, j);				
			}
			else{
				
				if(Rmaxter != 0 || sca_max_cell_value != 0){
					X2 = (sca_cell_value * Rmaxter + sca_max_cell_value)/region[region_index].tmin;
					X1 = (sca_cell_value * Rminter + sca_min_cell_value)/region[region_index].tmax;	
					csi_data = (float)sindexcell(slope_cell_value, 1,
								region[region_index].cmin, region[region_index].cmax, 
								region[region_index].tphimin, region[region_index].tphimax,
								X1, X2, region[region_index].r, &cellsat);
				
									
					csiData->setData(i, j, csi_data);
					satData->setData(i, j, float(cellsat));
					
				}				
			}				
		}
	}
	
	//  DGT 12/31/14 commented passing of borders.  This function acts locally so does not need any border sharing
	//Pass information
	//csiData->addBorders();		
	//satData->addBorders();	

	//Clear out borders
	//csiData->clearBorders();
	//satData->clearBorders();

	//Stop timer
	end = MPI_Wtime();
 	double compute, temp;
    compute = end-begin;

    MPI_Allreduce (&compute, &temp, 1, MPI_DOUBLE, MPI_SUM, MCW);
    compute = temp/size;

    if( rank == 0)
	{
		printf("Compute time: %f\n",compute);		
	}

	//Create and write to the csi TIFF file
	float aNodata = -1.0f;
	tiffIO csi(sincombinedfile, FLOAT_TYPE, &aNodata, slp);
	csi.write(xstart, ystart, ny, nx, csiData->getGridPointer());
	//Create and write to the sat TIFF file
	tiffIO sat(satfile, FLOAT_TYPE, &aNodata, slp);
	sat.write(xstart, ystart, ny, nx, satData->getGridPointer());

	}MPI_Finalize();

	return 0;
}
Ejemplo n.º 8
0
int main(int argc, char * argv[]){
  int opt;
  bool err = false;
  string inputFilename, outputFilename, line;
  uInt gramLen = 2;
  enum AlgoType atype = NONE;
  enum InputType itype = INPUT_SLP;
  bool sort_output = false;
  while((opt = getopt(argc, argv, "hcnxsq:f:ta:")) != -1){
    switch(opt){
    case 'h': display_usage(argc, argv); return 0; break;
    case 'q': gramLen = atoi(optarg); break;
    case 'f': inputFilename = optarg; break;
    case 't': itype = INPUT_PLAINTEXT; break; 
    case 's': sort_output = true; break;
    case 'a':
      if(atoi(optarg) <= 4) atype = static_cast<enum AlgoType>(atoi(optarg)); break;
    default: err = true;
    }
  }
  if(atype == NONE){ 
    cerr << "ERROR: algorithm type (1 - 4) must be specified with -a" << endl;
    err = true; 
  }
  if(err){
    display_usage(argc, argv);
    return 1;
  }
  posfreq rp;
  gramfreq rg;
  string t;
  vector<posfreq> pfs;
  string str;
  str.clear();
  vector<uInt> weights;
  std::map<substr, uInt, substrCmp> * counts = NULL;
  if (itype == INPUT_PLAINTEXT){
    ifstream ifile(inputFilename.c_str(), fstream::in);
    while(ifile.good()){
      char c = ifile.get();
      if(ifile.good()){ str.push_back(c); }
    }
    if (atype == NAIVE_GRAMMAP){ // NMP
      substrCmp compclass(str);
      counts = new std::map<substr, uInt, substrCmp>(compclass);
      // std::map<substr, uInt, substrCmp>  counts1(compclass);
      qgramGM::Frequent(gramLen, str, *counts);
    }else if (atype == NAIVE_SUFFIXARRAY){ // NSA
      SuffixArrayAux SA(str);
      qgramSA::Frequent(SA, gramLen, pfs);
    }else{
      assert(atype > 2);
    }
  }else{
    SLPFastQgramStats slp(inputFilename.c_str());
    if (atype == NAIVE_SUFFIXARRAY){ // nsa
      slp.toString(str);
      SuffixArrayAux SA(str);
      qgramSA::Frequent(SA, gramLen, pfs);
    }else if (atype == NAIVE_GRAMMAP){ // nmp
      slp.toString(str);
      substrCmp compclass(str);
      counts = new std::map<substr, uInt, substrCmp>(compclass);
      // std::map<substr, uInt, substrCmp>  counts1(compclass);
      qgramGM::Frequent(gramLen, str, *counts);
    }else { // for slp
      slp.prepare(gramLen);
      qgramSLPFast::makeGramStrWeights(slp, str, weights);
      if (atype == SLP_GRAMMAP){ //smp
        substrCmp compclass(str);
        counts = new std::map<substr, uInt, substrCmp>(compclass);
        qgramWGM::Frequent(gramLen, str, weights, *counts);
      }else if (atype == SLP_SUFFIXARRAY){ // ssa
        SuffixArrayAux slpSA(str);
        qgramSA::Frequent(slpSA, gramLen, weights, pfs);

      }
    }
  }

  if (atype == NAIVE_GRAMMAP || atype == SLP_GRAMMAP){
    if (!sort_output){
      map<substr, uInt, substrCmp>::const_iterator itr;
      for(itr = counts->begin(); itr != counts->end(); itr++){
        const substr & s = (*itr).first;
        cout << "\"" << str.substr(s.p, gramLen) << "\","
             << (*itr).second << endl;
      }
    }else{
      vector<gramfreq> gfs;
      map<substr, uInt, substrCmp>::const_iterator itr;
      for(itr = counts->begin(); itr != counts->end(); itr++){
        gramfreq gf;
        gf.gram = str.substr((*itr).first.p, gramLen);
        gf.freq = (*itr).second;
        gfs.push_back(gf);
      }
      // cout << "gfs.size()=" << gfs.size() << " counts.size()" << counts->size() << endl;
      sort(gfs.begin(), gfs.end(), greater<gramfreq>());
      for(uInt i = 0; i < gfs.size(); i++){
        cout << "\"" << gfs[i].gram << "\","
             << gfs[i].freq << endl;
      }
    }
  }else{
    if (sort_output) sort(pfs.begin(), pfs.end(), greater<posfreq>());
    for(uInt i = 0; i < pfs.size(); i++){
      cout << "\"" << str.substr(pfs[i].pos, gramLen) << "\","
           << pfs[i].freq << endl;
    }
  }
  return 0;
}
int main(int argc, char * argv[]){
  int opt;
  bool err = false;
  string inputFilename, outputFilename, line, inputString;
  uInt gramLen = 2;
  enum AlgoType atype = NONE;
  enum InputType itype = INPUT_SLP;
  while((opt = getopt(argc, argv, "hcnxsq:f:ta:")) != -1){
    switch(opt){
    case 'h': display_usage(argc, argv); return 0; break;
    case 'q': gramLen = atoi(optarg); break;
    case 'f': inputFilename = optarg; break;
    case 't': itype = INPUT_PLAINTEXT; break; 
    case 'a':
      if(atoi(optarg) <= 4) atype = static_cast<enum AlgoType>(atoi(optarg)); break;
    default: err = true;
    }
  }
  if(atype == NONE){ 
    cerr << "ERROR: algorithm type (1 - 4) must be specified with -a" << endl;
    err = true; 
  }
  if(err){
    display_usage(argc, argv);
    return 1;
  }
  posfreq rp;
  gramfreq rg;
  string t;
  if(itype == INPUT_PLAINTEXT){
    ifstream ifile(inputFilename.c_str(), fstream::in);
    while(ifile.good()){
      char c = ifile.get();
      if(ifile.good()){ inputString.push_back(c); }
    }
    if (atype == NAIVE_GRAMMAP){ // NMP
      rp = qgramGM::mostFrequent(gramLen, inputString);
    }else if (atype == NAIVE_SUFFIXARRAY){ // NSA
      SuffixArrayAux SA(inputString);
      rp = qgramSA::mostFrequent(SA, gramLen);
    }else{
      assert(atype > 2);
    }
    rg.gram = inputString.substr(rp.pos, gramLen);
    rg.freq = rp.freq;
  } else { // SLP
    string str;
    vector<uInt> weights;
    SLPFastQgramStats slp(inputFilename.c_str());
    if (atype == NAIVE_GRAMMAP){
      slp.toString(str);
      rp = qgramGM::mostFrequent(gramLen, str);
    }else if (atype == NAIVE_SUFFIXARRAY){
      slp.toString(str);
      SuffixArrayAux SA(str);
      rp = qgramSA::mostFrequent(SA, gramLen);
    }else{
      slp.prepare(gramLen);
      qgramSLPFast::makeGramStrWeights(slp, str, weights);
      // cout << "str.size() = " << str.size() << " weights.size() = " << weights.size() << endl;
      if( atype == SLP_GRAMMAP){ // SMP
        rp = qgramWGM::mostFrequent(gramLen, str, weights);
        // rp = qgramWGM::mostFrequentEnd(gramLen, str, weights);
      }else if (atype == SLP_SUFFIXARRAY){  // SSA
        SuffixArrayAux slpSA(str);
        rp = qgramSA::mostFrequent(slpSA, gramLen, weights);
        // rp = qgramSA::mostFrequentEnd(slpSA, gramLen, weights);
      }
    }
    rg.gram = str.substr(rp.pos, gramLen);
    rg.freq = rp.freq;
  }
  struct rusage r;
  getrusage(RUSAGE_SELF, &r);
  cout << "rg.gram=[" << rg.gram << "] freq=" << rg.freq << endl;
  return 0;
}