Пример #1
0
/**
 * Pan is linear, from -1 to 1. 0 is in the middle.
 */
static void setPan(ALuint source, float pan)
{
    float pos[3];

    vectors((float) (headYaw - pan * PI / 2), headPitch, pos, 0);
    alSourcefv(source, AL_POSITION, pos);
}
Пример #2
0
void    KPCA::computeEigens(bool centering) {
    eigens.clear();
    std::vector<double> vectors(dim*dim),lambdas(dim);

    memcpy(&vectors[0],gram,sizeof(double)*dim*dim);
    if (centering)
    {
        std::cout << "kpca => centering" << std::endl;
        matrix_sym_centering_double (&vectors[0],dim,NULL);
    }

    matrix_eigSym_double(&vectors[0],&lambdas[0],dim);
    
    double max = 0;
    for (size_t r=0;r<dim;r++) {
        if (fabs(lambdas[r]) > max)
            max = fabs(lambdas[r]);
    }
    if (max < 1E-7)
        return;
    for (size_t r=0;r<dim;r++) {
        if (fabs(lambdas[r]) > 1E-6*max) {
            eigens.push_back(Eigen(lambdas[r],&vectors[r*dim],dim));
        }
    }
}
Пример #3
0
// Constructor creates an instance of the spline class with tvector data given.
spline::spline (tvector<nr_double_t> y, tvector<nr_double_t> t) {
    x = f0 = f1 = f2 = f3 = NULL;
    d0 = dn = 0;
    n = 0;
    boundary = SPLINE_BC_NATURAL;
    vectors (y, t);
    construct ();
}
Пример #4
0
// Constructor creates an instance of the spline class with vector data given.
spline::spline (vector y, vector t) {
    x = f0 = f1 = f2 = f3 = NULL;
    d0 = dn = 0;
    n = 0;
    boundary = SPLINE_BC_NATURAL;
    vectors (y, t);
    construct ();
}
Пример #5
0
    /// Writes the results, according to the given flags
    class_type& write(size_t numResults, ff_string_slice_t const* results, int flags)
    {
        stlsoft::auto_buffer<iovec>     vectors(numResults + 2);
        ff_string_slice_t               crlf = fastformat_getNewlineForPlatform();

#ifdef STLSOFT_CF_THROW_BAD_ALLOC
        if(!vectors.empty())
#endif /* STLSOFT_CF_THROW_BAD_ALLOC */
        {
            STLSOFT_ASSERT(vectors.size() == numResults + 2);

            { for(size_t i = 0; i != vectors.size() - 2; ++i)
            {
                vectors[i].iov_base =   const_cast<char*>(results[i].ptr);
                vectors[i].iov_len  =   results[i].len;
            }}

            if(!m_delim.empty())
            {
                vectors[vectors.size() - 2].iov_base    =   const_cast<char*>(m_delim.data());
                vectors[vectors.size() - 2].iov_len     =   m_delim.size();
            }
            else
            {
                vectors.resize(vectors.size() - 1);
            }

            if(flags::ff_newLine & flags)
            {
                vectors[vectors.size() - 1].iov_base    =   const_cast<char*>(crlf.ptr);
                vectors[vectors.size() - 1].iov_len     =   crlf.len;
            }
            else
            {
                vectors.resize(vectors.size() - 1);
            }

            if(::writev(m_fh, &vectors[0], static_cast<int>(vectors.size())) < 0)
            {
#ifdef STLSOFT_CF_EXCEPTION_SUPPORT
                throw platformstl::platform_exception("failed to write vector payload", errno);
#endif /* STLSOFT_CF_EXCEPTION_SUPPORT */
            }

#if 0
            if(flags::ff_flush & flags)
            {
                ::flush(m_fh);
            }
#endif /* 0 */
        }

        return *this;
    }
