function [dat,nogap]=bridgemain(dat,nlin,nmaxbr,maxngaps,vname);

global xhand xnum

% c	Program to fill gaps in time-series files using Joseph's 
% c	scheme( a spectral method) after filling short gaps with
% c	a linear fit from neighbors' values.

% Adapted from a Fortran program by jpx on 7-15-99
nogap=0;
dat=dat;
infofid=fopen('bridge.info','wt');
if infofid<0
	warndlg('The file ''bridge.info'' needs to be closed before proceed!','Error');
	nogap=1;
	return;
end;
fprintf(infofid,'Max. gap length to fill linearly: %2d ; Max. gaps to fill: %5d\n',nlin,maxngaps);
fprintf('Max. gap length to fill linearly: %2d ; Max. gaps to fill: %5d\n',nlin,maxngaps);
fstr=get(xhand.filename,'string');
fprintf(infofid,'File: %s\n',fstr{xnum.file+1}(4:end));
fprintf('File: %s\n',fstr{xnum.file+1}(4:end));
fprintf(infofid,'Variables: %s      : %d points\n',vname,length(dat));
fprintf('Variables: %s      : %d points\n\n',vname,length(dat));


[m,n]=size(dat);
if n>m
	dat=dat';
end;
[m,n]=size(dat);

for i=1:n
	thisdata=dat(:,i);
	[ngaps,notfilled,nfirstbad,nlastbad,lgap,endgap]=idgaps(thisdata,maxngaps,infofid);
	
	if ngaps<1
		warndlg('No gap found.','Notes');
		nogap=1;
		return;
	end;
	
	for j=1:ngaps
		if ~(endgap & j==ngaps)
			if lgap(j)<=nlin
				[nfirstbad(j),nlastbad(j),thisdata]=linbridge(nfirstbad(j),nlastbad(j),thisdata,infofid);
			end;
		end;
	end;

	if ngaps>0
		[ngaps,nfirstbad,nlastbad,lgap]=reseq(ngaps,nfirstbad,nlastbad,lgap);
		for j=1:ngaps
			if ~(endgap & j==ngaps)
				[nbefore,nafter,notfilled,nflag(j)]=goodpts(j,m,nmaxbr,ngaps,nfirstbad,nlastbad,lgap,notfilled,infofid);
				
				if nflag(j)<1
					thisdata=bridgeit(nfirstbad(j),nlastbad(j),lgap(j),nbefore,nafter,thisdata);
				end;
			end;
		end;
	end;
	dat(:,i)=thisdata;
% 	ngaps,nfirstbad,nlastbad,lgap
	fclose(infofid);
end;
					
