function [datout, datout2, dS, dT]=TS_corr_acs(datin, channel, wl, S, T, Tcal)
% perform salinty and temperature correction of an AC-S.
% channel: 'a' for absorption, 'c' for attenuation.
% wl - wavelength
%Tcal - temperature where instrument is zeroed taken from device file
% T S - temperature from CTD

%from sullivan's 2006 paper
tmp = xlsread('Sullivan_etal_2006_instrumentspecific.xls');

phi_T=interp1(tmp(:,1),tmp(:,2),wl,'linear');
phi_Sc=interp1(tmp(:,1),tmp(:,4),wl,'linear');
phi_Sa=interp1(tmp(:,1),tmp(:,6),wl,'linear');

if channel=='a'
%first we use the measure values to correct
    for j=1:length(datin)     
        datout2(j,:)=datin(j,:)-phi_T*(T-Tcal)+phi_Sa*S;
    end
elseif channel=='c'
    for j=1:length(datin)     
        datout2(j,:)=datin(j,:)-phi_T*(T-Tcal)+phi_Sc*S;
    end
end
%then we do an additional correction

opts = optimset('fminsearch');      
opts = optimset(opts,'MaxIter',20000000); 
opts = optimset(opts,'MaxFunEvals',20000);
opts = optimset(opts,'TolX',1e-8);
opts = optimset(opts,'TolFun',1e-8);

I = find(wl>=710);  % spectral srange for optimization (710 to 750nm)   
    
delT = 0;
delS = 0;
offset = 0;

% minimization routine
if channel=='a'
    for j=1:length(datin)
        [x1] = fminsearch(@f_TS, [delT, delS, offset], opts, datin(j,I), phi_T(I), phi_Sa(I), wl(I));
        datout(j,:)=datin(j,I)+x1(1).*phi_T+x1(2).*phi_Sc
        dS(j)=x1(2);
        dT(j)=x1(1);
    end
elseif channel=='c'
    for j=1:length(datin)
        [x1] = fminsearch(@f_TS, [delT, delS, offset], opts, datin(j,I), phi_T(I), phi_Sc(I), wl(I));
        datout(j,:)=datin(j,I)+x1(1).*phi_T+x1(2).*phi_Sc
        dS(j)=x1(2);
        dT(j)=x1(1);
    end
    
    
end