Пример #6
0
 msix_t::msix_t(PCI_Device& device)
   : dev(device)
 {
   // get capability structure
   auto cap = dev.msix_cap();
   assert(cap >= 0x40);
   // read message control bits
   uint16_t func = dev.read16(cap + 2);
   
   /// if MSIX was already enabled, avoid validating func
   if ((func & MSIX_ENABLE) == 0)
     assert(func < 0x1000 && "Invalid MSI-X func read");
   
   // enable msix and mask all vectors
   func |= MSIX_ENABLE | MSIX_FUNC_MASK;
   dev.write16(cap + 2, func);
   
   // get the physical addresses of the
   // MSI-X table and pending bit array (PBA)
   this->table_addr = get_bar_paddr(cap + 4);
   this->pba_addr   = get_bar_paddr(cap + 8);
   // get number of vectors we can get notifications from
   this->vector_cnt = (func & MSIX_TBL_SIZE) + 1;
   
   if (vector_cnt > 16) {
     printf("table addr: %#x  pba addr: %#x  vectors: %u\n",
             table_addr, pba_addr, vectors());
     assert(vectors() <= 16 && "Unreasonably many MSI-X vectors");
   }
   
   // reset all entries
   for (size_t i = 0; i < this->vectors(); i++) {
     mask_entry(i);
     zero_entry(i);
   }
   
   // unmask vectors
   func &= ~MSIX_FUNC_MASK;
   // write back message control bits
   dev.write16(cap + 2, func);
 }
Пример #7
0
void test_alignment (int max_size = 2000)
{
  std::vector<V *, nonstd::aligned_allocator<V *>> vectors(0);

  for (int size = 0; size < max_size; ++size) {
    vectors.push_back(new V(size));
  }

  for (int size = 0; size < max_size; ++size) {
    V * p = vectors[size];
    ASSERT_ALIGNED(& (* p)[0]);
    delete p;
  }

  ASSERT_ALIGNED(& vectors[0]);

  vectors.clear();
}
Пример #8
0
std::vector<MyMarker *> calculate_vectors(vector<MyMarker *> const segment, MyMarker *parent){
    std::vector<MyMarker *> vectors(segment.size());
    MyMarker *marker;
    for (int i = 0; i < segment.size(); i++){
        // Calculating vector from parent to child, approximating tangent vector
        
        if (i > 0) parent = segment[i-1];

        if (i < segment.size()-1)
            marker = segment[i+1];
        else
            // Node is either terminal or bifurcation, so use vector from parent to self
            marker = segment[i];
        
        vectors[i] = calculate_vector(marker, parent);
        
        /* Calculating from current node to child
        vectors[i] = calculate_vector(marker, parent);
         */
        /*
        if (parent){
            double sum_sq = 0;
            vectors[i] = new MyMarker();
            vectors[i]->x = marker->x - parent->x;
            sum_sq += vectors[i].x * vectors[i].x;
            vectors[i]->y = marker->y - parent->y;
            sum_sq += vectors[i].y * vectors[i].y;
            vectors[i]->z = marker->z - parent->z;
            sum_sq += vectors[i].z * vectors[i].z;
            
            double mag = sqrt(sum_sq);
            vectors[i]->x /= mag;
            vectors[i]->y /= mag;
            vectors[i]->z /= mag;
        }else{
            vectors[i] = nullptr;
        }*/
    }
    return vectors;
};
Пример #9
0
void DS_SFX_Listenerv(int prop, float* values)
{
    float ori[6];

    if(!values) return;

    switch(prop)
    {
    case SFXLP_PRIMARY_FORMAT:
        // No need to concern ourselves with this kind of things...
        break;

    case SFXLP_POSITION:
        alListener3f(AL_POSITION, values[VX] / unitsPerMeter,
                     values[VZ] / unitsPerMeter, values[VY] / unitsPerMeter);
        break;

    case SFXLP_VELOCITY:
        alListener3f(AL_VELOCITY, values[VX] / unitsPerMeter,
                     values[VZ] / unitsPerMeter, values[VY] / unitsPerMeter);
        break;

    case SFXLP_ORIENTATION:
        vectors(headYaw = (float) (values[VX] / 180 * PI),
                headPitch = (float) (values[VY] / 180 * PI),
                ori, ori + 3);
        alListenerfv(AL_ORIENTATION, ori);
        break;

    case SFXLP_REVERB: // Not supported.
        break;

    default:
        DS_SFX_Listener(prop, 0);
        break;
    }
}
Пример #10
0
int main(int argc, char *argv[]) {
	byte *stream;
	long n;
	char *strings, *queryString, *string;
	char **allwords, **uniquewords;
	int i, nwords, maxlength, newwords;
	double **allvectors, **A, **query;

	if (argc != NARGS) {
		printf("usage: %s filename\n", argv[PROGNAME]);
		return -1;
	}

	printf("READING INPUT FILE...\n");
	stream = readFullFile(argv[FILENAME], &n);

	printf("PREPROCESSING...\n");
	strings = preprocessing(stream, n);
	printf("preprocessed: %s\n\n", strings);

	printf("EXTRACTING WORDS...\n");
	allwords = words(strings, &nwords);
	for (i = 0; i < nwords; i++) {
		printf("%s\n", allwords[i]);
	}

	printf("NORMALIZING WORDS...\n");
	maxlength = normalize(allwords, nwords);

	printf("EXTRACTING UNIQUE WORDS...\n");
	uniquewords = unique(allwords, nwords, &newwords);

	printf("PREPARING THE VECTORS {+1,-1}...\n");
	allvectors = vectors(uniquewords, newwords, maxlength);

	printf("GENERATING MATRIX A...\n");
	A = bam_training(allvectors, newwords, maxlength*BITS_IN_BYTE);

	query = (double **) malloc(sizeof(double *));
	// query (double **)
	//    |
	//    ----> double *

	while (1) {
		printf("Type a word: ");
		queryString = readLine(maxlength);
		printf("Word: %s\n", queryString);

		if (strcmp(queryString, "q") == 0) {
			free(queryString);
			break;
		}

		query[FIRST_ROW] = char2vec(queryString, maxlength);
		string = bam_testing(A, maxlength*BITS_IN_BYTE, maxlength*BITS_IN_BYTE, query);
		printf("Did you mean '%s'?\n", string);
		free(query[FIRST_ROW]);
		free(queryString);
		free(string);
	}

	free(query);
	free(stream);
	free(strings);
	for (i = 0; i < nwords; i++) free(allwords[i]); free(allwords);
	for (i = 0; i < newwords; i++) free(uniquewords[i]); free(uniquewords);
	matrix_free(allvectors, newwords);
	matrix_free(A, maxlength * BITS_IN_BYTE);

	return 0;
}
Пример #11
0
  FunctionPublish_addFunction(LUXI_CLASS_STATICARRAY,PubStaticArray_prop,
    (void*)VA_MOUNTSCALAR,"mountscalararray","(scalararray):(staticarray,[int vectorsize]) - returns a mounted scalararray from current array.");


