function time_average_CL31(inname,outname,tave)
% time_average_CL31 - Averages CL31 structure to lower frequencies. Applies
% mean, mode averaging to selected structure fields, and applies special 
% procedure for sky condition variables.
% 
% time_average_CL31(inname,outname,tave)
%
% INPUTS:
% inname     - File to read in, should be native resoution (30s) file.
% outname    - Output file name. 
% tave       - length (minutes) of period to average data to.
%
% JZP February 2019, mod Apr 2022 & Feb 2024 SM

load(inname)

cl31in = cl31;
fields = fieldnames(cl31in);
% Set indexes of which fields to be meaned, mode, or vector averaged
meani = [1,2,4,5,6,9,11];
modei = 3;
           
% Index of fields to receive no averaging           
leaveind = 10;


% Define time step
intv = 1/(24*60/tave); % step through in tave minute blocks
% Find index of start of first hour
[~,~,~,~,min,~] = datevec(cl31in.mday);
startind = find(min==0,1,'first');
nblocks = round( ( cl31in.mday(end) - cl31in.mday(startind) ) / intv);
mindata = (tave/4) * 2; % minimum number of 30s data in a block to do average

% create blank output array
for nf = 1:length(fields)
    if ~ismember(nf,leaveind)
        cl31.(fields{nf}) = nan(nblocks,size(cl31in.(fields{nf}),2));
    end
end

disp('Averaging CL31 structure...')
for n = 1:nblocks
    sday = cl31in.mday(startind) + (n-1)*intv;
    eday = sday + intv;
    ii = cl31in.mday >= sday & cl31in.mday < eday;
    if sum(ii) > mindata
        
        Xout = structure_time_average(cl31in,ii,meani,modei);
        
        % sky condition algorithm uses data collected over previous 30 minutes, 
        % with double wieghted last 10 minutes
        if tave <= 20 % Select final value in averaging period
            ff = find(ii==1,1,'last');
            Xout.sc_frac = cl31in.sc_frac(ff,:);
            Xout.sc_ht = cl31in.sc_ht(ff,:);
        else % for longer periods, average all except first ten minutes
            sday2 = sday + 1/(24*6);
            ii2 = cl31in.mday >= sday2 & cl31in.mday < eday;
            Xout.sc_frac = mean(cl31in.sc_frac(ii2,:),'omitnan');
            Xout.sc_ht = mean(cl31in.sc_ht(ii2,:),'omitnan');
        end

        for nf = 1:length(fields)
            if ~ismember(nf,leaveind)
                cl31.(fields{nf})(n,:) = Xout.(fields{nf});
            end
        end
    end
end

cl31_av = cl31;
save(outname,'cl31_av')