function eqChs=dopRawChEqual(inChs,varargin)
% dopOSCCI Mark II: dopRawChEqual ~ 4-Jan-2012 (last edit)
%
% eqsChs=dopRawChEqual(inChs,[evCh],[epoch])
%
% sets left and right channel activation to mean 100
%
% where:
% - inChs = raw inputted left and right channels
% - evCh = event marker channel from dopRawEvMarkTidy or dopRawEvMark (used
% in dopRawAutoEdit
% - epoch = upper and lower values of desired trial epoch is samples;
% i.e., [-12 30] (e.g., in seconds) would indicate -12 seconds before
% marker through to 30 seconds after marker.
%
% [evCh] and [epoch] = optional inputs
% both required if it is desired to normalise the data by epoch.  We have
% found that this reduces artifact due to drift in a single channel.
% - note, epoch must be in samples
%
% creates a n,m,x array where n=time, m = 2 (left right) and x = the
% number of event channels
%
% if splitting baseline and poi between different events, normalization by
% epoch is based upon an extended epoch around these two intervals.
% Therefore, you should not use the same base for mulitple different pois
% unless the poi epochs are the same.
%

% -------------------------------------------------------------------------
%     '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
%
try
evCh=[];
epoch=[];
eqByEpoch=0;
evType=[];
evMatch=[];
fileName=[];
lengthWarn=0;
shortWarn=1; % display warn dialog box
if ~isempty(varargin)%nargin>1
    evCh=varargin{1};
    chSize=size(evCh);
    marks=find(evCh);
    
    tmpMarks=[];
    if chSize(2)>1
        for i=1:chSize(2)
            % these won't necessarily be the same size so use cell array
            tmpMarks{i}=marks(and(marks<chSize(1)*(i),marks>chSize(1)*(i-1)));
            while sum(tmpMarks{i}>chSize(1))
                tmpMarks{i}=tmpMarks{i}-chSize(1);
            end
        end
        marks=tmpMarks;
    else
        marks={marks};
    end
    %     base=varargin{2}; % don't need the base, just use epoch 11-3-10
    if nargin>2
        epoch=varargin{2};
    end
    if nargin>3
        eqByEpoch=varargin{3};
    end
    if nargin>4
        evType=varargin{4};
        evMatch=varargin{5};
    end
    if nargin>6
        fileName=varargin{6};
    end
    if nargin>7
        shortWarn=varargin{7};
    end
end

%% normalise for each epoch
if ~isempty(evCh) && ~isempty(epoch) && eqByEpoch %nargin>1
    fprintf('\n\t%s\n','Normalising by epoch: ');
    for i=1:size(epoch,1);
        fprintf('\n\t%i\t%i\n',epoch(i,:));
    end
    % set the marks up first
    for i = 1 : numel(marks) % cell array so pull out each cell
        
            tmpMarks=marks{i};
            epochMarks{i}=[]; % start with this empty
            baseMarks=[]; % only use these for base & poi only
            poiMarks=[]; % only use these for base & poi only
            loopMarks=i; % if matching marks, must loop with fewest markers
            
            if evType(i)<2
                baseMarks=tmpMarks; % assume current is base
                poiMarks=marks{evMatch(i)};
                epochi=[i evMatch(i)]; % epoch references for base and matched
                if evType(i) % if not base = poi only
                    epochi=[evMatch(i) i]; % [base_match poi]
                    baseMarks=marks{evMatch(i)};
                    poiMarks=tmpMarks;
                end
                % must loop on minimum number of marks
                if numel(marks{i})>numel(marks{evMatch(i)}) 
                    % if current greater than match, use match to loop
                    loopMarks=evMatch(i);
                end
            end
            for ii=1:numel(marks{loopMarks})
                if ~isempty(evType) && numel(evType)>=i
                    switch evType(i)
                        case 2 % base & poi
                            epochMarks{i}(end+1,:)=tmpMarks(ii)+epoch(i,:);
                        otherwise % base only or poi - use match
                            % we know it's base or poi by evType - evType+1
                            % can be used for selection (left and right)
                            % find base, then next suitable poi marker
                            if numel(baseMarks)<=numel(poiMarks)% set base, find poi
                                % assumes base is lower... difficult not to
                                epochMarks{i}(end+1,1)=baseMarks(ii)+epoch(epochi(1),1);
                                % find suitable match
                                epochMarks{i}(end,2)=poiMarks(find(poiMarks>epochMarks{i}(end,1),1,'first'))+epoch(epochi(2),2);
                            else % more poi than base >> set poi, find base
                                if isempty(epochMarks{i})
                                    % dummy numbers due to fewer poi
                                    % markers - these shouldn't be used...
                                    epochMarks{i} = ones(numel(baseMarks)-numel(poiMarks),2)*-99;
                                    fprintf('\t\t Fewer POI than Base markers - adding dummy markers.\n')
                                end
                                epochMarks{i}(end+1,1)=poiMarks(ii)+epoch(epochi(1),1);
                                % find suitable match
                                tmpBase = rot90(baseMarks,2);
                                
                                epochMarks{i}(end,2)=tmpBase(find(tmpBase<epochMarks{i}(end,1),1,'first'))+epoch((2),2);
                            end
                            
                    end
                else
                    epochMarks{i}(end+1,:)=tmpMarks(ii)+epoch(i,:);
                end
            end
    end
    eqChs=zeros(size(inChs,1),2,numel(epochMarks));
    for ii=1:numel(epochMarks) % cell array so pull out each cell
        epMarks=epochMarks{ii};
        for i=1:2 % each channel
            % 9-Dec-10 not sure what this was doing.
            %             if sum(tmpMarks>length(inChs)) % any markers too long
            %                 tmpMarks=tmpMarks-length(inChs); % ???
            %             end
            %         for ii=1:length(tmpMarks);
            %         disp(i)
            %             tmpEpoch=epoch; % just in case there are multiple epochs
            %             if size(epoch,1)>1
            %                 tmpEpoch=epoch(ii,:);
            %             end
            tmpSkip=0;
            for j=1:size(epMarks,1) % number of epochs
                
                %% > normalise section
                if ~tmpSkip
                    if epMarks(j,1)==epMarks(j,2) && epMarks(j,1)==-99
                        epMarks(j,:) = [0 2];
                        fprintf('\t\t note: missing data - poi to base matching\n');
                    end
                        section=epMarks(j,1):epMarks(j,2);
           
%                     switch j
%                         case 1 % first trial
%                             section=epMarks(j,1):epMarks(j+1,2);%1:tmpMarks(j+1)+tmpEpoch(1); %1-3-10
%                         case size(epMarks,1)%length(tmpMarks) % last trial
%                             
%                             section=secLimits(2)+1:length(evCh);%epMarks(j,1):length(evCh);%tmpMarks(j)+tmpEpoch(1):length(evCh);
%                         otherwise
%                             % normalis by epoch...
%                             section=secLimits(2)+1:epMarks(j,2);%tmpMarks(j)+tmpEpoch(1):tmpMarks(j)+tmpEpoch(2);
%                             % unless epoch eats into next trial
%                             if epMarks(j,2)>epMarks(j+1,1)%tmpMarks(j)+tmpEpoch(2)>tmpMarks(j+1)+tmpEpoch(1)
%                                 % then just run to next base
%                                 section=secLimits(2)+1:epMarks(j+1,1);%tmpMarks(j)+tmpEpoch(1):tmpMarks(j+1)+tmpEpoch(1);
%                             end
%                     end
                    
                      
                    if min(section)<1 
                        if ~lengthWarn && shortWarn
                            lengthWarn=1;
                            tmp=sprintf('%s\n%s\n%s\n',['Lower epoch is too low for epoch ',num2str(j)],...
                                'Consider re-running with higher value.',...
                                ['(',fileName,')']);
                            fprintf('\n%s\n',tmp);
                            warndlg(tmp,'Epoch outside data limits:'); % ,'modal'
                        end
                        if epMarks(j,2)>1 && epMarks(j,2)<length(inChs)
                            section=1:epMarks(j,2);
                        elseif epMarks(j,2)>1
                            section=1:length(inChs);
                        else
                            section=1:2;
                        end
                        
                    elseif max(section)>length(inChs)
                        section=min(section):length(inChs);
                    end
                    secLimits=[section(1) section(end)];
%                       disp(secLimits);
                    eqChs(section,i,ii)=(inChs(section,i)*100)/mean(inChs(section,i));
                    % > check for gaps
                    secBtw=[];
                    if j==1 && secLimits(1)>1
                        secBtw=1:secLimits(1)-1;
                        eqChs(secBtw,i,ii)=(inChs(secBtw,i)*100)/mean(inChs(secBtw,i));
                        secBtw=[];
                    end
                    switch j
                        case size(epMarks,1) % final epoch
                            if secLimits(2)<length(evCh)
                                secBtw=secLimits(2)+1:length(evCh);
                            end
                        otherwise %j<size(epMarks,1)%length(tmpMarks) % all except for the last trial/end
                            currentEnd=secLimits(2)+1;%tmpMarks(j)+tmpEpoch(2)+1; % just after
                            nextStart=epMarks(j+1,1)-1;%tmpMarks(j+1)+tmpEpoch(1)-1; % just before
                            if currentEnd<nextStart
                                %                             disp('btw');
                                secBtw=currentEnd:nextStart;
                            end
                    end
                    if ~isempty(secBtw)
                        eqChs(secBtw,i,ii)=(inChs(secBtw,i)*100)/mean(inChs(secBtw,i));
                    end
%                     clear secBtw currentEnd nextStart
                end
                % don't want a bunch of little corrections if heaps of
                % markers really close
                tmpSkip=0;
                if  j<size(epMarks,1) && epMarks(j+1,1)-epMarks(j,1)<diff(epMarks(j,:))*.2
                    %j<numel(tmpMarks) && ~tmpMarks(j+1)-tmpMarks(j)>diff(tmpEpoch)
                    tmpSkip=1; disp(['skip ',num2str(j)]);
                elseif j<size(epMarks,1) && epMarks(j+1,1)<1
                    tmpSkip=1; disp(['skip ',num2str(j)]);                                
                end
            end
            % have we missed anything?
            if secLimits(2)<length(eqChs)
                section=secLimits(2)+1:length(eqChs);
                eqChs(section,i,ii)=(inChs(section,i)*100)/mean(inChs(section,i));
            end
            
        end
    end
else
    eqChs=inChs;
    for i=1:2
        eqChs(:,i)=(inChs(:,i)*100)/mean(inChs(:,i));
    end
    % need a few layers of these to be in line with the number of channels
    if chSize(2)>1
        for i = 1 : chSize(2)
            eqChs(:,1:2,i)=eqChs(:,:);
        end
    end
end
clear tmp inChs marks epoch section evCh tmpMarks chSize lengthWarn
catch err
    %% catch dopOSCCI error
    save(dopOSCCIdebug(mfilename));rethrow(err);  
end
