
function [ mwRTM_param, N_tile ] = read_mwRTMparam( fname );

% reichle,  1 Jun 2011

% NOTE: For large files this reader is inefficient (slow execution,
% excessive memory demand)  due to the use of a matlab structure
% array. If you need better performance, convert to reading 
% data into a regular matrix (as opposed to a structure array).
%
% ------------------------------------------------------------------

int_precision   = 'int32';      % precision of fortran tag
float_precision = 'float32';    % precision of data in input file

disp(['read_mwRTMparam.m: reading from ', fname])

ifp = fopen( fname, 'r', 'b' );

% read N_tile

fortran_tag = fread( ifp, 1, int_precision );
N_tile      = fread( ifp, 1, int_precision );
fortran_tag = fread( ifp, 1, int_precision );

% for backward compatibility, back out number of parameters in file
% from file size:

% file size = ( 3 + N_param * (N_tile + 2)) * bytes_per_datapoint

tmps = dir(fname);

N_param = (tmps.bytes/4 - 3)/(N_tile+2);

if     N_param==18
  
  file_format = 1;

  int_columns = [ 1 2 ];
  
else
  
  error('read_mwRTMparam.m: something wrong with file size or format')
  
end

disp(['read_mwRTMparam.m: expecting ', num2str(N_param), ...
      ' parameters in file with file_format ', num2str(file_format)])

% ----------------------------------------------------------------

for i=1:N_param
  
  fortran_tag = fread( ifp, 1, int_precision );
  if any(i==int_columns)
    tmp         = fread( ifp, [1 N_tile], int_precision );
  else
    tmp         = fread( ifp, [1 N_tile], float_precision );
  end
  fortran_tag = fread( ifp, 1, int_precision );
  
  tmp_data(i,:) = tmp;
  
end

disp(['read_mwRTMparam.m: assembling structure array'])

if file_format==1
  
  mwRTM_param.vegcls     = tmp_data( 1,:)';
  mwRTM_param.soilcls    = tmp_data( 2,:)';  

  mwRTM_param.sand       = tmp_data( 3,:)';  
  mwRTM_param.clay       = tmp_data( 4,:)';    
  mwRTM_param.poros      = tmp_data( 5,:)';    

  mwRTM_param.wang_wt    = tmp_data( 6,:)';
  mwRTM_param.wang_wp    = tmp_data( 7,:)';

  mwRTM_param.rgh_hmin   = tmp_data( 8,:)';
  mwRTM_param.rgh_hmax   = tmp_data( 9,:)';
  mwRTM_param.rgh_wmin   = tmp_data(10,:)';
  mwRTM_param.rgh_wmax   = tmp_data(11,:)';
  mwRTM_param.rgh_Nrh    = tmp_data(12,:)'; 
  mwRTM_param.rgh_Nrv    = tmp_data(13,:)';  
  mwRTM_param.rgh_polmix = tmp_data(14,:)';  

  mwRTM_param.omega      = tmp_data(15,:)';  

  mwRTM_param.bh         = tmp_data(16,:)';  
  mwRTM_param.bv         = tmp_data(17,:)';    
  mwRTM_param.lewt       = tmp_data(18,:)'; 
  
else
  
  error('read_mwRTMparam.m: something wrong with file size or format')  
  
end
  
fclose(ifp);


% =========== EOF ===========================================
