function goodedges=checkrange(edgemat, narrow, wide);

% goodedges=checkrange(edgemat, narrow, wide);
% This function runs through the matrix returned by the edge detector,
% looking for edges which match the size we're looking for.

% This matrix has the coordinates for the edge pixels from edge detection
[I,J]=find(edgemat>0);
szJ=size(J);
goodv=[];
goodh=[];

% get the numbers for columns which have edges (but without repeating
% column numbers)
jvalindex=find(J~=[NaN;J(1:size(J)-1)]);
szjv=size(jvalindex);

% check each of the columns which have edge pixels
for j=1:szjv(1)
   % find the closest and furthest pixels which would be in range
   lowpixnum=I(jvalindex(j))+narrow;
   highpixnum=I(jvalindex(j))+wide;
   % find the coordinates which match the current column value
   curindex1=find(J==J(jvalindex(j)));
   % find which of these edge pixels are in range
   goodcuri=find( (I(curindex1)>=lowpixnum) & (I(curindex1)<=highpixnum));
   % If some pixels were in range of the original...
   if prod(size(goodcuri))>0
      % add them to the list
      goodv=[goodv; [I(jvalindex(j)), J(jvalindex(j))]; [I(jvalindex(j)+goodcuri-1), J(jvalindex(j)+goodcuri-1)]];
   end
end

% Make a matrix with the good edges set high
goodvm=zeros(size(edgemat));
if prod(size(goodv)) > 0
   goodvlin=sub2ind(size(edgemat), goodv(:,1), goodv(:,2));
   goodvm(goodvlin)=1;
end

% Now switch around the I and J to be in order of increasing row   
[orderedI,index]=sort(I);
matchedJ=J(index);

% get the numbers for rows which have edges (but without repeating
% row numbers)
ivalindex=find(orderedI~=[NaN;orderedI(1:size(orderedI)-1)]);
sziv=size(ivalindex);

% check each of the rows which have edge pixels
for i=1:sziv(1)
   % find the closest and furthest pixels which would be in range
   lowpixnum=matchedJ(ivalindex(i))+narrow;
   highpixnum=matchedJ(ivalindex(i))+wide;
   % find the coordinates which match the current row value
   curindex2=find(orderedI==orderedI(ivalindex(i)));
   % find which of these edge pixels are in range
   goodcurj=find( (matchedJ(curindex2)>=lowpixnum) & (matchedJ(curindex2)<=highpixnum) );
   % If some pixels were in range of the original...
   if prod(size(goodcurj))>0
      % add them to the list
      goodh=[goodh; [orderedI(ivalindex(i)), matchedJ(ivalindex(i))]; [orderedI(ivalindex(i)+goodcurj-1), matchedJ(ivalindex(i)+goodcurj-1)]];
   end
end

goodhm=zeros(size(edgemat));
if prod(size(goodh)) > 0
   goodhlin=sub2ind(size(edgemat), goodh(:,1), goodh(:,2));
   goodhm(goodhlin)=1;
end


goodedges=or(goodvm, goodhm);
