function edgepts=findedge(sctrlpts,img,numpts,lev)

bsize = 2^lev; % box size
ranb = bsize - 1; % range of box
lctrlpts=sctrlpts*bsize;
edgepts = [];
for j = 1:size(sctrlpts,1)
    mat=img(lctrlpts(j,1)-ranb:lctrlpts(j,1),lctrlpts(j,2)-ranb:lctrlpts(j,2));
    diffmat = abs(diff(double(mat),1,2));
    
    [rdm cdm] = size(diffmat);
    [rm cm] = size(mat);
    rcoor = zeros(rm,cm);
    ccoor = zeros(rm,cm);
    cvect = [lctrlpts(j,2)-ranb:lctrlpts(j,2)]';
    rvect = [lctrlpts(j,1)-ranb:lctrlpts(j,1)]';
    rcoor(:,1) = rvect;
    ccoor(:,1) = cvect;
    ccoor = (ccoor*ones(rm,cm))';
    rcoor = rcoor*ones(rm,cm);
    numpix = rdm*cdm;
    vecdmat = reshape(diffmat,numpix,1);
    [smat smatloc] = sort(vecdmat,'descend');
    [repts cepts] = size(edgepts);
    edgepts(repts+1:repts+numpts,1) = rcoor(smatloc(1:numpts));
    edgepts(repts+1:repts+numpts,2) = ccoor(smatloc(1:numpts));
end
