Contents

SET FILE NAMES ACCORDING TO FOLDER NAME

back to top
      % Get directory of folders in Group
      % Index through folder list, copy name of folder
      % Index inside folder through all file names and rename each file
      % Use the '_' token as a marker
      % Example
      % Folder name: 'T-4-944-P30'
      % File name: 'T-4-944-P35_0001.abf'
      %            'T-4-944-P35_0001_autoEventStats.abf'
      %            'T-4-944-P35_0001_Events.abf'
      %
      % Folder name: 'T-4-944-P30'
      % File name: 'T-4-944-P30_0001.abf'
      %            'T-4-944-P30_0001_autoEventStats.abf'
      %            'T-4-944-P30_0001_Events.abf'
      %
      % Copy entire folder name = part1
      % Copy file name after '_' token = part2
      % Combine [part1, part2] and rename file
      % MAKE LIST OF EXISTING DATA FOLDERS
      % Folder names with all data
      % '...\EPC\Group 1'
      % '...\EPC\Group 2'
      % '...\MEPPs\Group 1'
      % '...\MEPPs\Group 2'
      % loop through existing data folders
      myGroups = {'\EPCs\Group 1';...
      '\EPCs\Group 2';...
      '\MEPPs\Group 1';...
      '\MEPPs\Group 2'};
      % loop through all groups
      for n = 1:size(myGroups,1)
      % make list from directory append above to pwd
      currentFolder = pwd;
      searchFolder = [pwd, myGroups{n}]; %change to change folder
      % get list of searchfolder contents using dir command
      searchDir = dir(searchFolder);
      % get rid of hidden files and folders
      searchDirtemp = struct('name',{}, 'date',{}, 'bytes',{}, 'isdir',{}, 'datenum',{});
      Dircount = 1; %initialize Dircount
      for k = 1:length(searchDir)
      if strcmpi(searchDir(k).name,'.') || strcmpi(searchDir(k).name,'..') || ~searchDir(k).isdir
      continue; %skip if hidden dir found
      else
      searchDirtemp(Dircount,1) = searchDir(k);
      Dircount = Dircount +1;
      end
      end
      searchDir = searchDirtemp;
      clear searchDirtemp Dircount
      % GO THROUGH CONTENTS OF EACH FOLDER, EX: '...\EPC\Group 1'
      % Generate directory of fies and then index through all files
      for j =  1:length(searchDir)
      filePath = [searchFolder, '\', searchDir(j).name]; %get path to file location
      fileDir = dir(filePath); %get list of all files in path
      fileDirtemp = struct('name',{}, 'date',{}, 'bytes',{}, 'isdir',{}, 'datenum',{}); %preallocate structure for file directory list
      filecount = 1; %initialize file counter
      % loop through list, and remove hidden files/folders from list
      for k = 1:length(fileDir)
      if strcmpi(fileDir(k).name,'.') || strcmpi(fileDir(k).name,'..') %hidden files/folders are called '.' or '..'
      continue; %skip if hidden dir found and do not increment file counter
      else
      fileDirtemp(filecount,1) = fileDir(k); %populate temp file directory list
      filecount = filecount + 1; %increment conter
      end
      end
      fileDir = fileDirtemp; % reassign variable
      clear fileDirtemp filecount%remove unused variable
      % Loop through each file in fileDir and use folder name from
      % searchDir to rename each file
      for k = 1:length(fileDir)
      % rename file, combining folder name and part of old file name
      oldfileName = fileDir(k).name; %old file name
      newName1 = searchDir(j).name; %part1 of new file name
      newName2temp = oldfileName; %make temp variable for part2 of new file name
      newName2ind = strfind(newName2temp,'_'); %find all indices of '_' token
      newName2 = newName2temp(newName2ind:end); %get part of file name after first '_' token
      newfileName = [newName1, newName2]; %combine parts
      % move file if newfileName is different form oldfileName
      if ~strcmp(newfileName,oldfileName)
      movefile([filePath, '\', oldfileName], [filePath, '\', newfileName]); %move new '.mat' file to original file location
      end
      end
      end
      end
      

REGENERATE AUTOEVENTSTATS FILE, SPECIFICALLY EVENTDATASTATS

back to top
% NEW RESAMPLING AND NEW CRITERIA FOR CURVE FITTING & AUC & AMP
% 08-May-2014 07:16:41
% Scan all .mat files that only have a file name:
% 'T-19-P30_0001_autoEvents.mat'
% use the 'autoEvents.mat' string to identify files of interest

%  MAKE LIST OF EXISTING DATA FOLDERS
% Folder names with all data
% '...\EPC\Group 1'
% '...\EPC\Group 2'
% '...\MEPPs\Group 1'
% '...\MEPPs\Group 2'
% loop through existing data folders
clear all
myGroups = {'\EPCs\Group 1';...
            '\EPCs\Group 2';...
            '\MEPPs\Group 1';...
            '\MEPPs\Group 2'};
%
% make list from directory append folder names with all data to pwd
for n = 1:size(myGroups,1)
    currentFolder = pwd;
    searchFolder = [pwd myGroups{n}]; %change to change folder
    % get list of searchfolder contents using dir command
    searchDir = dir(searchFolder);
    % get rid of hidden files and folders
    searchDirtemp = struct('name',{}, 'date',{}, 'bytes',{}, 'isdir',{}, 'datenum',{});
    Dircount = 1; %initialize Dircount
    for k = 1:length(searchDir)
        if strcmpi(searchDir(k).name,'.') || strcmpi(searchDir(k).name,'..') || ~searchDir(k).isdir
            continue; %skip if hidden dir found
        else
            searchDirtemp(Dircount,1) = searchDir(k);
            Dircount = Dircount +1;
        end
    end
    searchDir = searchDirtemp;
    clear searchDirtemp Dircount
    % index through the directories and files, generate '...autoEventStats.mat'
    % extract myEvents [#x3] and regenerate EventDataStats variable
    % use getEventStats function and resave autoEventDataStats
    for j =  1:length(searchDir) %index through folders
        fileDirtemp = struct('name',{}, 'date',{}, 'bytes',{}, 'isdir',{}, 'datenum',{});
        filecount = 1; %initialize folder count
        fileDir = dir([searchFolder, '\', searchDir(j).name]);
        for k = 1:length(fileDir)
            if strcmpi(fileDir(k).name,'.') || strcmpi(fileDir(k).name,'..')
                continue; %skip if hidden dir found
            else
                fileDirtemp(filecount,1) = fileDir(k);
                filecount = filecount + 1;
            end
        end
        fileDir = fileDirtemp;
        % find all files with string 'autoEventStats.mat' and generate
        for k = 1:length(fileDir) %index through files
            if ~isempty(strfind(fileDir(k).name,'_autoEventStats.mat')) %if the current file in loop contains '_autoEventStats.mat'
                Eventsfile = fileDir(k).name; % get name of the '_autoEventStats.mat' file
                cellnameidx = strfind(Eventsfile,'_autoEventStats.mat'); % find index in file name where '_autoEventStats.mat' begins
                cellname = Eventsfile(1:cellnameidx(end)-1); % cellname is all string data before last index of '_'
                limitsCrop = []; % initialize variable because all 'autoEventStats.mat' contain a variable 'limitsCrop'
                peakThreshold = []; % initialize variable because all 'autoEventStats.mat' contain a variable 'peakThreshold'
                abfFile = [cellname,'.abf']; % generate the name of the associated .abf file
                movefile([searchFolder, '\', searchDir(j).name, '\', Eventsfile], pwd) % move .mat file
                copyfile([searchFolder, '\', searchDir(j).name, '\', abfFile], pwd) % copy .abf file
                load(Eventsfile); % load data in '_autoEventStats.mat' file
                % return file and go to next loop if file corrupt
                if exist('fileCorrupt','var')
                    movefile(Eventsfile, [searchFolder, '\', searchDir(j).name]); % move the autoEventStats.mat file
                    clear fileCorrupt
                    delete(abfFile);
                    continue
                end
                % load .abf .mat files. regenerate autoEventStats.mat
                [mycell si] = abfload(abfFile); % load abf file and sample interval, 'si'
                si = si/1e6; % convert sample interval usec to sec
                mycell = myFilter(mycell); % filter signal
                % determine if limitsCrop was erroneous, carried over from
                % previous analysis that used a cropped signal
                if ~isempty(limitsCrop)
                    leftlimit = myEvents(1,1); %find leftmost point
                    rightlimit = myEvents(3,end); %find rightmost point
                    EventsRange = rightlimit - leftlimit; %get span of events
                    % compare span of events to span of crop limits
                    if limitsCrop(2)-limitsCrop(1) <  EventsRange
                        limitsCrop = [];
                    end
                end
                % determine if signal needs to be cropped
                if isempty(limitsCrop)
                    y1 = mycell;
                else
                    y1 = mycell(limitsCrop(1):limitsCrop(2));
                end
                % recompute EventDataStats
                [EventDataStats hfigStats] = getEventStats(myEvents,y1,myEventsFlag,si); %run getEventStats function
                close(hfigStats)
                save([cellname,'_','autoEventStats', '.mat'],...
                'EventDataStats', 'limitsCrop', 'myEvents',...
                'myEventsFlag', 'peakSet', 'si', 'peakThreshold'); % save the 'autoEventStats.mat' file
                movefile(Eventsfile, [searchFolder, '\', searchDir(j).name]); % move the autoEventStats.mat file
                delete(abfFile); %delete .abf file
                clear EventDataStats limitsCrop myEvents myEventsFlag peakSet si peakThreshold y1 mycell
            end
        end

    end
    clear fileDirtemp filecount
end

SEPERATE ALL FILES INTO RESPECTIVE GROUPS

back to top
Oops...
% BY EPC OR MEPP & T OR W & P15 OR P30
% This is where all 8 groups are generated and files are assigned to groups
% based on title of folder where they are contained

% clear workspace and command window
evalin('base','clear all; clc');
% get cell string of partial paths to destination folders
Analysisfolders = {'\Analysis\EPC\T\P15'; %1
             '\Analysis\EPC\T\P30'; %2
             '\Analysis\EPC\W\P15'; %3
             '\Analysis\EPC\W\P30'; %4
             '\Analysis\MEP\T\P15'; %5
             '\Analysis\MEP\T\P30'; %6
             '\Analysis\MEP\W\P15'; %7
             '\Analysis\MEP\W\P30';}; %8
% make new folders
for k = 1:size(Analysisfolders,1)
    mkdir([pwd, Analysisfolders{k}]);
end
% MAKE LIST OF EXISTING DATA FOLDERS
% Folder names with all data
% '...\EPC\Group 1'
% '...\EPC\Group 2'
% '...\MEP\Group 1'
% '...\MEP\Group 2'
% loop through existing data folders
myGroups = {'\EPCs\Group 1';...
            '\EPCs\Group 2';...
            '\MEPPs\Group 1';...
            '\MEPPs\Group 2'};
for n = 1:size(myGroups,1)
    % make list from directory append above to pwd
    currentFolder = pwd;
    searchFolder = [pwd, myGroups{n}]; %change to change folder
    % get list of searchfolder contents using dir command
    searchDir = dir(searchFolder);
    % get rid of hidden files and folders
    searchDirtemp = struct('name',{}, 'date',{}, 'bytes',{}, 'isdir',{}, 'datenum',{});
    Dircount = 1; %initialize Dircount
    for k = 1:length(searchDir)
        if strcmpi(searchDir(k).name,'.') || strcmpi(searchDir(k).name,'..') || ~searchDir(k).isdir
            continue; %skip if hidden dir found
        else
            searchDirtemp(Dircount,1) = searchDir(k);
            Dircount = Dircount +1;
        end
    end
    searchDir = searchDirtemp;
    clear searchDirtemp Dircount
    % select the first folder in list to populate with files
    % Follow order of myGroups determined by var 'n' or by 'EPCs' or
    % 'MEPPs
    if ~isempty(strfind(myGroups{n},'EPCs'))
        recordType = 'EPCs';
    else
        recordType = 'MEPPs';
    end
    % GO THROUGH CONTENTS OF EACH FOLDER, EX: '...\EPCs\Group 1'
    % Generate directory of fies and then scan all files that match description
    % of a '...autoEventStats.mat' file
    for j =  1:length(searchDir)
        % use mysearchfoldername to help determine which analysis folder to
        % populate extract gene and age information
        searchfolderName = searchDir(j).name;
        if strcmp(searchfolderName(1),'T')
            recordGene = 'T';
        elseif strcmp(searchfolderName(1),'W')
            recordGene = 'W';
        end
        if ~isempty(strfind(searchfolderName,'P15')) || ~isempty(strfind(searchfolderName,'P1'))
            recordAge = 'P15';
        elseif ~isempty(strfind(searchfolderName,'P30')) || ~isempty(strfind(searchfolderName,'P3'))
            recordAge = 'P30';
        end
        % Build a string used to determine analysis path
        folderStringBuild = [recordType,recordGene,recordAge];
        % create analysis folder path strings and store in cell array
        analysisString = {['EPCs','T','P15']; %1
                          ['EPCs','T','P30']; %2
                          ['EPCs','W','P15']; %3
                          ['EPCs','W','P30']; %4
                          ['MEPPs','T','P15']; %5
                          ['MEPPs','T','P30']; %6
                          ['MEPPs','W','P15']; %7
                          ['MEPPs','W','P30']}; %8
        % construct string of search folder and compare to analysis string
        for k = 1:size(analysisString,1) %index through all rows
            if strcmp(folderStringBuild,analysisString{k}) %
                analysisPath = Analysisfolders{k};
                break;
            end
        end
        %iterate through all files in folder and copy
        %'...autoEventStats.mat' to analysis folders
        fileDirtemp = struct('name',{}, 'date',{}, 'bytes',{}, 'isdir',{}, 'datenum',{});
        filecount = 1; %initialize folder count
        searchPath = [searchFolder, '\', searchDir(j).name]; %folder path
        fileDir = dir(searchPath); %get dir of folder path
        for k = 1:length(fileDir)
            if strcmpi(fileDir(k).name,'.') || strcmpi(fileDir(k).name,'..')
                continue; %skip if hidden dir found
            else
                fileDirtemp(filecount,1) = fileDir(k);
                filecount = filecount + 1;
            end
        end
        fileDir = fileDirtemp;
        % go through each file in fileDir and copy 'autoEventStats.mat'
        % files to analysis folders
        % find all files with string 'autoEventStats.mat'
        for k = 1:length(fileDir)
            if ~isempty(strfind(fileDir(k).name,'autoEventStats.mat'))
                Eventsfile = fileDir(k).name; % get name of file

                %Copy file if not corrupt
                load([searchPath, '\', Eventsfile]); %load file into workspace
                % do not attempt to extract data from corrupt file or files missing
                % variables
                if exist('fileCorrupt','var');
                    clear fileCorrupt
                    continue;
                else
                    copyfile([searchPath, '\', Eventsfile], [pwd, analysisPath]) % copy 'autoEventStats.mat' file

                end

            end

        end

    end

end

SEARCH THE ANALYSIS FOLDER DATA FOR ERRORS

back to top
% EXECUTE IN RAW DATA DIRECTORY

% clear workspace and commmand prompt
evalin('base','clear all; clc');

% addpath to abf files, for search queries
% ADD SPECIFIC FOLDERS TO SEARCH PATH CONTAINING RAW DATA, ABF FILES
% ...\EPCs\Group 1;
% ...\EPCs\Group 2;
% ...\MEPPs\Group 1;
% ...\MEPPs\Group 2;
% along with all subfolders
rawDataPaths

% create partial path to folders with data
Analysisfolders = {'\Analysis\EPC\T\P15'; %1
             '\Analysis\EPC\T\P30'; %2
             '\Analysis\EPC\W\P15'; %3
             '\Analysis\EPC\W\P30'; %4
             '\Analysis\MEP\T\P15'; %5
             '\Analysis\MEP\T\P30'; %6
             '\Analysis\MEP\W\P15'; %7
             '\Analysis\MEP\W\P30';}; %8

for n = 1:size(Analysisfolders,1)

    % enter code here
    % make list from directory append above to pwd
    searchFolder = [pwd, Analysisfolders{n}];
    % get list of searchfolder contents using dir command
    fileDir = dir(searchFolder);
    % get rid of hidden files and folders
    fileDirtemp = struct('name',{}, 'date',{}, 'bytes',{}, 'isdir',{}, 'datenum',{});
    filecount = 1; %initialize filecount
    for k = 1:length(fileDir)
        if strcmpi(fileDir(k).name,'.') || strcmpi(fileDir(k).name,'..')
            continue; %skip if hidden file found
        else
            fileDirtemp(filecount,1) = fileDir(k);
            filecount = filecount +1;
        end
    end
    fileDir = fileDirtemp;
    clear fileDirtemp filecount
    %open new file
    fid = fopen(['Check_Events_Group_', num2str(n),'.txt'],'w'); %open new file
    %write header
    myheader = 'File_Name \t Corrupt \t Events \t Flags \t Percent_Flags \t Re-analyze \r\n\n';
    fprintf(fid, myheader);
    hplot = figure('numbertitle','off'); %get handle to figure
    for j = 1:length(fileDir)
        %enter code here
        if ~isempty(strfind(fileDir(j).name,'autoEventStats.mat'))
            %enter code here
            Eventsfile = fileDir(j).name; %get name of .mat file
            cellnameidx = strfind(Eventsfile,'_autoEventStats.mat'); % find index in file name where '_autoEventStats.mat' begins
            cellname = Eventsfile(1:cellnameidx(end)-1); % cellname is all string data before last index of '_'
            abfFile = [cellname,'.abf']; % generate the name of the associated .abf file
            load([searchFolder,'\',Eventsfile]); %load file
            %skip if file is corrupt
            if exist('fileCorrupt','var');
                clear fileCorrupt
                fprintf(fid,'%s \t', Eventsfile); %print file name
                fprintf(fid,'%d \t %d \t %d \t %d \t %d \r\n', [1 NaN NaN NaN NaN]); %print corrupt, events, flags, fraction
                disp(['File Corrupt ', Eventsfile]);
            continue;
            end
            % load .abf .mat files. regenerate autoEventStats.mat
            [mycell si] = abfload(abfFile); % load abf file and sample interval, 'si'
            si = si/1e6; % convert sample interval usec to sec
            mycell = myFilter(mycell); % filter signal
            % determine if signal needs to be cropped
            if isempty(limitsCrop)
                y1 = mycell;
            else
                y1 = mycell(limitsCrop(1):limitsCrop(2));
            end
            % Get proper print of title
            Eventsfile_print = regexprep(Eventsfile,'_','\\_');
            %plot the signal and overlay the events
            set(hplot, 'Name', Eventsfile); %set figure name
            plot(y1,'k'); %plot the signal
            title({['Events = ', num2str(size(myEvents,1))]; Eventsfile_print}); %create title
            hold on;
            % plot each event green for non flagged and red for flagged
            for k = 1:size(myEvents,1)
                if myEventsFlag(k) == 0
                    plot(myEvents(k,1):myEvents(k,3),y1(myEvents(k,1):myEvents(k,3)),'g')
                else
                    plot(myEvents(k,1):myEvents(k,3),y1(myEvents(k,1):myEvents(k,3)),'r')
                end
            end
            hold off;
            %get user feedback from plot to determine if events file needs to be regenerated
            choice = questdlg('Are the Events Properly Aligned?', ...
             'Event Detection Feedback', ...
             'No','Yes','Yes');
            % Handle response
            switch choice
                case 'No'
                    reAnalyze = 1; %set to 1 to indicate flag
                case 'Yes'
                    reAnalyze = 0; %set to zero to indicate no flag
                case ''
                    fclose(fid); %close text file
                    return %stop if exit dialog box, return control to command window

            end

            %get event info of non corrupt files
            A = size(myEventsFlag,1); %number of events
            B = sum(myEventsFlag); %total flags
            C = B/A; %fraction of flags
            fprintf(fid,'%s \t', Eventsfile); %print file name
            fprintf(fid,'%d \t %d \t %d \t %d \t %d \r\n', [0 A B C reAnalyze]); %print corrupt, events, flags, fraction, reAnalyze

        end

    end
    fclose(fid); %close file

end

USE ANALYSIS FOLDER TO GENERATE GROUP STATISTICS FOR EXPORT

back to top
Oops...

Oops...
%   *MODIFIED*
%   29-Apr-2014 13:56:43
% ADDING FREQUENCY CALCULATION
% frequency will be calculated as the cell average value
% frequency = total number of peaks/ span of peaks in seconds
% the start of file length is the start point of the first event
% the end of the file length is the last point of the last event
%   30-Apr-2014 17:43:55
% NORMALIZING ALL DATA BASED ON GAIN SETTING
% extract gain information from binary file
%   01-May-2014 23:01:49
% FIXING MISSPELLING SAMPLES WAS SMAPLES
% will replace with Frequency(events/sec)

% Metrics:
%         Animal
%         Cell
%         Amplitude
%         Area Under Curve
%         Tau Rise
%         Tau Decay
%         Rsquare Tau Rise
%         Rsquare Tau Decay
%         Time
%         InterpeakInterval
%         Frequency

% clear workspace and commmand prompt
evalin('base','clear all; clc');

% ADD SPECIFIC FOLDERS TO SEARCH PATH CONTAINING RAW DATA, ABF FILES
% ...\EPCs\Group 1;
% ...\EPCs\Group 2;
% ...\MEPPs\Group 1;
% ...\MEPPs\Group 2;
% along with all subfolders
rawDataPaths


Analysisfolders = {'\Analysis\EPC\T\P15'; %1
             '\Analysis\EPC\T\P30'; %2
             '\Analysis\EPC\W\P15'; %3
             '\Analysis\EPC\W\P30'; %4
             '\Analysis\MEP\T\P15'; %5
             '\Analysis\MEP\T\P30'; %6
             '\Analysis\MEP\W\P15'; %7
             '\Analysis\MEP\W\P30';}; %8
nameAnalysisfolders = regexprep(Analysisfolders, '\', '_'); %search and replace '\' with '_'
% Generate summary statistics for each group
% Save data in foder titled Summary_Analysis
SummaryAnalysisPath = [pwd '\Summary_Analysis'];
mkdir(SummaryAnalysisPath);
%
animalcountAll = 1; %initialize all animal counter animals
cellcountAll = 1; %initialize cell counter cells
%
animalcountEPCAll = 1; %initialize counter for all EPC animals
cellcountEPCAll = 1; %initialize counter of all EPC cells
%
animalcountMEPAll = 1; %initialize counter for all MEP animals
cellcountMEPAll = 1; %initialize counter for all MEP cells
%
AllmyData = []; %initialize variable to store all data
AllmyEPCData = []; %initialize variable to store all data
AllmyMEPData = []; %initialize variable to store all data
% loop index through all group folders
for n = 1:size(Analysisfolders,1);
    searchPath = [pwd, Analysisfolders{n}];
    fileDir = dir(searchPath);
    fileDirtemp = struct('name',{}, 'date',{}, 'bytes',{}, 'isdir',{}, 'datenum',{});
    filecount = 1; %initialize folder count
    for k = 1:length(fileDir)
        if strcmpi(fileDir(k).name,'.') || strcmpi(fileDir(k).name,'..')
            continue; %skip if hidden dir found
        else
            fileDirtemp(filecount,1) = fileDir(k);
            filecount = filecount + 1;
        end
    end
    fileDir = fileDirtemp;
    clear fileDirtemp filecount
    %load each .mat file and extract analysis metrics
    cellcount = 1; %initialize cell count for each new group
    animalcount = 1; %initialize cell count for each new group
    fileName_string = {}; %initialize fileName cell string
    events_string = {}; %initialize event cell string

    myDataSummary = []; %initialize dataSummary for each new group
    myDataSummaryAll = []; %initialize all dataSummary for each new group
    myDataSummaryEPCAll = []; %initialize all EPC dataSummary for each new group
    myDataSummaryMEPAll = []; %initialize all MEP dataSummary for each new group
    for k = 1:length(fileDir) %index through all files in directory
        if k > 1 %increment animal count by checking previous file name, do not check when k=1
            fileName1 = fileDir(k-1).name; %previous file name
            fileName2 = fileDir(k).name; %current file name
            token1 = strfind(fileName1,'_'); %use '_' token to parse file
            animalName1 = fileName(1:token1(1)-1); %parse file name preserving animal ID only
            token2 =strfind(fileName2,'_');
            animalName2 = fileName2(1:token2(1)-1);
            if ~strcmp(animalName1,animalName2) %compare animal id name only
                animalcount = animalcount+1; %incremet animal count
                animalcountAll = animalcountAll +1; %incremnt all animal count when indexing inside group
            end
            if ~strcmp(animalName1,animalName2) && n <= 4
                animalcountEPCAll = animalcountEPCAll +1; %increment EPC all animal count
            end
            if ~strcmp(animalName1,animalName2) && n >= 5
                animalcountMEPAll = animalcountMEPAll +1; %increment MEP all animal count
            end
        end
        fileName = fileDir(k).name; %get file name
        load([searchPath, '\', fileName]); %load .mat file into workspace
        %generate new data with following fields
%         Amplitude - taken from EventDataStats
%         Tau Rise - taken from EventDataStats
%         Tau Decay - taken from EventDataStats
%         Area Under Curve - taken from EventDataStats
%         R square error of Tau Rise - taken from EventDataStats
%         R square error of Tau Decay - taken from EventDataStats
%         InterpeakInterval - computed from peakSet and si
%         Frequency - computed as the # of peaks/time(start peak to end
%         peak)

        % do not attempt to extract data from corrupt file or files missing
        % variables
        if exist('fileCorrupt','var');
            clear fileCorrupt
            continue;
        end
        if ~exist('EventDataStats','var') || ~exist('si','var')...
                || ~exist('peakSet','var') || ~exist('myEventsFlag','var')
           continue;
        end
        % Make variable storing time stamp of events
        mytime = myEvents(:,2)*si; %time of event = index of event*sample interval
        % if events were flagged, need to eliminate flagged events from mytime
        if size(EventDataStats,1) ~= size(mytime,1) %if sizes do not agree
            mytimetemp = ones(size(EventDataStats,1),1); %create temporary array
            mytimecount = 1; %initialize time counter
            for j = 1:length(mytime)
                if myEventsFlag(j) == 1 % continue loop if event is flagged
                    continue
                else
                    mytimetemp(mytimecount) = mytime(j);
                    mytimecount = mytimecount +1;
                end
            end
            mytime = mytimetemp;
        end
        % Make variable storing computed cell average frequency
        rateF = nan(size(mytime)); %make temporary variable for the frequency measurement
        %find first real event
        for countF = 1:length(myEventsFlag) %count from start to end
            if myEventsFlag(countF) == 0 %break on first good event
                startF = myEvents(countF,1); %start of event series, begins with first good event
                break %stop search when first good event found
            end
        end
        %find last real event
        for countF = length(myEventsFlag):-1:1 %count *backward* from end to start
            if myEventsFlag(countF) == 0 %break on first good event
                endF = myEvents(countF,3); %start of event series, begins with first good event
                break %stop search when first good event found
            end
        end
        %compute
        timeF = endF - startF; %number of data points spaning event series
        timeF  = timeF*si; %convert data points into time, using the sample interval
        eventsF = sum(~myEventsFlag); %get the total number of good events
        rateF(1) = eventsF / timeF; %frequency of events given in samples/second, entered in to the 1st entry of rateF array

        %Make variable to store the computed interpeak interval
        iPitemp = nan(size(mytime)); %make temporary variable for interpeak interval filled with NaN's
        iPi = diff(mytime); %compute interpeak interval
        iPitemp(1:length(iPi)) = iPi; %enter interpeak interval values into preinitialized array
        iPi = iPitemp; %interpeak interval will have one entry with NaN

        %Make cellstring of file name and event#
        % Get proper print of title, remove .mat
        fileName_print = regexprep(fileName,'.mat','');
        fileName_string_temp = repmat(fileName_print, size(EventDataStats,1),1); %make row array of fileName
        fileName_string_temp = cellstr(fileName_string_temp); %convert to cell string
        fileName_string = [fileName_string; fileName_string_temp]; %concatenate string
        % Make string of individual events
        events_string_temp = 1:size(EventDataStats,1); %get count of all events
        events_string_temp = events_string_temp(:); %make row array
        events_string_temp = num2str(events_string_temp); %make charachter array
        events_string_temp = cellstr(events_string_temp); %convert to cell string
        events_string = [events_string;events_string_temp]; %concatenate string

        %make [group animal cell amplitude(nA) Tau-Rise(sec) Tau-Decay(sec) AreaUnderCurve(nA*sec) R(rise) R(fall) InterPeakInterval(sec) time(sec)]
        animalArray = ones(size(EventDataStats,1),1)*animalcount; %make array of animal ID
        cellsArray = ones(size(EventDataStats,1),1)*cellcount; %make array of cell ID
        animalArrayAll = ones(size(EventDataStats,1),1)*animalcountAll; %make array of animal ID for storing into composite data file
        cellsArrayAll = ones(size(EventDataStats,1),1)*cellcountAll; %make array of cell ID for storing into composite data file
        if n <= 4
            animalArrayEPCAll = ones(size(EventDataStats,1),1)*animalcountEPCAll; %make array of animal ID
            cellsArrayEPCAll = ones(size(EventDataStats,1),1)*cellcountEPCAll; %make array of cell ID
        else
            animalArrayMEPAll = ones(size(EventDataStats,1),1)*animalcountMEPAll; %make array of animal ID
            cellsArrayMEPAll = ones(size(EventDataStats,1),1)*cellcountMEPAll; %make array of cell ID
        end
        groupArray = ones(size(EventDataStats,1),1)*n; %make array of group ID

        %concatenate [group animal cell EventDataStats iPi mytime]
        %EventDataStats
        %EPC
        %amplitude(nA) Tau-Rise(sec) Tau-Decay(sec) AreaUnderCurve(nA*sec) R(rise) R(decay)
        %MEP
        %amplitude(mV/100) Tau-Rise(sec) Tau-Decay(sec) AreaUnderCurve(mV/100*sec) R(rise) R(decay)
        %filter EventDataStats error, <0sec, entries and replace with NaN
        for p = 1:numel(EventDataStats)
            if EventDataStats(p) < 0
                EventDataStats(p) = NaN;
            end
        end
        %filter Tau should be <0.1sec
        for p = 1:size(EventDataStats,1)
            if EventDataStats(p,2) > 0.1
                EventDataStats(p,2) = NaN;
            end
            if EventDataStats(p,3) > 0.1
                EventDataStats(p,3) = NaN;
            end
        end

        %Find the cell Gain and correct for the gain
        %fileName = the autoEventStats.mat file
        cellnameidx = strfind(fileName,'_autoEventStats.mat'); % find index in file name where '_autoEventStats.mat' begins
        cellname = fileName(1:cellnameidx(end)-1); % cellname is all string data before last index of '_'
        abfFile = [cellname,'.abf']; % generate the name of the associated .abf file
        %Search the file for the Gain information
        myfileN = abfFile; %enter file name
        fid = fopen(myfileN,'r','ieee-le'); %open the abf file
        sz=1;  %# of data entries to read
        numType = 'float'; %precision format
        myGainfileoffset = 268; %find the correct offset where data entry for gain begins
        fseek(fid,myGainfileoffset,'bof'); %move field position
        cellGain = fread(fid,sz,numType); %read formatted data
        fclose(fid); %close file

        %Correct for cell gain
        EventDataStats(:,1) = EventDataStats(:,1)/cellGain; %convert amplitude
        EventDataStats(:,4) = EventDataStats(:,4)/cellGain; %convert AreaUnderCurve

        %Build Data Arrays
        myDataSummarytemp = [groupArray animalArray cellsArray EventDataStats iPi rateF mytime];
        myDataSummaryAlltemp = [groupArray animalArrayAll cellsArrayAll EventDataStats iPi rateF mytime];
        myDataSummary = [myDataSummary; myDataSummarytemp]; %concatenate arrays
        myDataSummaryAll = [myDataSummaryAll; myDataSummaryAlltemp]; %concatenate arrays
        cellcount = cellcount +1; %increment cell count before next loop iteration
        cellcountAll = cellcountAll +1; %increment all cell count
        if n <= 4 %Buld EPC data array
            myDataSummaryEPCAlltemp = [groupArray animalArrayEPCAll cellsArrayEPCAll EventDataStats iPi rateF mytime];
            myDataSummaryEPCAll = [myDataSummaryEPCAll; myDataSummaryEPCAlltemp]; %concatenate arrays
            cellcountEPCAll = cellcountEPCAll +1; %increment all EPC cell count
        else %Build MEP data array
            myDataSummaryMEPAlltemp = [groupArray animalArrayMEPAll cellsArrayMEPAll EventDataStats iPi rateF mytime];
            myDataSummaryMEPAll = [myDataSummaryMEPAll; myDataSummaryMEPAlltemp]; %concatenate arrays
            cellcountMEPAll = cellcountMEPAll +1; %increment all EPC cell count
        end

        clear EventDataStats limitsCrop myEvents myEventsFlag peakSet peakThreshold si %clear variables
    end
    %concatenate myDataSummary from same group
    eval(['DataSummary', nameAnalysisfolders{n}, '= myDataSummary;']); %save DataSummary as variable to workspace
    %make cell aray for Event; EPC, MEPP, Gene; T, W, Age; P15, P30
    EventGeneAge = {['EPC','\t', 'TWI','\t', 'P15','\t']; %1
                 ['EPC','\t', 'TWI','\t', 'P30','\t']; %2
                 ['EPC','\t', 'WT ','\t', 'P15','\t']; %3
                 ['EPC','\t', 'WT ','\t', 'P30','\t']; %4
                 ['MEP','\t', 'TWI','\t', 'P15','\t']; %5
                 ['MEP','\t', 'TWI','\t', 'P30','\t']; %6
                 ['MEP','\t', 'WT ','\t', 'P15','\t']; %7
                 ['MEP','\t', 'WT ','\t', 'P30','\t']}; %8
    %header
%     myheader = {'Event', 'Gene', 'Age', 'Group', 'Animal', 'Cell', 'Amplitude(nA)', '1/Tau-Rise(sec)', '1/Tau-Decay(sec)', 'AreaUnderCurve(nA*sec)', 'Rsquare(rise)', 'Rsquare(decay)', 'InterPeakInterval(sec)', 'time(sec)', 'Event', 'File name'};
    %open a text file to enter data for individual groups
    if n <= 4 %print header for EPC group
        fid = fopen(['Data_Summary', nameAnalysisfolders{n}, '.txt'], 'w'); %open file and assign group name
        fprintf(fid, 'Event \t Gene \t Age \t Group \t Animal \t Cell \t Amplitude(nA) \t 1/Tau-Rise(sec) \t 1/Tau-Decay(sec) \t AreaUnderCurve(nA*sec) \t Rsquare(rise) \t Rsquare(decay) \t InterPeakInterval(sec) \t Frequency(events/sec) \t time(sec) \t Event \t File Name \r\n\n'); % write header
        for p = 1:size(myDataSummary,1) %loop through each row of myDataSummary
            fprintf(fid, EventGeneAge{n}); %wite Event Gene Age info
            fprintf(fid, '%10d \t %10d \t %10d \t %10.5f \t %10.5e \t %10.5e \t %10.5e \t %10.5e \t %10.5e \t %10.5e \t %10.5e \t %10.5e \t', myDataSummary(p,:)); %write Data to file
            fprintf(fid, [events_string{p}, ' \t ', fileName_string{p}, ' \r']); %write last two columns in row and move to next row
        end
    else %print header for MEPP group
        fid = fopen(['Data_Summary', nameAnalysisfolders{n}, '.txt'], 'w'); %open file and assign group name
        fprintf(fid, 'Event \t Gene \t Age \t Group \t Animal \t Cell \t Amplitude(mV) \t 1/Tau-Rise(sec) \t 1/Tau-Decay(sec) \t AreaUnderCurve(mV*sec) \t Rsquare(rise) \t Rsquare(decay) \t InterPeakInterval(sec) \t Frequency(events/sec) \t time(sec) \t Event \t File Name \r\n\n'); % write header
        for p = 1:size(myDataSummary,1) %loop through each row of myDataSummary
            fprintf(fid, EventGeneAge{n}); %wite Event Gene Age info
            fprintf(fid, '%10d \t %10d \t %10d \t %10.5f \t %10.5e \t %10.5e \t %10.5e \t %10.5e \t %10.5e \t %10.5e \t %10.5e \t %10.5e \t', myDataSummary(p,:)); %write Data to file
            fprintf(fid, [events_string{p}, ' \t ', fileName_string{p}, ' \r']); %write last two columns in row and move to next row
        end
    end
    fclose(fid); %close file
    movefile(['*',nameAnalysisfolders{n}, '.txt'], SummaryAnalysisPath); % move file(s) to Summaryanalysis folder
    clear myDataSummary %remove variable so that it does not concatenate with other groups DataSummary
    %Write all data to a single text file
    %open a text file to write and save ALL data
    if n == 1 %open a new file and print header for EPC gropus
        fidAll = fopen(['Data_Summary_ALL', '.txt'], 'w'); %open file and assign group name
        fprintf(fidAll, 'Event \t Gene \t Age \t Group \t Animal \t Cell \t Amplitude(nA) \t 1/Tau-Rise(sec) \t 1/Tau-Decay(sec) \t AreaUnderCurve(nA*sec) \t Rsquare(rise) \t Rsquare(decay) \t InterPeakInterval(sec) \t Frequency(events/sec) \t time(sec) \r\n\n'); % write header
        for p = 1:size(myDataSummaryAll,1) %loop through each row of myDataSummary
            fprintf(fidAll, EventGeneAge{n}); %wite Event Gene Age info
            fprintf(fidAll, '%10d \t %10d \t %10d \t %10.5f \t %10.5e \t %10.5e \t %10.5e \t %10.5e \t %10.5e \t %10.5e \t %10.5e \t %10.5e \r', myDataSummaryAll(p,:)); %write to file
        end
    elseif n == 5 %print a new header for start of MEPP gropus but dont reopen file that is already open
        fprintf(fidAll, ' \r\n\n'); %line feed
        fprintf(fidAll, 'Event \t Gene \t Age \t Group \t Animal \t Cell \t Amplitude(mV) \t 1/Tau-Rise(sec) \t 1/Tau-Decay(sec) \t AreaUnderCurve(mV*sec) \t Rsquare(rise) \t Rsquare(decay) \t InterPeakInterval(sec) \t Frequency(events/sec) \t time(sec) \r\n\n'); % write header
        for p = 1:size(myDataSummaryAll,1) %loop through each row of myDataSummary
            fprintf(fidAll, EventGeneAge{n}); %wite Event Gene Age info
            fprintf(fidAll, '%10d \t %10d \t %10d \t %10.5f \t %10.5e \t %10.5e \t %10.5e \t %10.5e \t %10.5e \t %10.5e \t %10.5e \t %10.5e \r', myDataSummaryAll(p,:)); %write to file
        end
    else %print data only for groups
        for p = 1:size(myDataSummaryAll,1) %loop through each row of myDataSummary
            fprintf(fidAll, EventGeneAge{n}); %wite Event Gene Age info
            fprintf(fidAll, '%10d \t %10d \t %10d \t %10.5f \t %10.5e \t %10.5e \t %10.5e \t %10.5e \t %10.5e \t %10.5e \t %10.5e \t %10.5e \r', myDataSummaryAll(p,:)); %write to file
        end
    end
    AllmyData = [AllmyData; myDataSummaryAll]; %concatenate AllmyData
    animalcountAll = animalcountAll +1; %incremnt all animal count when indexing between groups
    clear myDataSummaryAll %remove variable so that it does not concatenate with other group's DataSummary
    %Write all EPC data to a single text file
    %open a text file to write and save ALL data
    if n <= 4
        if n == 1 %open a new file and print header for EPC gropus
            fidEPCAll = fopen(['Data_Summary_EPC_ALL', '.txt'], 'w'); %open file and assign group name
            fprintf(fidEPCAll, 'Event \t Gene \t Age \t Group \t Animal \t Cell \t Amplitude(nA) \t 1/Tau-Rise(sec) \t 1/Tau-Decay(sec) \t AreaUnderCurve(nA*sec) \t Rsquare(rise) \t Rsquare(decay) \t InterPeakInterval(sec) \t Frequency(events/sec) \t time(sec) \r\n\n'); % write header
            for p = 1:size(myDataSummaryEPCAll,1) %loop through each row of myDataSummary
                fprintf(fidEPCAll, EventGeneAge{n}); %wite Event Gene Age info
                fprintf(fidEPCAll, '%10d \t %10d \t %10d \t %10.5f \t %10.5e \t %10.5e \t %10.5e \t %10.5e \t %10.5e \t %10.5e \t %10.5e \t %10.5e \r', myDataSummaryEPCAll(p,:)); %write to file
            end
        else %print data only for groups
            for p = 1:size(myDataSummaryEPCAll,1) %loop through each row of myDataSummary
                fprintf(fidEPCAll, EventGeneAge{n}); %wite Event Gene Age info
                fprintf(fidEPCAll, '%10d \t %10d \t %10d \t %10.5f \t %10.5e \t %10.5e \t %10.5e \t %10.5e \t %10.5e \t %10.5e \t %10.5e \t %10.5e \r', myDataSummaryEPCAll(p,:)); %write to file
            end
        end
        AllmyEPCData = [AllmyEPCData; myDataSummaryEPCAll]; %concatenate all EPC data
        animalcountEPCAll = animalcountEPCAll +1;
        clear myDataSummaryEPCAll %remove variable so that it does not concatenate with other EPC group's DataSummary
    end
    %Write all EPC data to a single text file
    %open a text file to write and save ALL data
    if n >= 5
        if n == 5 %open a new file and print header for MEP gropus
            fidMEPAll = fopen(['Data_Summary_MEP_ALL', '.txt'], 'w'); %open file and assign group name
            fprintf(fidMEPAll, 'Event \t Gene \t Age \t Group \t Animal \t Cell \t Amplitude(mV) \t 1/Tau-Rise(sec) \t 1/Tau-Decay(sec) \t AreaUnderCurve(mV*sec) \t Rsquare(rise) \t Rsquare(decay) \t InterPeakInterval(sec) \t Frequency(events/sec) \t time(sec) \r\n\n'); % write header
            for p = 1:size(myDataSummaryMEPAll,1) %loop through each row of myDataSummary
                fprintf(fidMEPAll, EventGeneAge{n}); %wite Event Gene Age info
                fprintf(fidMEPAll, '%10d \t %10d \t %10d \t %10.5f \t %10.5e \t %10.5e \t %10.5e \t %10.5e \t %10.5e \t %10.5e \t %10.5e \t %10.5e \r', myDataSummaryMEPAll(p,:)); %write to file
            end
        else %print data only for groups
            for p = 1:size(myDataSummaryMEPAll,1) %loop through each row of myDataSummary
                fprintf(fidMEPAll, EventGeneAge{n}); %wite Event Gene Age info
                fprintf(fidMEPAll, '%10d \t %10d \t %10d \t %10.5f \t %10.5e \t %10.5e \t %10.5e \t %10.5e \t %10.5e \t %10.5e \t %10.5e \t %10.5e \r', myDataSummaryMEPAll(p,:)); %write to file
            end
        end
        AllmyMEPData = [AllmyMEPData; myDataSummaryMEPAll]; %concatenate all MEP data
        animalcountMEPAll = animalcountMEPAll +1;
        clear myDataSummaryEPCAll %remove variable so that it does not concatenate with other MEP group's DataSummary
    end
end

fclose(fidAll); %close SummaryAll Data file
fclose(fidEPCAll); %close SummaryEPCAll Data file
fclose(fidMEPAll); %close SummaryMEPAll Data file
movefile('Data_Summary_ALL.txt', SummaryAnalysisPath); %move file to summaryAnalysisPath
movefile('Data_Summary_EPC_ALL.txt', SummaryAnalysisPath); %move file to summaryAnalysisPath
movefile('Data_Summary_MEP_ALL.txt', SummaryAnalysisPath); %move file to summaryAnalysisPath
% combine each group's 'DataSummary_Analysis*' variables into one .mat file
% called 'DataSummary_Analysis.mat'
save('Data_Summary_Analysis','DataSummary_Analysis*'); %save each variable beginning with DataSummary_Analysis* as DataSummary_Analysis.mat
% move into Summaryanalysis folder
movefile('Data_Summary_Analysis.mat', SummaryAnalysisPath);
% save AllmyData variable as a mat file
save('All_Summary_Analysis','AllmyData'); %save to workspace
% move into SummaryAnalysis folder
movefile('All_Summary_Analysis.mat', SummaryAnalysisPath);
% save AllmyEPCData variable as mat file
save('All_EPC_Summary_Analysis','AllmyEPCData'); %save to workspace
% move into SummaryAnalysis folder
movefile('All_EPC_Summary_Analysis.mat', SummaryAnalysisPath);
% save AllmyEPCData variable as mat file
save('All_MEP_Summary_Analysis','AllmyMEPData'); %save to workspace
% move into SummaryAnalysis folder
movefile('All_MEP_Summary_Analysis.mat', SummaryAnalysisPath);
% make headers and store them as .mat files
EPCheader = {'Group'; 'Animal'; 'Cell'; 'Amplitude(nA)'; '1/Tau-Rise(sec)'; '1/Tau-Decay(sec)'; 'AreaUnderCurve(nA*sec)'; 'Rsquare(rise)'; 'Rsquare(decay)'; 'InterPeakInterval(sec)'; 'Frequency(events/sec)'; 'time(sec)'; 'Events'; 'File Name'};
MEPheader = {'Group'; 'Animal'; 'Cell'; 'Amplitude(mV)'; '1/Tau-Rise(sec)'; '1/Tau-Decay(sec)'; 'AreaUnderCurve(mV*sec)'; 'Rsquare(rise)'; 'Rsquare(decay)'; 'InterPeakInterval(sec)'; 'Frequency(events/sec)'; 'time(sec)'; 'Events'; 'File Name'};
save('Data_Summary_EPCHeader', 'EPCheader'); %save myheader to workspace as .mat file
save('Data_Summary_MEPHeader', 'MEPheader'); %save myheader to workspace as .mat file
% move into SummaryAnalysis folder
movefile('Data_Summary_EPCHeader.mat', SummaryAnalysisPath);
movefile('Data_Summary_MEPHeader.mat', SummaryAnalysisPath);