function out = HRcalibrate(HR,calfile)
% HRcalibrate - Calibrates HR data passed from oasisHR2plot
% 
% Usage:  HR = HRcalibrate(HR,calfile)
%     HR          - data conforming to format specified below
%     calfile     - calibration file for HR data
% 
% Variable HR data format. Created by oasisHR2plot
%   HR(i).tStamp
%   HR(i).RawTime
%   HR(i).Temp
%   HR(i).Voltage
%   HR(i).Depth
%   HR(i).Process
%   HR(i).N
%   HR(i).Scale
%   HR(i).Do
%   HR(i).Dt
%   HR(i).IntTime
%   HR(i).FirstPix
%   HR(i).PixInc
%   HR(i).PixCount
%   HR(i).pixels
   
% Daniel Cosgrove
% 16 Apr 2002 

%-----------------------------------------------------------------------------
%Read in calibration file specified in calfile
%-----------------------------------------------------------------------------

[r c] = size(HR);

calfileID = fopen(calfile,'r');
fprintf('\nReading calibration file...');
while ~feof(calfileID)
    S = fgetl(calfileID);
    if findstr(S,'WAVE]')
        for p = 1:3
            S = fgetl(calfileID);
            W(p) = sscanf(S, '%f');
        end
    end
    if findstr(S, '<-F, C, epsilon,')
        pix = 1;
        while ~isempty(S)
            calstore = sscanf(S,'%f,%f,%f,%f');
            caldata(pix).F = calstore(1);
            caldata(pix).C = calstore(2);
            caldata(pix).e = calstore(3);
            caldata(pix).immer = calstore(4);
            pix = pix + 1;
            S = fgetl(calfileID);
        end
    end
end
fclose(calfileID);
fprintf('done\nCalabrating data...');

%-----------------------------------------------------------------------------
%Calibrate data
%-----------------------------------------------------------------------------
for k = 1:c-1
    for q = 1:HR(k).PixCount
        
        if q > length(HR(k).pixels)
            break
        end
        
        pixelNum = HR(k).FirstPix + HR(k).PixInc*q;
        
        HR(k).lambda(q) = W(1) + W(2) * pixelNum +...
            W(3) * pixelNum * pixelNum;
                
        HR(k).eu(q) = caldata(pixelNum).e *...
            caldata(pixelNum).immer *...
            HR(k).Scale * HR(k).pixels(q);
    end
end

out = HR;
fprintf('done\n');