
clear all
close all

%files to merge
CDOM_FN='EXPORTS-EXPORTSNP_SlowDROP_ACS_024_Dissolve_process_20180818_R2.txt';
wl=[399.8	404.6	408.7	413	418	423.1	427.6	431.8	436.1	440	445.3	450	454.6	459.2	464	468.7	473.4	478	482.9	487.6	492.3	496.8	501.2	506.1	510.9	515.9	520.6	525.8	530.4	534.2	538.7	543.3	547.6	552.4	556.9	560.3	564.5	569.1	573.7	577.8	581.9	585.9	590.5	595.4	600.1	604.6	609.5	614.2	618.7	623.5	628.2	633	637.5	642.3	646.9	651.7	656.3	661.1	665.7	670.3	675.2	679.4	683.5	687.9	691.9	695.8	699.7	703.8	707.9	711.5	714.8	718.2	721.9	725.6	729.2	732.3	735.8	738.6	741.9	744.6	748.1	750.6	752.8	755.4];

CPG_FN='Tot_cpg_20180818020.mat';
outfile='cp_20180818.txt';

%read CDOM files in
data=read_sb(CDOM_FN);
[m,n]=size(data);

p=data{4:m,1};
FL=str2double(data{4:m,2});
T=str2double(data{4:m,3});
S=str2double(data{4:m,4});
NN=length(wl);
ag=str2double(data{4:m,5:5+NN-1});
ag_std=str2double(data{4:m,5+NN:5+2*NN-1});

load(CPG_FN)

cg=interp1(wl,ag',wlc,'linear')';
cg_=interp1(p,cg,prrT,'linear');
cg_std=interp1(wl,ag_std',wlc,'linear')';
cg_std_=interp1(p,cg_std,prrT,'linear');

plot(wlc,c_pg-cg_)
cp=c_pg-cg_;
stdcp=sqrt(cal_c_unc.^2+cg_std_.^2);

I=isfinite(cp(:,10));
J=isfinite(cp(20,:));
wlcp=wlc(J);

%Global parameters
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);
gamma0=-1;
L=find(I==1);
for j=1:length(L)
    amp0=cp(L(j),20);
    K=find(wlcp>420 & wlcp<700);
    [x1 Fval] = fminsearch(@least_squares_cp, [amp0, gamma0], opts, cp(L(j),K), stdcp(L(j),K),wlcp(K));
    gamma(j)=x1(2);
    cp650(j)=x1(1);
end
 

A=[prrT(I)', datT(I,3), datT(I,4), gamma', cp(I,J), stdcp(I,J)];

save(outfile, 'A', '-ascii', '-tabs')


