function [ngaps,notfilled,nfirstbad,nlastbad,lgap,endgap]=idgaps(dat,maxgaps,infofid)

% c	SUBROUTINE to identify the endpoints of gaps in the series
% c	IF there are too many gaps, the subroutine writes an error
% c	message that only the first nmaxgaps were filled 
% c	IMPORTS:
% c 		dat: the data array from the EPIC file
% c		maxngaps: the max # of gaps the program will fill (500)
% c	EXPORTS:
% c		ngaps: the number of gaps to fill (excludes gaps that
% c		can't be filled because they go to the end of the file)
% c		notfilled (also modified in goodpts): a count of the
% c		number of gaps program refused to fill: for header info
% c		nfirstbad,nlastbad,lgap:  integer arrays containing the
% c		point#s for the first bad point of each gap and the last
% c		bad point, and the length of each gap
% c 		endgap: 1. if final gap goes all the way to the end of
% c 		the file (and can't be filled).  0 otherwise

% adapted from a fortran program bridge.f by jpx on 7-12-99

m=length(dat);
dat(dat>=1e35)=nan;

ngaps=0;
notfilled=0;
endgap=0;
nfirstbad=nan;
nlastbad=nan;
lgap=0;
mydata=find(isnan(dat)==1);
if ~isempty(mydata)
	ngaps=ngaps+1;
	nfirstbad(ngaps)=mydata(1);
	nlastbad(ngaps)=mydata(1);
	tot=length(mydata);
	for j=2:tot
		if mydata(j)-mydata(j-1) >1 & j<=tot
			ngaps=ngaps+1;
			nfirstbad(ngaps)=mydata(j);
			nlastbad(ngaps)=mydata(j);
		else
			nlastbad(ngaps)=mydata(j);
		end;
	end;
	for k=1:ngaps
		lgap(k)=nlastbad(k)-nfirstbad(k)+1;
		fprintf(infofid,'Gap # %4d : from point %d to point %d, gap length= %d\n',...
			k,nfirstbad(k),nlastbad(k),lgap(k));
		fprintf('Gap # %4d : from point %d to point %d, gap length= %d\n',...
			k,nfirstbad(k),nlastbad(k),lgap(k));
	end;
	if ngaps>maxgaps
		notfilled=notfilled+1;
		fprintf('%s has more than %d gaps. Only first %d gaps are bridged.\n',...
			inputname(1),maxgaps,maxgaps);
		fprintf(infofid,'%s has more than %d gaps. Only first %d gaps are bridged.\n',...
			inputname(1),maxgaps,maxgaps);
		ngaps=maxgaps
	end;
	if nlastbad(ngaps)>=m
		notfilled=notfilled+1;
		endgap=1;
		fprintf('Final gap extends from %d to end of file therefore can not be filled.\n',...
			nlastbad(ngaps));
		fprintf(infofid,'Final gap extends from %d to end of file therefore can not be filled.\n',...
			nlastbad(ngaps));
	end;
end;
% ngaps,nfirstbad,nlastbad,lgap;
return;
