% --- Executes on button press in rect_sub.
function rect_sub_Callback(hObject, eventdata, handles)
global shape incount invisible globcount
[nx,ny]=ginput(2);
x1=round(nx(1));
y1=round(ny(1));
x2=round(nx(2));
y2=round(ny(2));

x=round(min(nx));
xmax=round(max(nx));
y=round(min(ny));
ymax=round(max(ny));
w=x1-x2;          %w=width
h=y1-y2;          %h=height
w=abs(w);
h=abs(h);
if (w~=0)&&(h~=0)
    elem=zeros(w*h,2);
    k=1;
    for i=x:(x+w)
        for j=y:(y+h)
            elem(k,1)=i;
            elem(k,2)=j;
            k=k+1;
        end
    end
end
%'elem' is formed at end of this loop
t=1;
for s=x:xmax
   rect(t,1)=s;
   rect(t,2)=ymax;
   t=t+1;
end
for s=(ymax-1):-1:y
   rect(t,1)=xmax;
   rect(t,2)=s;
   t=t+1;
end
for s=(xmax-1):-1:x
   rect(t,1)=s;
   rect(t,2)=y;
   t=t+1;
end
for s=(y+1):(ymax-1)
   rect(t,1)=x;
   rect(t,2)=s;
   t=t+1;
end
elem_bound=rect;
clear rect
%'elem_boundary' is formed at end of this chunk

flag1=0;
flag2=0;
flag3=0;
connect=0;
[disc,page]=size(shape);
for i=1:page
    temp=shape(i).elem;
    elem=union(elem,elem,'rows');
    [m,n]=size(intersect(temp,elem,'rows'));
    if size(elem)==size(intersect(temp,elem,'rows'))
        if elem==(intersect(temp,elem,'rows'))
            flag1=1;
            connect=shape(i).seq;
        end
    end
    [disc,pagei]=size(invisible);
    if incount>=1
        for j=1:pagei
            if invisible(j).shape==connect
                flag1=0;
                flag3=1;
                msgbox('Cant be subtracted: subtraction possible only once from each electrode')
            end
        end
    end
    if (m~=0)&&(flag1==1)
        onion=setdiff(temp,elem,'rows');
        %boundary of invisble rectangle should be included
        onion=union(onion,elem_bound,'rows');
        shape(i).elem=onion;
        flag2=1;
        break
    end
end
if (flag2~=1)&&(flag3~=1)
    msgbox('Subtraction not possible: subtracted area does not FULLY lie within existing electrode')
elseif (flag3~=1)
    incount=incount+1;
    globcount=globcount+1;
    invisible(incount).elem=elem;
    invisible(incount).id=1;
    invisible(incount).seq=globcount;    
    limca(1,1)=x;
    limca(1,2)=y;
    limca(1,3)=w;
    limca(1,4)=h;
    invisible(incount).position=limca;
    invisible(incount).shape=connect;
    rectangle('Position',limca,'FaceColor','w','EdgeColor','w') 
    hold on
    gridplot()
end
clear elem

