function [Data, Config, PerformanceCheck] = DataProc(Data, Config, PerformanceCheck, tempdata, i, tStop, tStart)
%% Process Data
fn = fieldnames(Data);
for n = 1:length(fn) %number of fields (columns)
    for i = 1:length(Data) %rows
        if isempty(Data(i).(fn{n})) && ismember(fn{n},{'TrainingLevel' 'Sensor' 'TrialCount','idx' ...
                'MotorNumber' 'ReactTime' 'ReactTimeBin' 'TotalNumPrematureResponses','TotalNumTimeOut',...
                'TotalNumPanelPushesITI' 'TotalNumPerseverativeResponsesIncorrect' 'TotalNumPerseverativeResponsesDimmed' 'TotalNumPerseverativeResponsesCorrect'})
            Data(i).(fn{n}) = NaN; %replace empty with NaN
        elseif isempty(Data(i).(fn{n})) && ismember(fn{n},{'StimOnTime' 'StimOffTime' 'ResponseTime' 'MotorOnTime' 'RewardTime' 'TrialEnd' 'TotalRuntimeMinutes'})
            Data(i).(fn{n}) = NaT; %replace empty with NaT
        elseif isempty(Data(i).(fn{n}))&& ismember(fn{n},{'Perseverative' 'TimeoutAns'})
            Data(i).(fn{n}) = {NaN}; %replace empty with NaN cell array
        elseif isempty(Data(i).(fn{n})) && ismember(fn{n},{'PerseverativeTime' 'TimeoutAnsTime'})
            Data(i).(fn{n}) = {NaT}; %replace empty with NaT cell array
        end
    end
end

if isempty([Data(end).LedValue]) %If experiment stops before last row was complete: delete it since it contains no info
    Data(end-1).TotalNumPrematureResponses = tempdata.NumPrematureResponses; %writes the important info in second to last row
    Data(end-1).TotalNumTimeOut = tempdata.NumTimeOut;
    Data(end-1).TotalNumPanelPushesITI = tempdata.NumPanelPushesITI;
    Data(end-1).TotalNumPerseverativeResponsesIncorrect = tempdata.NumPersvIncorrect;
    Data(end-1).TotalNumPerseverativeResponsesDimmed = tempdata.NumPersvDimmed;
    Data(end-1).TotalNumPerseverativeResponsesCorrect = tempdata.NumPersvCorrect;
    Data(end-1).TotalRuntimeMinutes = minutes(tStop-tStart);
    Data(end) = []; %deletes last row
else
    Data(end).TotalNumPrematureResponses = tempdata.NumPrematureResponses; %writes the important info in last row
    Data(end).TotalNumTimeOut = tempdata.NumTimeOut;
    Data(end).TotalNumPanelPushesITI = tempdata.NumPanelPushesITI;
    Data(end).TotalNumPerseverativeResponsesIncorrect = tempdata.NumPersvIncorrect;
    Data(end).TotalNumPerseverativeResponsesDimmed = tempdata.NumPersvDimmed;
    Data(end).TotalNumPerseverativeResponsesCorrect = tempdata.NumPersvCorrect;
    Data(end).TotalRuntimeMinutes = minutes(tStop-tStart);
end
fprintf('Experiment done after %i Trials. Runtime: %.2f minutes or %.2f seconds \n', i, minutes(tStop - tStart), seconds(tStop - tStart)); %Command Window info
fprintf('Accuracy today is %0.2f \n', (sum([Data.Outcome] == 1)/(sum([Data.Outcome] == 1) + sum([Data.Outcome] == 3)) *100));
fprintf('Percentage of omission today is %0.2f \n \n', (sum([Data.Outcome] == 0)/(sum([Data.Outcome] == 0) + sum([Data.Outcome] == 1) + sum([Data.Outcome] == 3)) *100));

if (Config.Experiment.AutoSave == 1) %If autosave is on
    cd(Config.Experiment.Directory); %go to experiment directory
    strdate = datestr(now, 'yyyy.mm.dd_HH.MM.SS'); %get date and time
    filename = strcat(strdate, '.mat'); %name of file
    if ~isfolder(Config.Experiment.Subject) %if there is no subject folder in directory
        mkdir(Config.Experiment.Subject) %create subject folder
        cd(Config.Experiment.Subject)
    else
        cd(Config.Experiment.Subject)
    end
    save(filename, 'Config', 'Data', 'PerformanceCheck') %saves workspace structs to matlab file

    filename = strcat(strdate, '.xlsx'); %name of file
    XlsxData = Data; %copy struct to new struct before removing fields
    if nnz(isnan(cell2mat([Data.Perseverative]))) == 0 & nnz(isnan(cell2mat([Data.TimeoutAns]))) == 0 %there was no perseverative or timeout answers
        writetable(struct2table(Data), filename, 'UseExcel',true); %save original Data struct as table
    end
    if nnz(~isnan(cell2mat([Data.Perseverative]))) > 0 %there were perseverative answers
        XlsxData = rmfield(XlsxData,'Perseverative'); %delete Perseverative struct field
        XlsxData = rmfield(XlsxData,'PerseverativeTime'); %delete Perseverative Time struct field
    end
    if nnz(~isnan(cell2mat([Data.TimeoutAns]))) > 0 %there were timeout answers
        XlsxData = rmfield(XlsxData,'TimeoutAns'); %delete Timeout struct field
        XlsxData = rmfield(XlsxData,'TimeoutAnsTime'); %delete Timeout Time struct field
    end
    if length(fieldnames(XlsxData)) < length(fieldnames(Data)) %fields were removed
        writetable(struct2table(XlsxData), filename); %save other infos in one table sheet
%         for k = 1:length(Data)
%             StartRange = append('A',num2str(k+1)); %get range for the rows in table
%             if ~isfield(XlsxData,'Perseverative') %save perseverative answers to new sheet
%                 writecell(Data(k).Perseverative,filename,'Sheet','Perseverative Ans','UseExcel',true,'Range',StartRange);
%                 %writecell(Data(k).PerseverativeTime,filename,'Sheet','Perseverative Ans Time','UseExcel',true,'DateLocale',true,'Range',StartRange);
%             end
%             if ~isfield(XlsxData,'TimeoutAns') %save timeout answers to new sheet
%                 writecell(Data(k).TimeoutAns,filename,'Sheet','Timeout Ans','UseExcel',true,'Range',StartRange);
%                 writecell(Data(k).TimeoutAnsTime,filename,'Sheet','Timeout Ans Time','UseExcel',true,'DateLocale',true,'Range',StartRange);
%             end
%         end
    end
end
%% Plot data
if isfield(Data, 'Outcome') %simple plot with general data
    strdate = datestr(now, 'yyyy.mm.dd_HH.MM.SS');
    X = categorical({'Correct Response', 'Incorrect Response','Panel Pushes ITI','Total nr. Timeouts', 'Omission', 'Premature'});
    X = reordercats(X, {'Correct Response', 'Incorrect Response', 'Panel Pushes ITI', 'Total nr. Timeouts', 'Omission', 'Premature'});
    Y = [sum([Data.Outcome] == 1), sum([Data.Outcome] == 3), Data(end).TotalNumPanelPushesITI, Data(end).TotalNumTimeOut, sum([Data.Outcome] == 0), Data(end).TotalNumPrematureResponses];
    bar(X, Y, 'FaceColor', [0.75, 0.75, 0.75])
    figname = strcat(strdate, 'Timeout.pdf');
    print(gcf, figname, '-dpdf', '-bestfit'); %save graph as pdf
end

%write code to plot data here!