
clear all
close all

%files to merge
CDOM_FN='EXPORTS-EXPORTSNP_SlowDROP_ACS_298_Dissolve_process_20180827_R2.txt';
wl=[398.4	401.9	405.5	409.1	412.6	416.2	420.3	424.4	428.6	432.7	436.6	440.3	444.8	449.5	453.9	458.2	462.4	466.8	471.3	475.7	480.4	485	489.4	493.5	497.9	502.4	506.8	511.4	515.9	520.6	524.9	529.1	533.4	537.5	541.6	545.6	549.8	554.1	558.6	562.7	566.8	570.7	574.4	578.1	579.5	583.4	587.3	591.5	595.9	600.1	604.5	608.8	613.4	617.7	622	626.2	630.5	634.5	638.7	643	647.3	651.7	656	660.5	664.9	669.1	673.7	677.8	681.7	685.9	689.8	693.9	697.8	701.7	705.5	709.5	713.4	716.9	720.5	724.6	728.4	731.9	735.6	738.9];
CPG_FN='Tot_cpg_20180827021.mat';
outfile='cp_20180827.txt';

%read CDOM files i
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')


