function RI=read_ri(filename)
% Procedure to read in refractive index data file Filename (These
% files should have the filename extension .ri).
% 13-01-09 LC Created 

fh = fopen(filename, 'r');
if (fh==-1)
 disp('File not found.');
 return;
end
HL = 0; Vals=0; 
while ~feof(fh)
 ch = fgets(fh);
 if ch(1)=='#'
  HL=HL+1; % number of lines in header
 else
  Vals=Vals+1; % number of data rows
 end;
end

Tags={'DISTRIBUTEDBY','DESCRIPTION', 'SUBSTANCE', 'SAMPLEFORM', 'TEMPERATURE', 'CONCENTRATION', 'REFERENCE', 'DOI', 'SOURCE' , 'CONTACT', 'COMMENT' , 'FORMAT'};
for i=1:length(Tags), RI.(char(Tags{i}))=''; end;
RI.Vals=Vals;
Formattags={'Wavn','Wavl','N','dN','K','dK'};
for i=1:length(Formattags), RI.(char(Formattags{i}))=zeros(RI.Vals,1); end;

fseek(fh, 0, 'bof'); %Rewind
for i=1:HL %Read header
ch = fgetl(fh);
if ch(2)=='#', RI.(Tagname)=strcat(RI.(Tagname),ch(3:end)); continue; end;
k = strfind(ch,'='); 
Tagname=strtrim(upper(ch(2:k-1))); 
Tagvlue=strtrim(ch(k+1:end)); 
if ~ismember(Tags, Tagname) 
 sprintf('Warning in read_ri: %s tag unknown so ignored', Tagname)
else
 RI.(Tagname)=Tagvlue;
end;
end;
FMT=upper(strread(RI.FORMAT,'%s'));
data=textscan(fh,'%f'); data=reshape(data{1},length(FMT),RI.Vals)';
for i=1:length(FMT)
 RI.(char(Formattags{ismember(upper(Formattags), upper(FMT(i)))}))=data(:,i);
end;

if find(ismember(upper(FMT),'WAVN')) 
 RI.Wavl=10000./RI.Wavn;
else
 RI.Wavn=10000./RI.Wavl;
end;
fclose(fh); 
