%% This script is for plotting the acoustic data; Note, you will need to change the path for lines 3,6,and 9 

runacpath='/Volumes/PC/Experiments/p4581/run1/WF_'; % path where the .ac files live

% acoustic parameters
load('ACTimeVector_4581.mat'); % load in the acoustic time vector data;
ts=ts_adjusted; % offset for time vector

acSettings = load('p4581_AE.mat');              % load acoustic settings
numSFpfile = acSettings.numFrames/2;            % number of superframes per file
numWFpSFpCH = acSettings.numAcqs;               % number of WF per superframe and per channel
numWFpfilepCH = numSFpfile*numWFpSFpCH;         % number of WF per file and per channel
numCH = length(acSettings.channels2save);       % number of channels
WFlength = acSettings.Nsamples;                 % segment length
ts = ts/1e6;                                    % from microsec to sec
fs = 1/ts;                                      % acoustic sampling rate
%clear acSettings

AtWhichTimes=[4100]; % Time section to analyze data; Change this to plot different time intervals

% time vector for each waveform
timeWF = (0:WFlength-1)'*ts;
N = length(AtWhichTimes);
AETime = NaN(WFlength*numWFpfilepCH,1);
 
for ii =1:N

    idxAcTime = find(acTime > AtWhichTimes(ii),1,'first'); %find the next index over from the time at which you want to analyze   
    
    if acTime(1) > AtWhichTimes(ii)      
        error(['The first value of ''AtWhichTimes'' is too small. No acoustic data at time ' num2str(AtWhichTimes(1)) 's.']);
    elseif acTime(end) < AtWhichTimes(ii)
        error(['The last value of ''AtWhichTimes'' is too large. No acoustic data at time ' num2str(AtWhichTimes(end)) 's.']);
    end             
    
    filenumber = ceil(idxAcTime/numWFpfilepCH); % file number for WF   
     
    % build time vector for each file   
    for jj = 1:numWFpfilepCH
        AETime((jj-1)*WFlength+1:jj*WFlength) = acTime((filenumber-1)*numWFpfilepCH+jj) + timeWF;
    end    
    
    
    ACfilename = [runacpath num2str(filenumber) '.ac'];
    fid = fopen(ACfilename,'r');
    ACdata = fread(fid,'int16');   
    fclose(fid);
    % reshape to get one column per channel
    ACdata = reshape((ACdata),[],numCH,numSFpfile); % 3D matrix with WF vs Channel vs number of SF
    ACdata = permute(ACdata,[1 3 2]); % put Channel as the last dimension before reshaping
    ACdata = reshape(ACdata,[],numCH,1); % WF vs Channel  
    
     figure;
     plot(AETime,ACdata(:,1)); hold on % plot channel 1
end