Reference_registerType(LUXI_CLASS_FLOATARRAY,"floatarray",RStaticArray_free,NULL);
FunctionPublish_initClass(LUXI_CLASS_FLOATARRAY,"floatarray",
    "Floatarray in Luxinia for array operations.",NULL,LUX_TRUE);
  FunctionPublish_setParent(LUXI_CLASS_FLOATARRAY,LUXI_CLASS_STATICARRAY);
  FunctionPublish_addFunction(LUXI_CLASS_FLOATARRAY,PubStaticArray_new,(void*)LUXI_CLASS_FLOATARRAY,"new",
    "(floatarray):(int count) - creates a new staticarray. Count must be >0.");
  FunctionPublish_addFunction(LUXI_CLASS_FLOATARRAY,PubStaticFloatArray_prop_FPU,(void*)VA_OPLIT,"v4lit",
    "():(floatarray outputintensities(4n), floatarray vertexpos(3n), floatarray vertexnormal(3n), float lightpos x,y,z ,float diffuse r,g,b ,float ambient r,g,b ,float attconst, float attlin, float attsq) - \
computes per vertex lighting intensities for n vertices into the given array. The given light position, attenuation and color values are used. Note that light position must be in same coordinate system as vertices (local).");
  FunctionPublish_addFunction(LUXI_CLASS_FLOATARRAY,PubStaticFloatArray_prop_FPU,(void*)VA_SPLINE3,"v3spline",
    "():(floatarray interpolated(3i), floatarray splinepos(3n),[int noverride]) - \
does spline interpolation based on the n splinepos vectors (eventimed), and interpolates using i steps.");
  FunctionPublish_addFunction(LUXI_CLASS_FLOATARRAY,PubStaticFloatArray_prop_FPU,(void*)VA_SPLINE4,"v4spline",
    "():(floatarray interpolated(4i), floatarray splinepos(4n),[int noverride]) - \
does spline interpolation based on the n splinepos vectors (eventimed), and interpolates using i steps.");
  FunctionPublish_addFunction(LUXI_CLASS_FLOATARRAY,PubStaticFloatArray_prop_FPU,(void*)VA_LERP,"lerp",
    "():(floatarray interpolated(i), floatarray splinepos(n),[int noverride]) - \
does linear interpolation based on the n floats (eventimed), and interpolates using i steps.");
  FunctionPublish_addFunction(LUXI_CLASS_FLOATARRAY,PubStaticFloatArray_prop_FPU,(void*)VA_LERP3,"v3lerp",
    "():(floatarray interpolated(3i), floatarray splinepos(3n),[int noverride]) - \
does linear interpolation based on the n vectors (eventimed), and interpolates using i steps.");
  FunctionPublish_addFunction(LUXI_CLASS_FLOATARRAY,PubStaticFloatArray_prop_FPU,(void*)VA_LERP4,"v4lerp",
    "():(floatarray interpolated(4i), floatarray splinepos(4n),[int noverride]) - \
does linear interpolation based on the n vectors (eventimed), and interpolates using i steps.");
  FunctionPublish_addFunction(LUXI_CLASS_FLOATARRAY,PubStaticFloatArray_prop_FPU,(void*)VA_TONEXT3,"v3tonext",
    "():(floatarray out(3n)) - for every vector we do (next-self)");
  FunctionPublish_addFunction(LUXI_CLASS_FLOATARRAY,PubStaticFloatArray_prop_FPU,
Пример #12
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs,
                 const mxArray *prhs[]) {

  //Check for proper number of inputs
  if(nrhs != 1) {
    mexErrMsgTxt("One input required\n");
  }
  //Check for proper number of outputs

  bool diag_flag=false;
  if (nlhs == 2) {
    diag_flag=true;
  } else {
    if(nrhs !=1 ) {
    mexErrMsgTxt("One or two outputs required.");
    } 
  }
 
  int nfields = mxGetNumberOfFields(prhs[0]);
  if(nfields!=3) {
    mexErrMsgTxt("First input must have three fields.");
  }
 
  /* Get dimensions of first field of input */
  const mxArray* tmp=mxGetField(prhs[0],0,fnames_in[0]);
  mwSize ndims_in=mxGetNumberOfDimensions(tmp);
  const mwSize* dims_in=mxGetDimensions(tmp);
  if(!mxIsClass(tmp,"double")) {
    mexErrMsgTxt("First field of input must be double\n");
  }

  int N=dims_in[ndims_in-1];
  int n=1;
  for(int i=0;i<ndims_in-1;i++) {
    n*=dims_in[i];
  }
  
  mexPrintf("dim n=%d number N=%d\n",n,N);

  double* X=(double*)mxGetData(tmp);

  /* Get second field of input */

  tmp=mxGetField(prhs[0],0,fnames_in[1]);
  if(!mxIsClass(tmp,"double")) {
    mexErrMsgTxt("Second field of input must be double\n");
  }
  double* ptheta=(double*)mxGetData(tmp);  

  /* Get third field of input */

  tmp=mxGetField(prhs[0],0,fnames_in[2]);
  if(!mxIsClass(tmp,"int32")) {
    mexErrMsgTxt("Third field of input must be int32\n");
  }
  int* pmaxdescend=(int*)mxGetData(tmp); 
  int maxdescend=(int)*pmaxdescend;

  /* Create matrix for the return argument. */

  plhs[0] = mxCreateStructMatrix(1, 1, 8, fnames_out_0);
 
  mxArray* fout;
  
  dims[0]=1;
  dims[1]=1;
  fout =mxCreateNumericArray(ndims,dims,mxDOUBLE_CLASS,mxREAL);
  double* p=(double*)mxGetData(fout);
  mxSetField(plhs[0],0,fnames_out_0[0],fout);
  p[0]=ptheta[0];
  
  dims[0]=1;
  dims[1]=8;
  fout =mxCreateNumericArray(ndims,dims,mxINT32_CLASS,mxREAL);
  int* params=(int*)mxGetData(fout);
  mxSetField(plhs[0],0,fnames_out_0[1], fout);

  dims[0]=2;
  dims[1]=N;
  fout =mxCreateNumericArray(ndims,dims,mxINT32_CLASS,mxREAL);
  int* plp=(int*)mxGetData(fout);
  mxSetField(plhs[0],0,fnames_out_0[2], fout);

  dims[0]=4;
  dims[1]=N;
  fout =mxCreateNumericArray(ndims,dims,mxINT32_CLASS,mxREAL);
  int* pchildren=(int*)mxGetData(fout);
  mxSetField(plhs[0],0,fnames_out_0[3], fout);

  int* pdescend_list=(int*)mxMalloc(2*N*sizeof(int));
  int* pdist_flags=(int*)mxMalloc(N*sizeof(int));
  int* pindices_to_dist_flags=(int*)mxMalloc(N*sizeof(int));
  double* pdistances=(double*)mxMalloc(N*sizeof(double));
  int* pcurrent_child_flags=(int*)mxMalloc(N*sizeof(int));
  int* pindices_to_current_child_flags=(int*)mxMalloc(N*sizeof(int));
  int* pcurrent_children=(int*)mxMalloc(N*sizeof(int));

  Vectors vectors(n,N,X);

  Cover cover(*ptheta,
	      maxdescend,
	      &vectors,plp,
	      pchildren,
	      pdescend_list,
	      pdist_flags,
	      pindices_to_dist_flags,
	      pdistances,
	      pcurrent_child_flags,
	      pindices_to_current_child_flags,
	      pcurrent_children);


  params[0]=cover.getRoot();
  params[1]=N;
  params[2]=cover.getCoverNumber();
  params[3]=cover.getNumDuplicates();
  params[4]=cover.getMinLevel();
  params[5]=cover.getMaxLevel();
  int numlevels=cover.getNumLevels();
  params[6]=numlevels;
  params[7]=cover.getMaxDescend();

  dims[0]=1;
  dims[1]=cover.getNumLevels();
  fout=mxCreateNumericArray(ndims,dims,mxDOUBLE_CLASS,mxREAL);
  double* pradii=(double*)mxGetData(fout);
  pradii[0]=cover.getRadius();
  for(int i=1;i<numlevels;i++) {
    pradii[i]=ptheta[0]*pradii[i-1];
  }
  mxSetField(plhs[0],0,fnames_out_0[4], fout);

  //mexPrintf("cover.getDistCounter=%d\n",cover.getDistCtr());

  
  dims[0]=1;
  dims[1]=numlevels;
  fout =mxCreateNumericArray(ndims,dims,mxINT32_CLASS,mxREAL);
  int* plevel_counters=(int*)mxGetData(fout);
  mxSetField(plhs[0],0,fnames_out_0[5], fout);

  dims[0]=1;
  dims[1]=numlevels;
  fout =mxCreateNumericArray(ndims,dims,mxINT32_CLASS,mxREAL);
  int* plevel_offsets=(int*)mxGetData(fout);
  mxSetField(plhs[0],0,fnames_out_0[6], fout);

  dims[0]=1;
  dims[1]=cover.getCoverNumber();
  fout =mxCreateNumericArray(ndims,dims,mxINT32_CLASS,mxREAL);
  int* plevels=(int*)mxGetData(fout);
  mxSetField(plhs[0],0,fnames_out_0[7], fout);

  Levels(&cover,plevel_counters,plevel_offsets,plevels);
  
  if(diag_flag) {
    double* p=0;
    plhs[1]= mxCreateStructMatrix(1, 1, 4, fnames_out_1);
    ndims=2;
    dims[0]=1;
    dims[1]=1;

    fout = mxCreateNumericArray(ndims,dims,mxDOUBLE_CLASS,mxREAL);
    p=(double*)mxGetData(fout);
    mxSetField(plhs[1],0,fnames_out_1[0],fout);
    p[0]=cover.getDistNCallsToGet();

    fout = mxCreateNumericArray(ndims,dims,mxDOUBLE_CLASS,mxREAL);
    p=(double*)mxGetData(fout);
    mxSetField(plhs[1],0,fnames_out_1[1],fout);
    p[0]=cover.getDistNCallsToSet();

    fout = mxCreateNumericArray(ndims,dims,mxDOUBLE_CLASS,mxREAL);
    p=(double*)mxGetData(fout);
    mxSetField(plhs[1],0,fnames_out_1[2],fout);
    p[0]=cover.getChildrenNCallsToGet();

    fout = mxCreateNumericArray(ndims,dims,mxDOUBLE_CLASS,mxREAL);
    p=(double*)mxGetData(fout);
    mxSetField(plhs[1],0,fnames_out_1[3],fout);
    p[0]=cover.getChildrenNCallsToSet();
  }

  mxFree(pdescend_list);
  mxFree(pdist_flags);
  mxFree(pindices_to_dist_flags);
  mxFree(pdistances);
  mxFree(pcurrent_child_flags);
  mxFree(pindices_to_current_child_flags);
  mxFree(pcurrent_children);  
  
}
Пример #13
0
	void NormalModeOpenMM::run( int numTimesteps ) {
		if( numTimesteps < 1 ) {
			return;
		}

		//check valid eigenvectors
		if( mProtomolDiagonalize && *Q == NULL ) {
			report << error << "No Eigenvectors for NormalMode integrator." << endr;
		}

		if( mProtomolDiagonalize && app->eigenInfo.myEigVecChanged && myPreviousIntegrator != NULL ) {
			OpenMM::LTMD::Integrator *integ = dynamic_cast<OpenMM::LTMD::Integrator *>( integrator );
			if( integ ) {
				const unsigned int count = app->eigenInfo.myNumUsedEigenvectors;
				const unsigned int length = app->eigenInfo.myEigenvectorLength * 3;

				std::vector<EigenVector> vectors( count );

				for( unsigned int i = 0; i < count; i++ ) {
					vectors[i].resize( length / 3 );

					for( unsigned int j = 0; j < length; j++ ) {
						vectors[i][j / 3][j % 3] = app->eigenInfo.myEigenvectors[i * length + j];
					}
				}

				integ->setProjectionVectors( vectors );
			}

			app->eigenInfo.myEigVecChanged = false;
		}
		
		if( mLTMDParameters.ShouldProtoMolDiagonalize && app->eigenInfo.havePositionsChanged ){
			const unsigned int sz = app->positions.size();
			
			std::vector<OpenMM::Vec3> positions;
			positions.reserve( sz );
			
			OpenMM::Vec3 openMMvecp;
			for( unsigned int i = 0; i < sz; ++i ) {
				for( int j = 0; j < 3; j++ ) {
					openMMvecp[j] = app->positions[i].c[j] * Constant::ANGSTROM_NM;
				}
				positions.push_back( openMMvecp );
			}
			
			context->setPositions( positions );
			
			app->eigenInfo.havePositionsChanged = false;
		}
		
		OpenMMIntegrator::run( numTimesteps );
		
		if( mLTMDParameters.ShouldProtoMolDiagonalize && mLTMDParameters.ShouldForceRediagOnMinFail ){
			OpenMM::LTMD::Integrator *ltmd = dynamic_cast<OpenMM::LTMD::Integrator*>( integrator );
			if( ltmd ){
				const unsigned int completed = ltmd->CompletedSteps();
				const unsigned int remaining = numTimesteps - completed;
				
				if( completed != numTimesteps ) {
					app->eigenInfo.reDiagonalize = true;
					
					//fix time as no forces calculated
					app->topology->time -= remaining * getTimestep();
					
					//Fix steps
					app->currentStep -= remaining;
					std::cout << "OpenMM Failed Minimization" << std::endl;
				}
			}
		}
	}
