
clear all
close all

%files to merge
CDOM_FN='EXPORTS-EXPORTSNP_SlowDROP_ACS_301_Dissolve_process_20180817_R2.txt';
wl=[401.2	404.8	408	411.7	415.1	419	423.1	427.4	431.5	435	438.9	443.5	447.9	452.3	456.6	461	465.2	469.6	474.3	479.2	483.9	488	492.1	496.3	500.3	505	509.5	514.2	518.5	522.9	527.2	531.5	535.3	539.4	543.7	547.6	551.9	556.3	560.6	564.7	568.6	572.4	575.8	579.1	583	586.8	590.8	595.4	599.9	604.3	608.8	613.5	617.9	622.2	626.5	630.5	634.7	639	643.3	647.9	652.2	656.7	661.1	665.7	670	674.2	678.8	682.7	686.8	690.6	694.5	698.1	701.8	705.7	709.5	713.4	716.9	720.8	724.6	728.1	731.5	735.4];

CPG_FN='Tot_cpg_20180817012.mat';
outfile='cp_20180817.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')


