%% CLAP
[clapdata, clapinfo] = ARM_CDF_Import('E:\Google Drive\Projects\HI-SCALE SGP\Data\ARM_Data\CLAP');


%% NOT SURE IF THIS IS NEEDED
% %% Filter transmission correction
% clap_rawabsnames = {'Ba_R_CLAP3W','Ba_G_CLAP3W','Ba_B_CLAP3W'};
% clap_absnames = {'rpsap'
% clapdata.

%% Removing bad data points from absorbance data
clap_absnames = {'Ba_R_CLAP3W','Ba_G_CLAP3W','Ba_B_CLAP3W'};
for absname_idx = 1:3
	clapdata.(clap_absnames{absname_idx}) = double(clapdata.(clap_absnames{absname_idx}));
	clapdata.(clap_absnames{absname_idx})(clapdata.(clap_absnames{absname_idx}) == -9999) = NaN;
end

%% Removing flagged data points (filter change, bad temperature, flow sensor etc
clap_badbits = [1,2];
for clapbits_idx = 1:length(clap_badbits)
	for absname_idx = 1:3
		clapdata.(clap_absnames{absname_idx})(bitget(clapdata.instrument_flags,ones(size(clapdata.instrument_flags)).*clap_badbits(clapbits_idx)) == 1) = NaN;
	end
end

%% Negative absorbances are bad
clapdata.Ba_R_CLAP3W(clapdata.Ba_R_CLAP3W < 0) = NaN;
clapdata.Ba_B_CLAP3W(clapdata.Ba_B_CLAP3W < 0) = NaN;
clapdata.Ba_G_CLAP3W(clapdata.Ba_G_CLAP3W < 0) = NaN;

%% Removing 5 minute window around each hour
% There seems to be an issue where the absorbance drops to below 0 every
% hour at 1:00, 2:00 etc (almost every time)
clap_badminutes = [57, 58, 59, 0, 1, 2];
clap_datevec = datevec(clapdata.realtime);
clap_filtnames = {'rfilt','gfilt','bfilt'};
for absname_idx = 1:3
	clapdata.(clap_absnames{absname_idx})(ismember(clap_datevec(:,5),clap_badminutes)) = NaN;
	
	% Median filtering
	clapdata.(clap_filtnames{absname_idx}) = medfilt1(clapdata.(clap_absnames{absname_idx}),'omitnan');
end

%% Interpolates absorbance channels to deal with NaNs
clap_abspts = 1:length(clapdata.Ba_R_CLAP3W);
clap_interpnames = {'rinterp', 'ginterp','binterp'};
for absname_idx = 1:3
	clapdata.(clap_interpnames{absname_idx}) = interp1(clap_abspts, clapdata.(clap_filtnames{absname_idx}), clap_abspts, 'pchip');
	clapdata.(clap_interpnames{absname_idx})(clapdata.(clap_interpnames{absname_idx}) < 0) = 0;
end



clapdata.aae_rb_absinterp = -log(clapdata.rinterp./clapdata.binterp)./log(660./447);
clapdata.aae_rb_absinterp(imag(clapdata.aae_rb_absinterp) ~= 0) = NaN;

clapdata.aae_rb = -log(clapdata.Ba_R_CLAP3W./clapdata.Ba_B_CLAP3W)./log(660./447);
clapdata.aae_rb(imag(clapdata.aae_rb) ~= 0) = NaN;

clapdata.aae_rb_interp = interp1(clap_abspts, clapdata.aae_rb, clap_abspts,'pchip');
% figure; plot(clapdata.realtime,clapdata.aae_rb_interp); maxfig(gcf,1);

[clapdata.avgtime, clapdata.avgaae] = RollingAverage(clapdata.realtime,clapdata.aae_rb_interp,30);

% figure; plot(clapdata.avgtime,clapdata.avgaae); maxfig(gcf,1);

