function [rec, bg, ed] = long_rec( dat, n )

% [rec, bg, ed] = long_rec( dat, n );
%
% input:
% dat is a vector, n is the nth-longest nan-delimited record
% 	records are groups of numbers assumed to be nan separated.
%
% output:
% rec is the nth longest continuous record in dat.
% bg and ed are the beginning and ending indices of the returned record.
% if n is omitted, it is assumed 1, and the longest record is returned.
%

%
% dail, march 1998

if nargin==1,
 n = 1;
end

if isempty( find(~isnan(dat)) ),
 warning('data vector is all NaN''s')
 rec = [];
 bg = [];
 ed = [];
 break
end

i = find( isnan(dat) );
i = [0 i length(dat)+1];
%if isempty(i),
% rec = dat;
% bg = 1;
% ed = length(rec);
% if n~=1,
%  warn(n,1);
% end
% break
%end

 
ln = diff(i);
[ordered_ln] = sort(ln);
ordered_ln = flipud( ordered_ln(:) );
ordered_ln = ordered_ln( ordered_ln>1 );
if length(ordered_ln)<n  
 iw = find( ln==ordered_ln(end) );
 bg = i(iw)+1;
 ed = i(iw+1)-1;
 rec = dat(bg:ed);
 warn(n,length(ordered_ln))
else
 iw = find( ln==ordered_ln(n) );
 bg = i(iw)+1;
 ed = i(iw+1)-1;
 rec = dat(bg:ed);
end

function warn(n,m)

mes = sprintf('data does not have %d records. returning record %d.',n,m);
warning(mes) 
