% LOADSPKCHUNK is a function for loading long Neurorighter *.spk files and
% dividing them into a series of smaller files based on time
%
% FID_PREFIX is the culture/MEA identifier typically used to name files
%
% CHUNKSIZE is the length of the smaller files in hours.  If not value is
% specified, CHUNKSIZE is set to 1 hour.


function loadspkChunk_haruki17898b(fid_prefix, chunksize)

    % Default CHUNKSIZE is 1 hour
    if nargin < 2
        chunksize = 1;
    end

    % Initialize variables
    channel = [];
    time = [];
    threshold = [];
    waveform = [];
    %unit = [];
    tmp.channel = [];
    tmp.time = [];
    tmp.threshold = [];
    tmp.waveform = [];
    %tmp.unit = [];

    h = 1;

    % Set filepaths and identify files to process
    fpath = ['C:\Users\USER\Documents\mingfaifong\' fid_prefix '\spkfiles\'];
    spath = ['C:\Users\USER\Documents\mingfaifong\' fid_prefix '\matfiles\']; mkdir(spath);
    fpath_info = dir(fpath);      %get info about contents of directory
    isfile = ~[fpath_info.isdir]; %get index for files only
    fidlist = {fpath_info(isfile).name}; %create list of files
    
    % Define wells
    w(1,:) = [3 4 5 12 13 20 21 28 29];
    w(2,:) = [7 14 15 16 22 23 24 30 31];
    w(3,:) = [38 39 40 46 47 48 55 56 63];
    w(4,:) = [36 37 44 45 52 53 60 61 62];
    w(5,:) = [34 35 41 42 43 49 50 51 58];
    w(6,:) = [2 9 10 17 18 19 25 26 27];
    w_label = {'wA','wB','wC','wD','wE','wF'};

    

    % Open files and save chunks of data
    for i = 1:length(fidlist)

        clearvars -except i j h chunksize fid_prefix fidlist fpath spath T0 tmp w w_all w_label
        
        % Get name of spike file
        fid = fidlist{i}

        % Load file and find the time of the last spike
        
        %s = loadspk([fpath fid]);
        s = load([fpath fid]);
        %lastspk = max(s.time);
        
        % Determine start time of recording file
        T = [];
        starttime = s.meta.date
        rest = starttime;
        while ~isempty(rest)
            [token rest] = strtok(rest,'-');
            T = [T str2double(token)];
        end

        %set T0 as time of first file
        if i == 1
            T0 = T;
        end
        
        % Shift time to be relative to beginning of experiment (rather than
        % beginning of recording time)
        s.time = s.time + etime(T,T0);
        firstSpk = min(s.time)/3600
        lastSpk = max(s.time)/3600

        for j = ceil(firstSpk/chunksize)*chunksize:chunksize:ceil(lastSpk/chunksize)*chunksize
            
            % When the first spike time of the new recording exceeds that
            % current chunksize, save data from previous recording before
            % continuing.
            if min(s.time) > chunksize*h*3600
                w_all.channel = tmp.channel;
                w_all.time = tmp.time;
                w_all.threshold = tmp.threshold;
                w_all.waveform = tmp.waveform;
                %unit = tmp.unit;
                tmp.channel = [];
                tmp.time = [];
                tmp.threshold = [];
                tmp.waveform = [];
                %tmp.unit = [];
                %save([spath fid_prefix '_' num2str(chunksize*(h-1)) 'to' num2str(chunksize*(h)) 'hr' '.mat'],'channel','time','threshold','waveform', 'unit');
                for i = 1:6
                    time = w_all.time(ismember(w_all.channel,w(i,:))==1);
                    channel =  w_all.channel(ismember(w_all.channel,w(i,:))==1);
                    waveform = w_all.waveform(:,ismember(w_all.channel,w(i,:))==1);
                    threshold =  w_all.threshold(ismember(w_all.channel,w(i,:))==1);
                    save([spath fid_prefix '_' w_label{i} '_' num2str(chunksize*(h-1)) 'to' num2str(chunksize*(h)) 'hr' '.mat'],'channel','time','threshold','waveform');
                    clear time channel waveform threshold;
                end
                
                % The h index gets increments up until CHUNKSIZE*H*3600 is
                % in range for the newly-opened recording contained in the
                % S structure
                while min(s.time) > chunksize*h*3600
                    h = h+1;
                end
            end
            
            disp(['h=' num2str(h) ', j=' num2str(j)]);
            
            % Defining time window for when data should be saved, where h
            % is the number of CHUNKSIZEs that have passed so far
            mask = s.time < chunksize*h*3600 & s.time > chunksize*(h-1)*3600;

            % When the hour containing the last spike has been reached,
            % save remaining data to the TMP structure
            if j == ceil(lastSpk/chunksize)*chunksize
                tmp.channel = s.channel(mask);
                tmp.time = s.time(mask);
                tmp.threshold = s.threshold(mask);
                tmp.waveform = s.waveform(:,mask);
%                 if s.unit
%                     tmp.unit = s.unit(mask);
%                 else
%                     tmp.unit = [];
%                 end

            % In any other cases, any data contained in the TMP structure
            % (e.g. from a previous recording) is concatenated to the front
            % of the corresponding S structure variables.
            else
                w_all.channel = [tmp.channel; s.channel(mask)];
                w_all.time = [tmp.time; s.time(mask)];
                w_all.threshold = [tmp.threshold; s.threshold(mask)];
                w_all.waveform = [tmp.waveform s.waveform(:,mask)];
%                 if s.unit
%                     unit = [tmp.unit; s.unit(mask)];
%                 else
%                     unit = [];
%                 end
                tmp.channel = [];
                tmp.time = [];
                tmp.threshold = [];
                tmp.waveform = [];
%                 tmp.unit = [];

                % Saving one CHUNKSIZE of data!
%                 save([spath fid_prefix '_' num2str(chunksize*(h-1)) 'to' num2str(chunksize*(h)) 'hr' '.mat'],'channel','time','threshold','waveform', 'unit');
                for i = 1:6
                    time = w_all.time(ismember(w_all.channel,w(i,:))==1);
                    channel =  w_all.channel(ismember(w_all.channel,w(i,:))==1);
                    waveform = w_all.waveform(:,ismember(w_all.channel,w(i,:))==1);
                    threshold =  w_all.threshold(ismember(w_all.channel,w(i,:))==1);
                    save([spath fid_prefix '_' w_label{i} '_' num2str(chunksize*(h-1)) 'to' num2str(chunksize*(h)) 'hr' '.mat'],'channel','time','threshold','waveform');
                    clear time channel waveform threshold;
                end
                  h = h+1;
            end
        end
    end
end