function [Corr]=pointmatchfun(points,labels,maxpoints)
%maxpoints is the maximal number of points a single label can match to
npoints=length(points);
nlabels=length(labels);
Corr=zeros(1,npoints);
tCorr=zeros(1,npoints);

%find smallest distance between labels
mindist=inf;
for i=1:nlabels-1
    for j=i+1:nlabels
        dx=abs(labels(i,1)-labels(j,1));
        dy=abs(labels(i,2)-labels(j,2));
        if(mindist>dx&&dx~=0)
               mindist=dx;
        end
        if(mindist>dy&&dy~=0)
               mindist=dy;
        end
    end
end

%rotate points based on finding close points
noise=mindist/2.5;

i=2;
j=1;
k=1;
tmax=0;
cmax=0;
crot=0;
nh=noise*sqrt(2);
for rottmp=0:pi/128:pi*2%run through a number of possible rotations
while(j<=npoints)
    tCorr(j)=1;
    while(i<=nlabels)
        ldx=labels(i,1)-labels(1,1);
        ldy=labels(i,2)-labels(1,2);
        ldh=sqrt(ldx*ldx+ldy*ldy);
        lrot=rottmp+atan2(ldy,ldx);
        while(k<=npoints)
            if(k~=j)
                pdx=points(k,1)-points(j,1);
                pdy=points(k,2)-points(j,2);
                pdh=sqrt(pdx*pdx+pdy*pdy);
                if(pdh-noise<=ldh&&pdh+noise>=ldh)
                    tx=points(j,1)+pdh*cos(lrot);
                    ty=points(j,2)+pdh*sin(lrot);
                    if(tx-noise<points(k,1)&&tx+noise>points(k,1)&&...
                            ty-noise<points(k,2)&&ty+noise>points(k,2))
                            tCorr(k)=i;
                            tmax=tmax+1;    
                    end
                end
            end
            k=k+1;
        end
        i=i+1;
        k=1;
    end
    %
    if(tmax>cmax)
        Corr=tCorr;
        cmax=tmax;
        crot=rottmp;
    end
    tCorr(:)=0;
    tmax=0;
    %
    j=j+1;
    i=2;
end
j=1;
end

for i=1:npoints
   for j=1:npoints
       pdx=points(j,1)-points(i,1);
       pdy=points(j,2)-points(i,2);
       pdh=sqrt(pdx*pdx+pdy*pdy);
       if(pdh<=nh) 
           Corr(j)=Corr(i);
       end
   end
end

%for testing purposes
%cmax
%crot
%cnoise
%