%clear all;

% takes four raw .wav files and syncs time and crops to equal size and
% outputs data and time. Also marks each gunshot in shot-times matrix and
% then outputs to gun_data.mat



mics= [1 2 3 4];
micoffsets = [15764451 13764742 9334032 6794611]; % first shot locations for syncing
recordings = ["mic1raw.wav","mic2raw16b.wav", "mic3raw.wav", "mic4raw.wav"];

    %disp('reading data');
    for i=1:4
        disp(strcat('reading gun ',num2str(i)));
        [y,Fs(i)] = audioread([recordings(i)], 'double');
        y = y((micoffsets(i)-500000):length(y)); %chop beginning
        y = [y(1:Fs(i)*200);y(Fs(i)*1200:Fs(i)*1600)]; %chop middle
        y = y(1:24e6);%chop end
        time_vector=transpose(1/Fs(i):1/Fs(i):length(y)/Fs(i));
        disp(strcat('finding shots gun ',num2str(i)));
        shot_times(i,:) = findshots(y, 25000, 22);
        disp(strcat('plotting data gun ',num2str(i)));
        subplot(4,1,i)
        plot(time_vector, y, time_vector(shot_times(i,:)),zeros(1,22),'+')
        data(i,:)=y;
        clear y;
        
    end
    disp('saving data');
    save('gun_data.mat', 'data', 'time_vector', 'shot_times', 'Fs');


%% functions below here



function tagged = findshots(data, min_time_btwn, NN)
%% function for making the boxcars for the training and the test data
    inboxcar = 0;
    k=0;
    j=1;
    tagged = [];
    for i=1:length(data)
        if ~inboxcar & abs(data(i))>= 0.8 & j<=NN
            inboxcar=1;
            k=1;
            tagged(j)=i;
        end
        if inboxcar
            k=k+1;
        end
        if k==min_time_btwn
            k=0;
            inboxcar=0;
            j=j+1;
        end
    end
end


%% misc utility functins
function [ cols ] = columns( cs )
   m = size(cs);
   cols = m(:,2);
end

function [ r ] = rows( cs )
   m = size(cs);
   r = m(:,1);
end


