function varargout=dopDataSplitHalfCalcSetup(eventData,poiFilter,varargin)
% dopOSCCI Mark II: dopDataSplitHalfCalcSetup ~ 13-Dec-2010 (last edit)
%
% % setup events for split half calculations

% -------------------------------------------------------------------------
%     '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\n',['Running ',mfilename],...
    'Setting up Events for Split Half LI Calculation:');
try
    inputs.varargin=varargin;
    inputs.defaults=struct('actWin',2,...);%,... % activation window duration in seconds
        'screen',[],...); % epoch screen
        'sampleRate',25,...); % sampleRate in hertz to figure out timing
        'evType',2,...); % event type: 0 = base, 1 = stim only, 2 = both
        'saveEpoch',0,...); % is the epoch data requested to be saved ('all' screen)
        'splitOptions',[1 1],...); % odd v even, random
        'splitBal',1,...); % balance the number of trials in the split
        'splitCalcSave',[1 1]); % actually do the calculation & save data
    inputs.defaults.splitLabels={'odd','even';'rand1','rand2'};
    
    
    % don't think we want to have a behavioural option... 13-Dec-2010
    %'beh',[],...); % behavioural filter variable (see dopBehSummary)
    sphs=setGetInputsStruct(inputs);
    
    if sum(sphs.splitCalcSave)
        sphs.translation='split-half setup';
        sphs.structAbbreviations='sphs';
        sphs.data=eventData; clear eventData % 27-10-10 now L&R data
        sphs.filter=poiFilter; clear poiFilter
        
        
        
        % assume data is a stack of data from dopEventStack
        sphs.ens=sphs.data.evNames; % prior 29-10-10 fieldnames(sphs.data); % event names
        for i=1:length(sphs.ens)
            sphs.en=sphs.ens{i}; % event name
            sphs.scrn=[];
            if isfield(sphs.screen,sphs.en) && sphs.evType(i) % requires stimOnly or stim eventType - not base
                for j=1:length(sphs.screen.labels)
                    sphs.sl=sphs.screen.labels{j}; % screen label
                    %                 sphs.scrn=sphs.screen.(sphs.en)(:,j); % only send in one screen column at a time
                    if or(sphs.screen.calcData(j),...
                            and(strcmp(sphs.sl,sphs.screen.labels{1}),sphs.saveEpoch))
                        % don't need to process all levels of the screening
                        % variable - only all for each epoch and scrn - or
                        % whatever is requested to be saved
                        %                 %% behavioural summary
                        %                 if ~isempty(sphs.beh)
                        %                     sphs.tmp.bvs=fieldnames(sphs.beh); % behavioural variables
                        %                     for jj=1:length(sphs.tmp.bvs); sphs.tmp.bv=sphs.tmp.bvs{jj};
                        %                         sphs.out.behNames{jj}=sphs.tmp.bv;
                        %                         sphs.tmp.bls=size(sphs.beh.(sphs.tmp.bvs{jj}),2); % behavioural levels
                        %                         for jjj=1:sphs.tmp.bls
                        %                             sphs.scrn=and(sphs.screen.(sphs.en)(:,j),sphs.beh.(sphs.tmp.bvs{jj})(:,jjj));
                        %                             fprintf('\n\t\t%s\t%s\n',sphs.en,...
                        %                                 ['( beh ',sphs.tmp.bv, '(',num2str(jjj),')',...
                        %                                 'epoch screen ',num2str(j),')']);
                        %                             sphs.out.(sphs.tmp.bv)(jjj).(sphs.en).(sphs.sl)=liCalc(lis,i); % see embedded function below
                        %                             fprintf('\t%s\n',['Beh epochs (',...
                        %                                     sphs.en,' ',sphs.out.behNames{jj},' ',num2str(jjj),'): '...
                        %                                     num2str(find( sphs.scrn'))]);
                        %                         end
                        %                     end
                        %                 else
                        %                     if sum(sphs.scrn)
                        if sphs.evType(i)
                            sphs.epochScrn=sphs.screen.(sphs.en)(:,j); % only send in one screen column at a time
                            for ii=1:numel(sphs.splitOptions)
                                sphs.tmp.ne=numel(sphs.epochScrn); % number of elements
                                if sphs.splitOptions(ii)
                                    switch ii
                                        case 1 % odd vs even
                                            sphs.splitScrn(:,1)=and(sphs.epochScrn,(mod(1:sphs.tmp.ne,2)==1)');
                                            sphs.splitScrn(:,2)=and(sphs.epochScrn,(mod(1:sphs.tmp.ne,2)==0)');
                                        case 2 % random
                                            sphs.tmp.rp=randperm(sphs.tmp.ne);
                                            sphs.tmp.sel=zeros(sphs.tmp.ne,1);
                                            sphs.tmp.sel(sphs.tmp.rp(1:sphs.tmp.ne/2))=1;
                                            sphs.splitScrn(:,1)=and(sphs.epochScrn,sphs.tmp.sel==1);
                                            sphs.splitScrn(:,2)=and(sphs.epochScrn,sphs.tmp.sel==0);
                                            
                                    end
                                    if sphs.splitBal % balancing the epochs in each split
                                        while diff(sum(sphs.splitScrn))
                                            sphs.tmp.sum=sum(sphs.splitScrn);
                                            sphs.tmp.drop=1;% drop epochs from first half
                                            if sphs.tmp.sum(2)>sphs.tmp.sum(1) % drop epochs from second half
                                                sphs.tmp.drop=2;
                                            end
                                            sphs.splitScrn(find(sphs.splitScrn(:,sphs.tmp.drop),1,'first'),sphs.tmp.drop)=0;
                                        end
                                    end
                                    for jj=1:2;
                                        sphs.spl=sphs.splitLabels{ii,jj}; %split label
                                        sphs.scrn=sphs.splitScrn(:,jj);
                                        fprintf('\n\t\t%s\t%s\n',sphs.en,['(epoch screen ',num2str(j),')']);
                                        sphs.out.(sphs.en).(sphs.sl).(sphs.spl)=sphCalc(sphs,i);
                                    end
                                end
                            end
                        end
                        
                        %                 end
                    end
                end
                %             elseif sphs.evType(i) % without screening
                %                 sphs.out.(sphs.en)=dopDataLIcalc(sphs.data.(sphs.en),...
                %                     sphs.filter.(sphs.en).poi,...
                %                     'actWin',sphs.actWin,...
                %                     'sampleRate',sphs.sampleRate);
            end
        end
    else
        fprintf('\t%s\n','Split-Half Calculations not requested');
    end
    %% set ouputs
    sphs.out.note='sph = split half laterality output';
    
    varargout{1}=sphs.out;
    fprintf('\n\t%s\n','Done');
catch err
    %% catch dopOSCCI error
    save(dopOSCCIdebug(mfilename));rethrow(err);
end
clear lis inputs li
end


function sph=sphCalc(sphs,i)
try
        zeroPt = find(sphs.filter.(sphs.en).zeroPt,1,'first');
    if isempty(zeroPt)
        % if there's a completely positive epoch
        zeroPt = sphs.filter.(sphs.en).zeroValue;
    end
    sph=dopDataLIcalc(sphs.data.(sphs.en),... % data
        sphs.filter.(sphs.en).poi,... filter
        'actWin',sphs.actWin(i),'screen',sphs.scrn,...
        'sampleRate',sphs.sampleRate,...
        'filterZero',zeroPt);
catch err
    fprintf('\t%s\n','Error in embedded function');
    %% catch dopOSCCI error
    save(dopOSCCIdebug(mfilename));rethrow(err);
end
end
