
clear
close all

% use example output from 
trex = readtable('MSC_examp_reply_blank_samp.txt');

Istray = 150; % from addition of mcresol purple; about 40-50.

MMS.Dark = trex{:,17}';
% MMS.I_blank = trex{1,10:end}';
% MMS.I_blank_D = MMS.I_blank - MMS.Dark(1); 
MMS.HexIntens = trex{:,21}';
for i = 1:length(MMS.Dark)
    steg = MMS.HexIntens{i};
    for ii = 1:length(steg)/4
        istart = (ii-1)*4+1;
        MMS.I(i,ii) = hex2dec(steg(istart:istart+3));
    end
end

MMS.I = MMS.I';
MMS.I_D = MMS.I - MMS.Dark;
MMS.I_D_S = MMS.I_D - Istray;
% average sample intensity, with and without straylight
MMS.Iblank = mean(MMS.I_D(:,1:3),2);
MMS.Iblank_S = mean(MMS.I_D_S(:,1:3),2);
% average sample intensity, with and without straylight
MMS.Isamp = mean(MMS.I_D(:,4:5),2);
MMS.Isamp_S = mean(MMS.I_D_S(:,4:5),2);

MMS.A = log10(MMS.Iblank./MMS.Isamp);
MMS.A_S = log10(MMS.Iblank_S ./ MMS.Isamp_S);

% now do intensity and absorbance correction for polychromatic light

% Lamda calculation
% UVVIS1. Pretty sure this is the correct UVVIS 
C0 = +2.455646892E+02;
C1 = +2.136483472E+00;
C2 = +1.005266419E-04;
C3 = -7.432017061E-07;
C4 = +0.0;

X = [1:256]'; 
MMS.Lambda = C0 + C1.*X + C2.*X.^2 + C3.*X.^3;

% apply polychromatic correction
npixel = 5;
sigma = 4; 
% do polychromatic correction
MMS.Iblank_mono =  correct_polychromatic_light(MMS.Lambda, MMS.Iblank, npixel, sigma);
MMS.Iblank_S_mono =  correct_polychromatic_light(MMS.Lambda, MMS.Iblank_S, npixel, sigma);
MMS.Isamp_mono =  correct_polychromatic_light(MMS.Lambda, MMS.Isamp, npixel, sigma);
MMS.Isamp_S_mono =  correct_polychromatic_light(MMS.Lambda, MMS.Isamp_S, npixel, sigma);
MMS.A_mono_direct =  correct_polychromatic_light(MMS.Lambda, MMS.A, npixel, sigma);
MMS.A_S_mono_direct =  correct_polychromatic_light(MMS.Lambda, MMS.A_S, npixel, sigma);


MMS.A_mono = log10(MMS.Iblank_mono ./ MMS.Isamp_mono);
MMS.A_S_mono = log10(MMS.Iblank_S_mono ./ MMS.Isamp_S_mono);


X = 400:1:800;
Y = NaN(6,length(X));

Y(1,:) = interp1(MMS.Lambda, MMS.A_S, X, 'Spline');
Y(2,:) = interp1(MMS.Lambda, MMS.A, X, 'Spline');
Y(3,:) = interp1(MMS.Lambda, MMS.A_mono, X, 'Spline');
Y(4,:) = interp1(MMS.Lambda, MMS.A_S_mono, X, 'Spline');
Y(5,:) = interp1(MMS.Lambda, MMS.A_mono_direct, X, 'Spline');
Y(6,:) = interp1(MMS.Lambda, MMS.A_S_mono_direct, X, 'Spline');

Y = Y';

A4pH = Y([35 88 179 331],:);

pH = calc_spec_pH(A4pH, 33.5, 20, [0 0], 1);

trex = pH - pH(1)

    % Abs contains the absorbances at specific wavelenghts:
%       A(1,n) = A434;
%       A(2,n) = A487; (isosbestic wavelength. used for dye correction)
%       A(3,n) = A578;
%       A(4,n) = A730; (Or the "blank" wavelength)

    




% 
% 
% MMS.Araw = log10(MMS.I_D(:,1) ./ MMS.I_D(:, 2:end));
% 



















