% 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_MF20111214(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
    

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

        clearvars -except i j h chunksize fid_prefix fidlist fpath spath T0 channel time threshold waveform tmp
        
        % Get name of spike file
        fid = fidlist{i}

        % Finding fid name based on location of underscores
        uscloc = strfind(fid,'_');
        if length(uscloc)==1
            fidsave = fid;
        else
            fidsave = fid(1:uscloc(2)-1);
        end
        
        % 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)
        starttime = etime(T,T0);
        s.time = s.time + starttime;

        for j = 1:ceil(lastspk/3600)
            
            % 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
                channel = tmp.channel;
                time = tmp.time;
                threshold = tmp.threshold;
                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');
                save([spath fid_prefix '_' num2str(chunksize*(h-1)) 'to' num2str(chunksize*(h)) 'hr' '.mat'],'channel','time','threshold','waveform');
                
                % 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/3600)
                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
                channel = [tmp.channel; s.channel(mask)];
                time = [tmp.time; s.time(mask)];
                threshold = [tmp.threshold; s.threshold(mask)];
                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');
                save([spath fid_prefix '_' num2str(chunksize*(h-1)) 'to' num2str(chunksize*(h)) 'hr' '.mat'],'channel','time','threshold','waveform');
                  h = h+1;
            end
        end
    end
end