%% create a struct with timestamps of all neurons and events

%before starting:
%put all nex files in the same folder
%name of each file starts with "NA1" or corresponding region and rat
%for water and 3 rewards sessions, "WA1" or "TH1" (all VP)

%need supporting programs "readNexFile" and "myfind"

clear all;clc 
SAVE_FLAG=1;
tic

address=['C:\Users\dottenh2\Documents\MATLAB\David\2Rewards Nex Files'];

AF=dir([address,'\\*.nex']);
Sesnum=0;
for k=1:length(AF)
      
        fname=AF(k).name;
        [nexfile] = readNexFile([address,'\\',fname]);  fprintf([fname,'\n'])
        Iind=myfind(nexfile.intervals,'AllFile'); 
        Sesnum=Sesnum+1;
        % Get all events timestamps for the selected session
        NUM_EVENTS=length(nexfile.events);
        for j=1:NUM_EVENTS
            evt=nexfile.events{j}.timestamps;
            RAW(Sesnum).Erast{j,1}=evt(find((evt>nexfile.intervals{Iind}.intStarts) & (evt<nexfile.intervals{Iind}.intEnds)));
            RAW(Sesnum).Einfo(j,:)={fname,nexfile.events{j}.name};
        end
        % start from neuron 1 get ready for the next session
        
        % Get the Neuron timestamps and waveforms
       NUM_NEURONS=length(nexfile.neurons);
        for j=1:NUM_NEURONS
            nrn=nexfile.neurons{j}.timestamps;
            RAW(Sesnum).Nrast{j,1}=nrn(find((nrn>nexfile.intervals{Iind}.intStarts) & (nrn<nexfile.intervals{Iind}.intEnds)));
            RAW(Sesnum).Ninfo(j,:)={fname,nexfile.neurons{j}.name};
        end
        
        RAW(Sesnum).Type=fname(1:3);
    
end
toc   
%% SAVING DATA
if SAVE_FLAG
    save('RAW.mat','RAW')
end
fprintf('\n')
toc
