function [hdr, hdrs, hdrn] = scan_hdr(flog)
%  1.  NAME
%
%  scan_hdr - Retrieve the header from log files
%
%  2.  SYNOPSIS
%
%  [hdr, hdrs, hdrn] = scan_hdr(flog)
%
%  3.  DESCRIPTION
%
%  This Matlab function scans a log file and returns its header
%  information. The header synthax must follow the one used by
%  applications like scan_nbr(1) or scan_nav(1).
%
%  4.  PARAMETERS
%
%     flog
%        File descriptor of log file. The file must be positionned at the
%        beginning.
%
%  5.  RETURNS
%
%     hdr
%        String containing complete column description.
%
%     hdrs
%        Array of column names.
%
%     hdrn
%        Array of column numbers.
%
%  6.  AUTHORS
%
%  Pierre Jaccard, Geophysical Institute, University of Bergen, 1999
%

% ---------------------------------
% Initializations:
hdr = [];
hdrs= [];
hdrn= [];

% ---------------------------------
% Read until beginning of header:
finished = 0;
while ~finished & ~feof(flog),
  line = fgetl(flog);
  if length(line) > 1,
	 % Check for correct comments inside the line		
	 com = findstr(line, 'Data Description');
	 line= strcat(line, '  ');
	 if (length(com) > 0) & strcmp(line(1:1), '%'),
		finished = 1;
	 end
  end
end

% ---------------------------------
% Warning message:
if ~finished,
  disp(['Warning: did not find any data description header']);
  hdr = 'NO DATA DESCRIPTION';
  return;
end

% ---------------------------------
% Read until end of header:
finished = 0;
hdr = '';
n = 0;
while ~finished & ~feof(flog),
	line = fgetl(flog);
	%if length(line) > 1,
	% Check for end of header
	com = findstr(line, '% *');
	if length(com) > 0,
		finished = 1;
	else
		com = findstr(line, '%');
		line= strcat(line, ' ');
		if (length(com) > 0) & strcmp(line(1:1), '%'),
			n = n+1;
			line = strrep(line, '\n', '');
			line = strrep(line, '\r', '');
			hdr = strvcat(hdr, line(2:length(line)));
		end
	end
end

% ---------------------------------
% Warning message:		
if ~finished,
  disp(['Warning: did not find end of data description header']);
  hdr = 'NO DATA DESCRIPTION';
  return;
end

% ---------------------------------
% Process header description
for i=1:n,
	line = hdr(i,:);
	com = findstr(line, ':');
	if(length(com) > 0),
		hdrn(i) = str2num(line(1:com(1)-1));
		hdrs    = strvcat(hdrs, line(com(1)+1:length(line)));
	else 
		disp(['Warning: did not find data description separator']);
		hdr = 'NO DATA DESCRIPTION';
		hdrs=[];
		hdrn=[];
		return;
	end
end	

% ---------------------------------
% Build return description string:
line = '';
for i=1:n,
	line = sprintf('%s%s\n', line, hdr(i,:));
end;
hdr = line;

return;