Пример #14
0
 inline auto* get_entry(size_t idx)
 {
   assert(idx < vectors());
   return ((msix_entry*) table_addr) + idx;
 }
Пример #15
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs,
                 const mxArray *prhs[]) {



    /* Check for proper number of arguments. */
    if (nrhs != 3) {
        mexErrMsgTxt("Three inputs required.");
    }

    //the first argument is the array of vectors used to build the tree
    /*
      int nelements=mxGetNumberOfFields(prhs[0]);
    if(nelements!=1) {
      mexErrMsgTxt("Input should have one element.");
    }
    */

    //the second argument is the struct returned by covertree
    int nfields = mxGetNumberOfFields(prhs[1]);
    if(nfields!=8) {
        mexErrMsgTxt("Second input should have 8 fields.");
    }

    //the third argument is the struct whose first member is the array of
    //vectors being studied;
    //whose second member is the distance;
    //whose third member is the depth
    nfields = mxGetNumberOfFields(prhs[2]);
    if(nfields!=2) {
        mexErrMsgTxt("Third input should have two fields.");
    }

    const mxArray* tmp=0;

    //Check for proper number of return arguments; [D] or [D E] or [D E F]
    //Return argument one is a cell array D
    //D{i}=indices of A.vectors within distance of A.vectors(:,i) at right level
    //If two or more return arguments, E{i} is corresponding distances
    //F is diagnostics

    bool dist_flag=false;
    bool diag_flag=false;
    if(nlhs==3) {
        dist_flag=true;
        diag_flag=true;
    } else if (nlhs=3) {
        dist_flag=true;
    } else {
        if(nlhs!=1) {
            mexErrMsgTxt("One, two or three return arguments required\n");
        }
    }

    //Extract appropriate members from first input;
    //this is what what was passed to covertree

    tmp=prhs[0];
    mwSize ndims_in=mxGetNumberOfDimensions(tmp);
    const mwSize* dims_in=mxGetDimensions(tmp);

    int N=dims_in[ndims_in-1];
    int n=1;
    for(int i=0; i<ndims_in-1; i++) {
        n*=dims_in[i];
    }

    mexPrintf("n=%d N=%d\n",n,N);


    double* X=(double*)mxGetData(tmp);

    Vectors vectors(n,N,X);

    // Extract appropriate members from second input;
    //this is what was returned from covertree

    tmp=mxGetField(prhs[1],0,cover_in[0]);
    double* ptheta=(double*)mxGetData(tmp);
    double theta=*ptheta;

    tmp=mxGetField(prhs[1],0,cover_in[1]);
    int* params=(int*)mxGetData(tmp);

    tmp=mxGetField(prhs[1],0,cover_in[2]);
    int* lp=(int*)mxGetData(tmp);

    tmp=mxGetField(prhs[1],0,cover_in[3]);
    int* pchildren=(int*)mxGetData(tmp);
    DisjointLists children(N,pchildren,false);


    int* pdescend_list=(int*)mxMalloc(2*N*sizeof(int));
    int* pdist_flags=(int*)mxMalloc(N*sizeof(int));
    int* pindices_to_dist_flags=(int*)mxMalloc(N*sizeof(int));
    double* pdistances=(double*)mxMalloc(N*sizeof(double));
    int* pcurrent_child_flags=(int*)mxMalloc(N*sizeof(int));
    int* pindices_to_current_child_flags=(int*)mxMalloc(N*sizeof(int));
    int* pcurrent_children=(int*)mxMalloc(N*sizeof(int));

//Get third input

    //tmp=prhs[2];
    tmp=mxGetField(prhs[2],0,nearest_in[0]);
    ndims_in=mxGetNumberOfDimensions(tmp);
    dims_in=mxGetDimensions(tmp);


    int N2=dims_in[ndims_in-1];
    int n2=1;
    for(int i=0; i<ndims_in-1; i++) {
        n2*=dims_in[i];
    }

    mexPrintf("N2=%d\n",N2);

    if(n2!=n) {
        mexPrintf("n2=%d must equal n=%d\n",n2,n);
    }

    double* Y=(double*)mxGetData(tmp);

    tmp=mxGetField(prhs[2],0,nearest_in[1]);
    int* pk=(int*)mxGetData(tmp);
    int k=*pk;

    Cover cover(theta,
                params,
                &vectors,
                lp,children,
                pdescend_list,
                pdist_flags,pindices_to_dist_flags,
                pdistances,
                pcurrent_child_flags,pindices_to_current_child_flags,
                pcurrent_children);

    ndims=2;
    dims[0]=1;
    dims[1]=N2;

    mxArray* pointer0=mxCreateCellArray(ndims,dims);
    mxArray* pointer1=0;
    //Cover::DescendList* pdescendlist=0;
    if(dist_flag) {
        pointer1= mxCreateCellArray(ndims,dims);
        //pdescendlist=(Cover::DescendList*)&cover.getDescendList();
    }

    int* indices=(int*)mxMalloc(N*sizeof(int));
    double* d=(double*)mxMalloc(N*sizeof(double));
    int* Indices=(int*)mxMalloc(N*sizeof(int));
    double* D=(double*)mxMalloc(N*sizeof(double));

    for(int i=0; i<N2; i++) {
        //mexPrintf("loop i=%d\n",i);
        Vector v(n,Y+i*n);
        int K=cover.findNearest(&v,k,indices,d);
        dims[1]=K;
        mxArray* fout=mxCreateNumericArray(ndims,dims,mxINT32_CLASS,mxREAL);
        int* arr=(int*)mxGetData(fout);
        for(int j=0; j<K; j++) {
            arr[j]=indices[j];
        }

        /*
        bool test=cover.checkFindNearest(&v,k,K,indices,d,Indices,D);
        if(test) {
          mexPrintf("checkFindWithin passed\n");
        } else {
          mexPrintf("checkFindWithin failed\n");
        }
        mexPrintf("after mxSetCell i=%d\n",i);
        */

        mxSetCell(pointer0,i,fout);
        if(dist_flag) {
            fout=mxCreateNumericArray(ndims,dims,mxDOUBLE_CLASS,mxREAL);
            double* dist=(double*)mxGetData(fout);
            for(int j=0; j<K; j++) {
                //dist[i]=pdescendlist->getDist(&v,arr[i]);
                dist[j]=d[j];
            }
            mxSetCell(pointer1,i,fout);
        }
        cover.clearDescendList();
    }

    plhs[0]=pointer0;
    if(dist_flag) {
        plhs[1]=pointer1;
    }

    if(diag_flag) {
        double* p=0;
        plhs[2]= mxCreateStructMatrix(1, 1, 4, fnames_out_2);
        ndims=2;
        dims[0]=1;
        dims[1]=1;

        mxArray* fout=0;
        fout = mxCreateNumericArray(ndims,dims,mxDOUBLE_CLASS,mxREAL);
        p=(double*)mxGetData(fout);
        mxSetField(plhs[2],0,fnames_out_2[0],fout);
        p[0]=cover.getDistNCallsToGet();

        fout = mxCreateNumericArray(ndims,dims,mxDOUBLE_CLASS,mxREAL);
        p=(double*)mxGetData(fout);
        mxSetField(plhs[2],0,fnames_out_2[1],fout);
        p[0]=cover.getDistNCallsToSet();

        fout = mxCreateNumericArray(ndims,dims,mxDOUBLE_CLASS,mxREAL);
        p=(double*)mxGetData(fout);
        mxSetField(plhs[2],0,fnames_out_2[2],fout);
        p[0]=cover.getChildrenNCallsToGet();

        fout = mxCreateNumericArray(ndims,dims,mxDOUBLE_CLASS,mxREAL);
        p=(double*)mxGetData(fout);
        mxSetField(plhs[2],0,fnames_out_2[3],fout);
        p[0]=cover.getChildrenNCallsToSet();
    }

    mxFree(pdescend_list);
    mxFree(pdist_flags);
    mxFree(pindices_to_dist_flags);
    mxFree(pdistances);
    mxFree(pcurrent_child_flags);
    mxFree(pindices_to_current_child_flags);
    mxFree(pcurrent_children);

    mxFree(indices);
    mxFree(d);
    mxFree(Indices);
    mxFree(D);

}