function draw_grid(hObject, eventdata)

global var h
subplot(1,1,1)

var.Vstep = norm(var.TL-var.BL)/(var.Vpoints-1);
var.Hstep = norm(var.BR-var.BL)/(var.Hpoints-1);
CircleSize = mean([var.Vstep var.Hstep])/10;

Vcenter = 1+floor((var.Vstep-1)/2);
Hcenter = 1+floor((var.Hstep-1)/2);

pat1 = zeros(ceil(var.Vstep),ceil(var.Hstep));
for i=1:var.Vstep
    for j=1:var.Hstep
        if (i-Vcenter)^2+(j-Hcenter)^2<=CircleSize^2
            pat1(i,j)=1;
        end
    end
end
posval = sum(sum(pat1));
nbzeros = sum(sum(pat1==0));
pat1 = pat1 - 0*(posval/nbzeros)*(pat1==0);
var.pat2 = [pat1 pat1; pat1 pat1];

% cut image to the extremum points

cutoff = 3;

xleft = max(1+cutoff,floor(min(var.TL(1), var.BL(1)) - var.Hstep*.7));
xright = min(var.Imsize(2)-cutoff,ceil(max(var.BR(1), (var.TL+var.BR-var.BL)*[1;0]) + var.Hstep*.7));
ybot = max(1+cutoff,floor(min(var.BL(2), var.BR(2)) - var.Vstep*.7));
ytop = min(var.Imsize(1)-cutoff,ceil(max(var.TL(2), (var.BR+var.TL-var.BL)*[0;1]) + var.Vstep*.7));

cutimage = var.gray(ybot:ytop,xleft:xright);
Cutsize = size(cutimage);

background = mean(cutimage(:));
var.newimage = [background*ones(size(var.pat2,1),2*size(var.pat2,2)+Cutsize(2));
    background*ones(Cutsize(1),size(var.pat2,2))  cutimage   background*ones(Cutsize(1),size(var.pat2,2));
    background*ones(size(var.pat2,1),2*size(var.pat2,2)+Cutsize(2))];

var.nTL = var.TL + [size(var.pat2,1) - xleft; size(var.pat2,2) - ybot]';
var.nBL = var.BL + [size(var.pat2,1) - xleft; size(var.pat2,2) - ybot]';
var.nBR = var.BR + [size(var.pat2,1) - xleft; size(var.pat2,2) - ybot]';
nBR = var.nBR;
nBL = var.nBL;
nTL = var.nTL;
Hpoints = var.Hpoints;
Vpoints = var.Vpoints;

cla
h.plot=imagesc(var.newimage);
set(gca,'YDir','normal');
colormap gray
hold on
plot([var.nBL(1) var.nTL(1) var.nBR(1)], [var.nBL(2) var.nTL(2) var.nBR(2)],'oy')
hold off


for i=1:Vpoints
    for j=1:Hpoints
        points(i,j,:) = ceil(nBL + (j-1)*(nBR-nBL)/(Hpoints-1) + (i-1)*(nTL-nBL)/(Vpoints-1));
    end
end

hold on
for i=1:(Vpoints/2)
    for j=1:(Hpoints/2)
        plot([points(2*i-1,2*j-1,1) points(2*i-1,2*j,1) points(2*i,2*j,1) points(2*i,2*j-1,1) points(2*i-1,2*j-1,1)], ...
            [points(2*i-1,2*j-1,2) points(2*i-1,2*j,2) points(2*i,2*j,2) points(2*i,2*j-1,2) points(2*i-1,2*j-1,2)], ...
            '-', 'color', [.6 .6 .6])
    end
end
hold off

var.points=points;

set(h.buttons.gridbutton,'visible','on','backgroundcolor','w')

set(h.buttons.accept_grid,'visible','on','backgroundcolor','r')
set(h.buttons.reject_grid,'visible','on','backgroundcolor','r')

set(h.text.info,'string','Accept Grid')
    


