%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Read header of a NIST SPHERE file
% In case of success, a structure "sphere_header" is returned.
% In case of failure, an error is fired.

function sphere_header = read_sphere_header( filename )

  if nargin < 1
    error( [ mfilename '.read_sphere_header() needs 1 input argument.' ] );
  end
  
  sphere_header.filename = filename;

  % Open

  fid = fopen( filename, 'rt' );
  
  % We'll store the raw lines here

  line_list = {};

  % Check first line

  a_line = fgetl( fid );
  if ~ischar( a_line )
    error( [ mfilename '.read_sphere_header() could not read first line.' ] );
  end
  
  a_line = deblank( fliplr( deblank( fliplr( a_line ) ) ) );

  if ~strcmp( a_line, 'NIST_1A' )
    error( [ mfilename '.read_sphere_header(): first line is supposed to be "NIST_1A".' ] );
  end
  
  line_list{ end+1 } = a_line;

  % Check second line (header size)

  a_line = fgetl( fid );
  if ~ischar( a_line )
    error( [ mfilename '.read_sphere_header() could not read second line.' ] );
  end

  a_line = deblank( fliplr( deblank( fliplr( a_line ) ) ) );

  [ sphere_header.header_size, is_ok ] = str2num( a_line );

  if ~is_ok
    error( [ mfilename '.read_sphere_header() could not read the header size.' ] );
  end
  
  line_list{ end+1 } = a_line;

  % Read and parse remaining lines
  
  while 1
    
    a_line = fgetl( fid );
    
    if ~ischar( a_line )
      error( [ mfilename '.read_sphere_header() could not finish reading header.' ] );
    end

    a_line = deblank( fliplr( deblank( fliplr( a_line ) ) ) );

    line_list{ end+1 } = a_line;

    if ~isempty( a_line )
      
      % Split the line in tokens separated by white spaces

      tok_list = {};
      while ~isempty( a_line )
	
	[ t, r ] = strtok( a_line );
	tok_list{ end + 1 } = deblank( fliplr( deblank( fliplr( t ) ) ) );
	a_line              = deblank( fliplr( deblank( fliplr( r ) ) ) );
	
      end
      
      % Special case: end of header
      if strcmp( tok_list{ 1 }, 'end_head' )
	break
      end

      % Usual case: some parameter
      if numel( tok_list ) >= 3

	if strcmp( tok_list{ 2 }, '-i' )
	 
	  % In case of an integer, do a conversion and store the integer
	  eval( [ 'sphere_header.' tok_list{ 1 } ' = ' tok_list{ 3 } ';' ] );

	else
	
	  % In the general case, store the parameter as a string
	  eval( [ 'sphere_header.' tok_list{ 1 } ' = ''' tok_list{ 3 } ''';' ] );

	end

      end
            
    end
    
    % Check whether we reached end of header

    if ftell( fid ) >= sphere_header.header_size
      break;
    end
    
  end  % Loop reading header lines
  

  % Add filename and raw header
  sphere_header.filename = filename;
  sphere_header.line_list = line_list;

  fclose( fid );
