function gat=gate(im)
% gat;array of size 4 :
%	gat(1)= begin column of gate
%	gat(2)= end column of gate
%	gat(3)= begin row of gate
%	gat(4)= end row of gate
[r,c]=size(im); % imgae size
% initializations : whole array is 0

out(r,c)=0;
edge(c,1)=0;
gat(4)=0;

% loop to find the multiple edges in the image

for j=1:c
	prev=0;
	nr=1;
	for i=r:-1:1
		if (prev==0 & im(i,j) > 0) 
		if (nr==1) out(i,j)=255; end;
		edge(j,nr)=i;
		nr=nr+1;
		end;
               prev=im(i,j);

	end;
end;

% find connected edges

nr=1;
compb(nr)=1;
for j=2:c
	if abs(edge(j,1)-edge(j-1,1)) > 3
		compl(nr)=j-compb(nr);
		nr=nr+1;
		compb(nr)=j;
	end;
	compl(nr)=c-compb(nr);
end;

% which sufficient large connected edges have a second edge at 
% the right distance

for k=1:nr
	if (compl(k) > 10)
		pos=compb(k);
		n2=0;
		gem=0;
		for kl=1:compl(k)
			if (edge(pos,2) > 0 ) n2=n2+1;
			gem = gem+edge(pos,1)-edge(pos,2);
			pos=pos+1;
			end;
		end;
		if (n2>0) compd(k)= gem/n2;
			if (compd(k) <20 & compd(k) >5) 
			if (gat(1) ==0) gat(1)= compb(k); end;
			gat(2)=compb(k)+compl(k)-1;
			end;
		end;
	end;
end;

% print out values to check

compb
compl
compd
gat(3)=edge(gat(1),1);
gat(4)=edge(gat(2),1);
gat
% and show the closest edge

imshow(out);
end;
