%% average all files in string " folder" at int "frequency" in days
% inputs: folder: folder containing binary files to be averaged
%           frequency: number of days to average over
%           siz: grid size of binary files (include 3rd dimension even if
%           it's 1)


function avgBin(folder,frequency,siz)

fnames = dir([folder '/*.2*']);
numFiles = length(fnames);
tot = zeros(siz);

f1 = fnames(1).name;
avgFldr = [folder '/' num2str(frequency) '_day_averages'];
eval(['mkdir ' avgFldr]);

for ii = 1 : numFiles % each file is 1 hr apart
    fnam = [folder '/' fnames(ii).name];
    fld = readbin(fnam,siz);
    tot = tot + fld;
    if mod(ii,frequency*24) == 0
        aBin = tot./(24*frequency);
        fileName = [avgFldr '/' num2str(frequency) 'day_' f1];
        writebin(fileName,aBin);
        tot = zeros(siz);
        f1 = fnames(ii+1).name;
    end
    
end
end
