function zipfile = covis_decimate(filename, outputdir, decimation)
%
%
% ----------
% This program is free software distributed in the hope that it will be useful, 
% but WITHOUT ANY WARRANTY. You can redistribute it and/or modify it.
% Any modifications of the original software must be distributed in such a 
% manner as to avoid any confusion with the original work.
% 
% Please acknowledge the use of this software in any publications arising  
% from research that uses it.
% 
% ----------
%  Version 1.0 - 10/2010,  cjones@apl.washington.edu
%  Version 1.1 - 10/2011,  cjones@apl.washington.edu
%

global Verbose;
Verbose = 1;
zipfile = 0;

if(decimation < 1 )
    return;
end

% decimation filter parameters
filt.type = 'butterworth';
filt.bw = 2;  % Bandwdith is filt_bw/tau
filt.order = 4;
filt.decimation = decimation;

% Extract a COVIS archive, if it hasn't been unpacked already
[swp_path, swp_name] = covis_extract(filename, outputdir);
swp_dir = fullfile(swp_path, swp_name);

% check that archive dir exists
if(~exist(swp_dir))
    error('Sweep directory does not exist\n');
    return;
end

% set sweep path and name
swp.path = swp_path;
swp.name = swp_name;

% directory list of *.bin fileq
file = dir(fullfile(swp_dir, '*.bin'));
nfiles = length(file);

% loop over ping files
for n=1:nfiles

    % parse filenames
    bin_file = file(n).name;
    [type,ping_num] = strread(bin_file,'rec_%d_%d.bin');
    json_file = sprintf('rec_7000_%06d.json',ping_num);

    % read raw element quadrature data
    [hdr, data] = covis_read(fullfile(swp_dir, bin_file));

    % read ping meta data from fson file
    json_str = fileread(fullfile(swp_dir, json_file));
    json = parse_json(json_str);
    png.hdr = json.hdr;

    % Correct phase using first ping as reference
    %data = covis_phase_correct(png, monitor, data);

    bw = filt.bw;                  % Bandwdith is filt_bw/tau
    tau = png.hdr.pulse_width;     % Pulse length (sec)
    fsamp = png.hdr.sample_rate;   % Complex sampling frequency (Hz)
    order = filt.order;
    R = filt.decimation;
    new_fsamp = fsamp/R;
    f_cutoff = bw/fsamp/tau;

    % check first ping and make new archive dir for the decimated data
    % the new archive name will be the original name with the sampling rate
    if(n == 1)
        new_swp_name = [swp_name '_' num2str(fix(new_fsamp/1000)) 'K'];
        new_swp_dir = fullfile(swp_path, new_swp_name);
        fprintf('Creating new archive %s\n', new_swp_dir);
        if(~exist(new_swp_dir,'dir'))
            success = mkdir(swp_path, new_swp_name);
            if(success < 1)
                fprintf('Problem creating new archive %s\n', new_swp_dir);
                return;
            end
        end
        % copy needed files into new dir
        copyfile(fullfile(swp_dir, 'sweep.json'), fullfile(new_swp_dir, 'sweep.json'),'f');
        copyfile(fullfile(swp_dir, 'rotator.csv'), fullfile(new_swp_dir, 'rotator.csv'),'f');
        copyfile(fullfile(swp_dir, 'index.csv'), fullfile(new_swp_dir, 'index.csv'),'f');
        copyfile(fullfile(swp_dir, 'position.csv'), fullfile(new_swp_dir, 'position.csv'),'f');
    end
    
    switch lower(filt.type)
        case {'butterworth'}
            [B,A] = butter(order, f_cutoff);
        otherwise
            disp('Unknown filter type');
    end
        
    if(Verbose)
        fprintf('Decimating %s from %dkHz to %dkHz\n', bin_file, fix(fsamp/1000), fix(new_fsamp/1000));
    end

    % Apply Filter to data
    data = filter(B, A, data);

    % decimate
    data = data(1:R:end,:);

    % update new sampling freq
    png.hdr.sample_rate = new_fsamp; 

    % write raw element quadrature data
    covis_write(fullfile(new_swp_dir, bin_file), hdr, data);

    % update json str  with new sample rate
    % and overwrite json file
    % this should be replace with a json_write function
    m1 = strfind(json_str,'"sample_rate"');
    m2 = strfind(json_str(m1:end),',');
    str1 = json_str(m1+(0:(m2(1)-1)));
    str2 = sprintf('"sample_rate": %.6f,', png.hdr.sample_rate);
    json_new = strrep(json_str, str1, str2);
    fp = fopen(fullfile(new_swp_dir, json_file),'w');
    fwrite(fp, json_new, 'char');
    fclose(fp);

end

% create a new ZIP archive for the decimated data
fprintf('Creating new ZIP archive %s\n', new_swp_dir);
zip(new_swp_dir, new_swp_dir);

% check that new archive dir exists
zipfile = [new_swp_dir '.zip'];
if(~exist(zipfile))
    error('Failed to make new zip archive');
    zipfile = 0;
    return;
end

end


