function jbjejr = findinterp(datcol,flag,mseg)
% Find intervals of data with no flag intervals longer than a specified number of points
% Created August 2, 2001
% datcol = A single column of data with possible flag segements
% flag = The flag used in the datcol
% mseg = The number of sequential flags used to define boundary between long and short intervals
% jbjejr = The start, stop, and length of intervals that can be interpolated

% FIND IF THERE ARE FLAGS IN THE DATA SEGMENT
[md,nd] = size(datcol);
ii = find(datcol==flag); %Find the flags in the input data column
if(isempty(ii) | length(ii)==md) %There are no flags in the segment
jbjejr = [1,md,md]; %Return the limits of the input segment as ok to interpolate
%Note that if all point are flags then the interpolation routine thows them out and simply transfers flags to
% an already flagged array
else %There are some flags in the segment
if(nd~=1);disp('Error in findinterp.m - a single column of data is expected at input');return;end
ii = (datcol==flag); %A zero-one matrix with 1 for flags
ij = diff(ii); %First difference of above array showing start and stop of flag segements
ib = find(ij==+1); %Find positive spikes
ib = ib+1; %The start of a flag interval is one beyond the +1
if(ii(1)==1) %There is a flag in the first point
ib = [1;ib]; %There is no +1 to show flags start at the beginning
end
ie = find(ij==-1); %The end of a flag interval is at the -1
if(ii(md)==1)
ie = [ie;md]; %There in no -1 to show flags stop at the end
end
ir = ie-ib+1; %The number of flags in the sequence
% Find flag intervals short enough to interpolate and eliminate from list
ll = find(ir<=mseg); %Location of short flag intervals in above lists
ib(ll) =[];ie(ll)=[];,ir(ll)=[]; %Null the definition of short intervals
%Now define the intervals to interpolate that are between the long flag intervals
if(isempty(ib)) %All flag intervals are short
jb = 1;
je = md; %Interpolate the entire segment
else
jb = ie+1; %Start interp int one to the right of a large gap
je = ib-1; %End interp ints one to the left of a large gap
% Series of checks of beginning and end of data column to straighten out the [jb, je] table
if(ib(1)>1 & ie(end)<md) %There is no flag at either the first of last point
jb = [1;jb]; %Start the interpolation at first point
je = [je;md]; %Stop the integration at the last point
elseif(ib(1)==1 & ie(end)<md) %Long Flag interva; at the beginning, but not the end
je(1) = []; %Eliminate the 0 stored here by a statement above
je = [je;md]; %Interpolate all the way to the end
elseif(ib(1)>1 & ie(end)==md) %Long Flag interval at end, but not at beginning
jb(end) = []; %I had stored above an index one beyond the end of the array
jb = [1;jb]; %Start interpolation at beginning
elseif(ib(1)==1 & ie(end)==md) %Long flag intervals at both ends
jb(end) = []; %One beyond end of array
je(1) = []; %One before start of array
end
end

% CREATE THE OUTPUT ARRAY
jr = je-jb+1;
jbjejr = [jb, je, jr];
end

return
%%)