function dop=dopOverallDataSave(dop)
% dopOSCCI Mark II: dopOverallDataSave~ 24-11-2010 (last edit)
%
% saves event data (averaged accross allEpochs &/or scrnEpochs), left,
% right, difference, and averager for each participant so that data can be
% accessed for graphing external to dopOSCCI.
%
% only saves the normalised, baseline corrected event data.
% (raw and normalised session data is not currently saved 16-11-2010)
%
% save for each event and provide sample timing in seconds in header
%
% I'd like to save the basic versions of the data as well.  That is, if
% there is group, behavioural, or session function - collapse across these
% for the overall data files.
%

% -------------------------------------------------------------------------
%     'dopOSCCI' summarises functional transcranial Doppler ultrasonography
%     (fTCD) data.  The primary function of the software is to assess the
%     hemispheric lateralization of cognitive function.
%
%     Copyright (C) 2011 the Chancellor, Masters and Scholars of the
%     University of Oxford.
% 
%     This program is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     (at your option) any later version.
% 
%     This program is distributed in the hope that it will be useful,
%     but WITHOUT ANY WARRANTY; without even the implied warranty of
%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%     GNU General Public License for more details.
% 
%     You should have received a copy of the GNU General Public License
%     along with this program.  If not, see <http://www.gnu.org/licenses/> 
%     or write to the Free Software Foundation, Inc., 51 Franklin Street,
%     Fifth Floor, Boston, MA 02110-1301, USA.
%
%     Authors: Nic Badcock, Georgina Holt, Anneka Holden, & Dorothy Bishop.
%       contact: nicholas.badcock@gmail.com
%
%     Type 'dopOSCCIlicense' for license details or see dopOSCCIlicense.txt
%
fprintf('\n%s\n\t%s',['Running ',mfilename],...
    'Saving graphing data:');
try
    if ~dop.sum.skip && ~dop.sum.quit
        
        if sum(dop.scrn.saveGraphData(1:length(dop.scrn.labels))) && sum(dop.def.saveGraphDataChs)
            %% save location
            dop.gds.translation='graph data save ';
            dop.gds.evNames=dop.stack.evNames;
            dop.sav.graphDataDir=[dop.def.saveDir,'graphData\'];
            if ~exist(dop.sav.graphDataDir,'dir')
                fprintf('\n\t%s\n\t\t%s','Creating save dir:',dop.sav.graphDataDir);
                mkdir(dop.sav.graphDataDir);
            end
            %% > file note
            % useful to have a short note file that explains what's in each
            % of the event data files - epoch, base, poi info as well as
            % which data channels are saved (left, right, dif, average).
            % This info will be required for reading
            %
            % probably save a mat for all and txt for each event.
            %
            dop=dopSaveGraphNotes(dop);
            
            %% group inclusion
            dop.gds.gLabel='';
            dop.gds.grpAbbNote='';
            if dop.def.grpFileChk
                dop.gds.grpAbb=['grp',num2str(dop.sum.grp),dop.sum.grpName]; % in case there's a problem & no group...
                dop.gds.gLabel=[dop.gds.grpAbb,'_'];
                dop.gds.grpAbbNote=[' - ',dop.gds.grpAbb];
            end
            %% session inclusion
            dop.gds.sLabel='';
            dop.gds.sesAbbNote='';
            if dop.def.sesFileChk
                if dop.ses.session<dop.ses.nSes+1
                    dop.gds.sesAbb=['ses',num2str(dop.ses.session),dop.ses.sesNames{dop.ses.session}];
                else
                    dop.gds.sesAbb=['ses',num2str(dop.ses.session),'All',num2str(dop.ses.nSes)];
                    % check if we need extra labels for session
                    % balance
                    dop.tmp.scrnLabel=0;
                    if dop.def.saveSesGraphData(2) && ~strcmp(dop.scrn.labels{end},dop.def.saveEpochSelectionLabels{end})
                        dop.tmp.scrnLabel=1; % indicate whether we added this here
                        dop.scrn.labels{end+1}=dop.def.saveEpochSelectionLabels{end};
                        % check if we need to adjust what gets
                        % saved
                        if numel(dop.scrn.saveGraphData)<numel(dop.def.saveEpochSelectionLabels)
                            dop.tmp.saveGraphData=dop.scrn.saveGraphData;
                            dop.scrn.saveGraphData([end end+1])=dop.def.saveSesGraphData;
                        end
                    elseif sum(dop.scrn.saveGraphData([end-1 end]))~=sum(dop.def.saveSesGraphData)
                        dop.tmp.saveGraphData=dop.scrn.saveGraphData;
                        dop.scrn.saveGraphData([end-1 end])=dop.def.saveSesGraphData;
                    end
                    % and reverse this at the end
                end
                dop.gds.sLabel=[dop.gds.sesAbb,'_'];
                dop.gds.sesAbbNote=[' - ',dop.gds.sesAbb];
            end
            
            
            %% preparation
            for i=1:length(dop.scrn.labels)%(dop.def.saveGraphData) % all dat act man scrn bal (bal in final session)
                if dop.scrn.saveGraphData(i) % formerly dop.def.saveGraphData
                    dop.gds.epSel=i; % epoch selection
                    %                     dop.gds.epAbb=dop.def.saveGraphDataAbb{dop.gds.epSel}; % abbreviation
                    dop.gds.epAbb=[dop.scrn.labels{dop.gds.epSel},'Ep']; % abbreviation
                    
                    for j=1:length(dop.gds.evNames) % for each event
                        %% save file name
                        dop.gds.en=dop.gds.evNames{j}; % event name
                        %% > behavioural
                        dop.gds.bLabel='';
                        dop.gds.behAbbNote='';
                        if dop.def.behFileChk && dop.def.saveBehGraphData
                            
                            
                            
                            for jj=1:length(dop.beh.behNames); dop.tmp.bn=dop.beh.behNames{jj}; % behavioural name
                                for jjj=1:length(dop.beh.levels.(dop.tmp.bn))
                                    dop.tmp.blv=dop.beh.levels.(dop.tmp.bn)(jjj); % behavioural level value
                                    
                                    dop.gds.behAbb=['beh',num2str(dop.tmp.blv),dop.tmp.bn]; % in case there's a problem & no group...
                                    dop.gds.bLabel=[ dop.gds.behAbb,'_'];
                                    dop.gds.behAbbNote=[' - ',dop.gds.behAbb];
                                    % beh#name_
                                    for ii=1:1+dop.def.grpFileChk+dop.def.sesFileChk+prod([dop.def.grpFileChk dop.def.sesFileChk])
                                        switch ii
                                            case 1 % basic behavioural name
                                                dop.gds.saveFileName=[dop.gds.en,'_',...
                                                    dop.gds.behAbb,'_',...
                                                    dop.gds.epAbb,'.dat'];
                                            case 2 % behavioural + grp
                                                if dop.def.grpFileChk
                                                    dop.gds.saveFileName=[dop.gds.en,'_',dop.gds.gLabel,...
                                                        dop.gds.behAbb,'_',...
                                                        dop.gds.epAbb,'.dat'];
                                                elseif dop.def.sesFileChk
                                                    dop.gds.saveFileName=[dop.gds.en,'_',...
                                                        dop.gds.behAbb,'_',...
                                                        dop.gds.sLabel,dop.gds.epAbb,'.dat'];
                                                end
                                            case 3 % behavioural + session
                                                if dop.def.sesFileChk
                                                    dop.gds.saveFileName=[dop.gds.en,'_',...
                                                        dop.gds.behAbb,'_',...
                                                        dop.gds.sLabel,dop.gds.epAbb,'.dat'];
                                                elseif dop.def.grpFileChk
                                                    dop.gds.saveFileName=[dop.gds.en,'_',dop.gds.gLabel,...
                                                        dop.gds.behAbb,'_',...
                                                        dop.gds.epAbb,'.dat'];
                                                end
                                            case 4 % behavioural + group + session
                                                dop.gds.saveFileName=[dop.gds.en,'_',dop.gds.gLabel,...
                                                    dop.gds.behAbb,'_',...
                                                    dop.gds.sLabel,dop.gds.epAbb,'.dat'];
                                        end
                                        
                                        dop.gds.fnl=[dop.sav.graphDataDir,dop.gds.saveFileName]; % file name location
                                        
                                        dop.gds.epScrn=and(logical(dop.scrn.(dop.gds.en)(:,dop.gds.epSel)),...; % epoch screen
                                            dop.beh.filter.(dop.tmp.bn)(:,jjj));
                                        %% > writeLabels
                                        dop=writeLabels(dop,j);
                                        %% > writeData
                                        dop=writeData(dop,j);
                                    end
                                end
                            end
                        end
                        for ii=1:1+dop.def.grpFileChk+dop.def.sesFileChk+prod([dop.def.grpFileChk dop.def.sesFileChk])
                            %% > regular
                            switch ii
                                case 1 % basic file name (no grp, no session)
                                    dop.gds.saveFileName=[dop.gds.en,'_',dop.gds.epAbb,'.dat'];
                                case 2 % group only (no session) - try first, then session
                                    if dop.def.grpFileChk
                                        dop.gds.saveFileName=[dop.gds.en,'_',dop.gds.gLabel,dop.gds.epAbb,'.dat'];
                                    elseif dop.def.sesFileChk
                                        dop.gds.saveFileName=[dop.gds.en,'_',dop.gds.sLabel,dop.gds.epAbb,'.dat'];
                                    end
                                case 3 % session only (no group) - try first, then grp
                                    if dop.def.sesFileChk
                                        dop.gds.saveFileName=[dop.gds.en,'_',dop.gds.sLabel,dop.gds.epAbb,'.dat'];
                                    elseif dop.def.grpFileChk
                                        dop.gds.saveFileName=[dop.gds.en,'_',dop.gds.gLabel,dop.gds.epAbb,'.dat'];
                                    end
                                case 4 % group & session
                                    dop.gds.saveFileName=[dop.gds.en,'_',dop.gds.gLabel,dop.gds.sLabel,dop.gds.epAbb,'.dat'];
                            end
                            
                            dop.gds.fnl=[dop.sav.graphDataDir,dop.gds.saveFileName]; % file name location
                            
                            dop.gds.epScrn=logical(dop.scrn.(dop.gds.en)(:,dop.gds.epSel)); % epoch screen
                            %% > writeLabels
                            dop=writeLabels(dop,j);
                            %% > writeData
                            dop=writeData(dop,j);
                        end
                    end % each event
                end
            end
            fprintf('\n%s\n','Done');
        else
            fprintf('\n%s\n','Nothing set to be saved (see dopTaskDef)');
        end
        %% reverse session info
        if dop.def.sesFileChk
            if dop.ses.session==dop.ses.nSes+1
                if isfield(dop,'tmp') && dop.tmp.scrnLabel % if we added it above, then remove it here
                    dop.scrn.labels(end)=[];%dop.def.saveEpochSelectionLabels{end};
                end
                % check if we need to adjust what gets
                % saved
                if isfield(dop,'tmp') && isfield(dop.tmp,'saveGraphData')
                    dop.scrn.saveGraphData=dop.tmp.saveGraphData;
                end
            end
        end
        
        if isfield(dop,'gds'); dop=rmfield(dop,'gds'); end
    end
catch err
    %% catch dopOSCCI error
    % 
save(dopOSCCIdebug(mfilename));throw(err); 
%     dopOSCCIcrash(err,dop,mfilename);
end
end

function dop=writeLabels(dop,j)
%% labels
if ~exist(dop.gds.fnl,'file')
    fprintf('\n\t%s',['Writing header labels (',...
        dop.gds.en,' - ',dop.gds.epAbb,... % event and epoch selection
        dop.gds.grpAbbNote,... % group if used
        dop.gds.behAbbNote,... % behaviour if used
        dop.gds.sesAbbNote,')']); % session if used
    dop.gds.saveLabels={'fileName'}; % file name is first column
    if dop.def.grpFileChk
        dop.gds.saveLabels{end+1}='group';
    end
    if dop.def.sesFileChk
        dop.gds.saveLabels{end+1}='session';
    end
    % create an array of epoch samples in seconds...
    dop.gds.epochSeconds=((0:diff(dop.def.epoch(j,:))/(1/dop.def.downHertz))...
        +(dop.def.epoch(j,1)/(1/dop.def.downHertz)))*(1/dop.def.downHertz);
    for jj=1:length(dop.def.saveGraphDataChs); % dop.def.saveGraphDataChAbb={'Left','Right','Dif'};
        if dop.def.saveGraphDataChs(jj)
            dop.gds.chAbb=dop.def.saveGraphDataChAbb{jj};
            for jjj=1:length(dop.gds.epochSeconds);
                dop.gds.saveLabels{end+1}=...
                    [dop.gds.epAbb,dop.gds.chAbb,num2str(dop.gds.epochSeconds(jjj))];
                % eg., allEpochLeft-12
                % these aren't intended to be more
                % than a cue as to what's below in
                % the file - could ditch number
            end
        end
    end
    %% > save labels
    dop.gds.fid=fopen(dop.gds.fnl,'w'); % open for writing
    for jjj=1:length(dop.gds.saveLabels)
        fprintf(dop.gds.fid,'%s\t',dop.gds.saveLabels{jjj});
    end
    %% > save column numbers
    % new line and row label
    fprintf(dop.gds.fid,'\n%s\t','sampleSecondsRow'); % first column label... but to indicate row info (not fileName)
    %     fprintf(dop.gds.fid,'\n%u\t',0); % number makes reading it in much easier
    % this way first row of numbers indicates how many channels are
    % included - left, right, difference, average
    if dop.def.grpFileChk
        fprintf(dop.gds.fid,'%u\t',0); % number (element) required here to line up data due to group column label
    end
    if dop.def.sesFileChk
        fprintf(dop.gds.fid,'%u\t',0);
    end
    for jj=1:length(dop.def.saveGraphDataChs); % dop.def.saveGraphDataChAbb={'Left','Right','Dif','Avg'};
        if dop.def.saveGraphDataChs(jj)
            for jjj=1:length(dop.gds.epochSeconds)
                fprintf(dop.gds.fid,'%u\t',dop.gds.epochSeconds(jjj));
            end
        end
    end
    fprintf(dop.gds.fid,'\n'); % new line
    fclose(dop.gds.fid); % close file
end
end

%% writeData
function dop=writeData(dop,j)
%% save event data
% file name then average of epoch set
if sum(dop.def.saveGraphDataChs) % we want to save something
    fprintf('\t%s\n',dop.gds.fnl);
    dop.gds.fid=fopen(dop.gds.fnl,'a'); % open for appending
    fprintf(dop.gds.fid,'%s\t',dop.sum.fileName); % add the file name first
    if dop.def.grpFileChk
        fprintf(dop.gds.fid,'%u\t',dop.sum.grp); % add the group number
    end
    if dop.def.sesFileChk
        fprintf(dop.gds.fid,'%u\t',dop.ses.session); % add the group number
    end
    for jj=1:length(dop.def.saveGraphDataChs); % dop.def.saveGraphDataChAbb={'Left','Right','Dif','Avg'};
        if dop.def.saveGraphDataChs(jj)
            if sum(dop.gds.epScrn)
                switch jj
                    case {1,2}
                        dop.gds.data=mean(dop.stack.(dop.gds.en)(dop.gds.epScrn,:,jj));
                    case 3
                        dop.gds.data=mean(dop.dif.(dop.gds.en)(dop.gds.epScrn,:));
                    case 4
                        dop.gds.data=mean(dop.avg.(dop.gds.en)(dop.gds.epScrn,:));
                end
            else
                %                 dop.gds.epochSeconds=((0:diff(dop.def.epoch(j,:))/(1/dop.def.downHertz))...
                %         +(dop.def.epoch(j,1)/(1/dop.def.downHertz)))*(1/dop.def.downHertz);
                dop.gds.data=ones(1,length(((0:diff(dop.def.epoch(j,:))/(1/dop.def.downHertz))...
                    +(dop.def.epoch(j,1)/(1/dop.def.downHertz)))))*999;
            end
            for jjj=1:length(dop.gds.data)
                fprintf(dop.gds.fid,'%u\t',dop.gds.data(jjj));
            end
        end
    end
    fprintf(dop.gds.fid,'\n'); % new line
    fclose(dop.gds.fid);
end
end
%% save notes
function dop=dopSaveGraphNotes(dop)
%% > file note
% useful to have a short note file that explains what's in each
% of the event data files - epoch, base, poi info as well as
% which data channels are saved (left, right, dif, average).
% This info will be required for reading
%
% probably save a mat for all and txt for each event.
%
dop.gds.note=dbstack;
fprintf('\n\t%s\n',['Running ',dop.gds.note(1).name]);
for i=1:length(dop.def.evNames)
    dop.gds.ten=dop.def.evNames{i}; % temp event name
    %% > txt note
    dop.gds.txtFN=['notes_',dop.gds.ten,'.txt']; % txt file name
    dop.gds.txtFNL=[dop.sav.graphDataDir,dop.gds.txtFN]; % file name location
    if ~exist(dop.gds.txtFNL,'file')
        fprintf('\t%s\n',['Writing text note file for ',dop.gds.ten,':']);
        dop.gds.nfid=fopen(dop.gds.txtFNL,'w'); % open for writing
        fprintf(dop.gds.nfid,...
            '%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n\n',...
            ['Event Name: ',dop.gds.ten],...
            [' - n files = ',num2str(numel(dop.data.fileList))],...
            [' - epoch = ',num2str(dop.def.epoch(i,:))],...
            [' - base = ',num2str(dop.def.base(i,:))],...
            [' - poi = ',num2str(dop.def.poi(i,:))],...
            [' - type = ',num2str(dop.def.evType(i))],...
            [' - match = ',num2str(dop.def.evMatch(i))],...
            [' - hertz = ',num2str(dop.def.downHertz)],...
            '''Channels'' saved:');
        for j=1:length(dop.def.saveGraphDataChs);
            if dop.def.saveGraphDataChs(j)
                fprintf(dop.gds.nfid,'%s\n',...
                    [' - ',dop.def.saveGraphDataChAbb{j}]);
            end
        end
        fclose(dop.gds.nfid);
        fprintf('\t%s\n\t\t%s\n','Saved to: ',dop.gds.txtFNL);
    else
        fprintf('\t\t%s\n','text file already exists');
    end
end
%% > mat note
dop.gds.matFN='notes_graphData.mat'; % mat file name
dop.gds.matFNL=[dop.sav.graphDataDir,dop.gds.matFN]; % file name location
if ~exist(dop.gds.matFNL,'file')
    fprintf('\t%s\n','Writing mat note file for graphData:');
    gd.translation='graph data';
    gd.abbreviation='gd';
    gd.defInfoInclude={'evNames','epoch','base','poi','downHertz',...
        'saveGraphDataChs','saveGraphDataChAbb','evType','evMatch'};
    for i=1:length(gd.defInfoInclude);
        gd.(gd.defInfoInclude{i})=dop.def.(gd.defInfoInclude{i});
    end
    gd.n=length(dop.data.fileList);
    save(dop.gds.matFNL,'gd');
    fprintf('\t%s\n\t%s\n','Done - To open type:',...
        ['load(''',dop.gds.matFNL,''')']);
else
    fprintf('\t\t%s\n','mat file already exists');
end
clear gd
end


