 function [results]= rmanova(factor,keepolddata,pointwisestatus)
%   This software is protected by german copyright and international treaties.             
%   Copyright 2004 Markus Junghöfer & Peter Peyk. All Rights Reserved.                     
%                                                                                          
%   THIS SOFTWARE AND DOCUMENTATION IS PROVIDED "AS IS," AND COPYRIGHT HOLDERS MAKE        
%   NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO,    
%   WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE    
%   OF THE SOFTWARE OR DOCUMENTATION WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS,
%   TRADEMARKS OR OTHER RIGHTS. COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT,       
%   INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE SOFTWARE      
%   OR DOCUMENTATION.                                                                      
 printSSMSstatus = 1;
 faststatus = 1;
 %  '[results]= rmanova(factor)' calculates a repeated measures 
 %  analysis of variance for data previously exported with 'plot2d'
 %  from 'plot3d'-menu /calculate/repeatedmeasuresanova.
 %  'factor' needs to be a cell containing in 
 %
 
 %          factor{1,1}= the number of subjects
 %          factor{1,2}= the number of time intervalls
 %          factor{1,3}= the number of channelgroups 
 %   
 %  subsequent rows can contain custom repeated measures factors 
 %  with the name of the factor in the first column...
 %
 %          factor{2,1}='valence';
 %
 %  the number of gradations in the second column...
 %
 %          factor{2,2}=3;
 %
 %  and the names of the gradations in the third column as a nested
 %  cell...
 %
 %          factor{2,3}{1}='pleasant';
 %          factor{2,3}{2}='unpleasant';
 %          factor{2,3}{3}='neutral;
 %
 %  'results' is a cell array containing F-Values...
 
global hPlot3dMenuFig hPlot2dMenuFig 
 
if nargin < 3; pointwisestatus = 0;end
if nargin < 2; keepolddata = 0;end
if nargin < 1
    %test-data
    factor{1,1}=18;
    factor{1,2}= 1;
    factor{1,3}= 2;
    factor{2,1}='valence';
    factor{2,2}=3;
    factor{2,3}={'pleasant','unpleasant','neutral'};
    factor{3,1}='prepost';
    factor{3,2}=2;
    factor{3,3}={'post','pre'};
    
end
hPlot3dList=get(hPlot3dMenuFig,'Userdata'); 
hList=get(hPlot2dMenuFig,'Userdata'); 

%try
      
    %read plot2dexport
    %---------------------
    if ~keepolddata
        
        if ~pointwisestatus
			plot2dlibfilepath= which('plot3d.m');
			plot2dlibfilepath(findstr(plot2dlibfilepath,'Plot3d.m'):findstr(plot2dlibfilepath,'Plot3d.m')+7)=[];
			filename= 'anovaexporttmp.txt';
			subjects = factor{1,1};
			zeitpunkte = factor{1,2};
			channelgroups = factor{1,3};
			nroffactors = size(factor,1)-2-factor{2,2};
			customgradations = 1;
			for j=1:nroffactors
                customgradations = customgradations*factor{j+2,2};
			end
            %printdata?
            %---------------
            printdatastatus = 0;
			[anovadata]=expdata(filename,plot2dlibfilepath,subjects,zeitpunkte,channelgroups,customgradations,printdatastatus);
            hPlot3dList=get(hPlot3dMenuFig,'Userdata');
            if ~isempty(hPlot3dList) 
                set(hPlot3dList(133),'userdata',anovadata);
            elseif ~isempty(findobj('tag','hanovadata'))
                set(findobj('tag','hanovadata'),'Userdata',anovadata);
            end
        else
			plot2dlibfilepath= which('plot3d.m');
			plot2dlibfilepath(findstr(plot2dlibfilepath,'Plot3d.m'):findstr(plot2dlibfilepath,'Plot3d.m')+7)=[];
			filename= 'anovaexporttmp.mat';
            load([plot2dlibfilepath,filename],'TotDataMat');
            if ~isempty(hPlot3dList) 
                set(hPlot3dList(133),'userdata',TotDataMat);
            elseif ~isempty(findobj('tag','hanovadata'))
                set(findobj('tag','hanovadata'),'Userdata',TotDataMat);
            end
            subjects = factor{1,1};
			zeitpunkte = factor{1,2};
			channelgroups = factor{1,3};
			nroffactors = size(factor,1)-2-factor{2,2};
			customgradations = 1;
			for j=1:nroffactors
                customgradations = customgradations*factor{j+2,2};
			end
        end
    else
        
        if ~pointwisestatus
            hPlot3dList=get(hPlot3dMenuFig,'Userdata');
            anovadata = get(hPlot3dList(133),'userdata');
            subjects = factor{1,1};
			zeitpunkte = factor{1,2};
			channelgroups = factor{1,3};
			nroffactors = size(factor,1)-2-factor{2,2};
			customgradations = 1;
			for j=1:nroffactors
                customgradations = customgradations*factor{j+2,2};
			end
        else
            hPlot3dList=get(hPlot3dMenuFig,'Userdata');
            TotDataMat = get(hPlot3dList(133),'userdata');
            subjects = factor{1,1};
			zeitpunkte = factor{1,2};
			channelgroups = factor{1,3};
			nroffactors = size(factor,1)-2-factor{2,2};
			customgradations = 1;
			for j=1:nroffactors
                customgradations = customgradations*factor{j+2,2};
			end
        end
    end
        
	
    
    
    
    if ~pointwisestatus & isempty(anovadata)
        uiwait(errordlg('There was an error exporting or reusing the data... Perhaps the filematrix is empty, no channelgroups have been selected, the numbers of intervalls in designstring do not match intervall settings in 3d-menu or the designstring does not correspond the filematrix!'));
        results = [];
    elseif pointwisestatus & isempty(TotDataMat)
        uiwait(errordlg('There was an error exporting or reusing the data... Perhaps the filematrix is empty, no channelgroups have been selected, the numbers of intervalls in designstring do not match intervall settings in 3d-menu or the designstring does not correspond the filematrix!'));
        results = [];
    end
    
    
    
    
    %========================================
    %standard
    %======================================
    if ~pointwisestatus
        
        
        
        nrofcells = zeitpunkte*channelgroups*customgradations;
		if size(anovadata,2)~=nrofcells
            errordlg('Number of cells does not match the product of factor gradations! Quitting...','Factorial design:');
            return
		end
        
        
        if nroffactors > 0
            factor1nrofgradations = factor{3,2};
        else
            factor1nrofgradations = 1;
        end
        if nroffactors > 1
            factor2nrofgradations = factor{4,2};
        else
            factor2nrofgradations = 1;
        end
        if nroffactors > 2
            factor3nrofgradations = factor{5,2};
        else
            factor3nrofgradations = 1;
        end
        if nroffactors > 3 
            factor4nrofgradations = factor{6,2};
        else
            factor4nrofgradations = 1;
        end
        
        repeatintervalls = channelgroups*factor1nrofgradations*factor2nrofgradations*factor3nrofgradations*factor4nrofgradations;
        repeatchannelgroups = factor1nrofgradations*factor2nrofgradations*factor3nrofgradations*factor4nrofgradations;
        repeatfactor1 = 1
        repeatfactor2 = factor1nrofgradations;
        repeatfactor3 = factor1nrofgradations*factor2nrofgradations; 
        repeatfactor4 = factor1nrofgradations*factor2nrofgradations*factor3nrofgradations;
		
                
        validfactors = cell(1);
        nrofvalidfactors = 0;
        validbetweenfactors = cell(1);
        nrofvalidbetweenfactors = 0;
        
		%cellmean,QS & df
		%--------------------------
		CellMean = mean(anovadata,1);
        CellSum = sum(anovadata,1);
		
         %factor 1
         %--------------
        if nroffactors > 0
           factor1nrofgradations = factor{3,2};
           if factor1nrofgradations>1
                nrofvalidfactors = nrofvalidfactors +1;
                validfactor{nrofvalidfactors,1}=factor{3,1};
                validfactor{nrofvalidfactors,2}=factor{3,2};
                validfactor{nrofvalidfactors,3}=factor{3,3};
            end
        else
            factor1nrofgradations = 1;    
        end
        
         %factor 2
        %--------------
        if nroffactors > 1
            factor2nrofgradations = factor{4,2};
            if factor2nrofgradations>1
                nrofvalidfactors = nrofvalidfactors +1;
                validfactor{nrofvalidfactors,1}=factor{4,1};
                validfactor{nrofvalidfactors,2}=factor{4,2};
                validfactor{nrofvalidfactors,3}=factor{4,3};
            end
        else
            factor2nrofgradations = 1;
        end
        
        %factor 3
        %--------------
        if nroffactors > 2
            factor3nrofgradations = factor{5,2};
            if factor3nrofgradations>1
                nrofvalidfactors = nrofvalidfactors +1;
                validfactor{nrofvalidfactors,1}=factor{5,1};
                validfactor{nrofvalidfactors,2}=factor{5,2};
                validfactor{nrofvalidfactors,3}=factor{5,3};
            end
        else
            factor3nrofgradations = 1;
        end
       
        %factor 4
        %--------------
        if nroffactors > 3 
            factor4nrofgradations = factor{6,2};
            if factor4nrofgradations>1
                nrofvalidfactors = nrofvalidfactors +1;
                validfactor{nrofvalidfactors,1}=factor{6,1};
                validfactor{nrofvalidfactors,2}=factor{6,2};
                validfactor{nrofvalidfactors,3}=factor{6,3};
            end
        else
            factor4nrofgradations=1;
        end
        
        
        %channelgroupsmean,QS & df
		%--------------------------
        if channelgroups>1
            nrofvalidfactors = nrofvalidfactors +1;
            validfactor{nrofvalidfactors,1}='channelgroup';
            validfactor{nrofvalidfactors,2}=channelgroups;
            for t=1:channelgroups
                validfactor{nrofvalidfactors,3}{t}=['cg',num2str(t)];
            end
        end
        
        
		%intervallsmean,QS & df, errorQS,df & p
		%--------------------------
        if zeitpunkte > 1
            nrofvalidfactors = nrofvalidfactors +1;
            validfactor{nrofvalidfactors,1}='intervall';
            validfactor{nrofvalidfactors,2}=zeitpunkte;
            for t=1:zeitpunkte
                validfactor{nrofvalidfactors,3}{t}=['t',num2str(t)];
            end
        end
        
        %between-factors
        %==============================
       
        for r=size(factor,1)-factor{2,2}+1:size(factor,1)
            factornrofgradations = factor{r,2};
            if factornrofgradations>1
                nrofvalidbetweenfactors = nrofvalidbetweenfactors+1;
                validbetweenfactor{nrofvalidbetweenfactors,1} = factor{r,1};
                validbetweenfactor{nrofvalidbetweenfactors,2} = factor{r,2};
                validbetweenfactor{nrofvalidbetweenfactors,3} = factor{r,3};
                validbetweenfactor{nrofvalidbetweenfactors,4} = factor{2,3}{nrofvalidbetweenfactors};
            end
        end
        
        totvalidfactors = nrofvalidfactors + nrofvalidbetweenfactors;
        
        if totvalidfactors>1
            results = cell(1,2);
            results{2,1}='Two-way Interactions';
            results{2,2}= [];
        end
        if totvalidfactors>2
            results{3,1}='Three-way Interactions';
            results{3,2}= [];
        end
        if totvalidfactors>3
            results{4,1}='Four-way Interactions';
            results{4,2}= [];
        end
        if totvalidfactors>4
            results{5,1}='Five-way Interactions';
            results{5,2}= [];
        end
        if totvalidfactors>5
            results{6,1}='Six-way Interactions';
            results{6,2}= [];
        end
        if totvalidfactors>6
            results{6,1}='Seven-way Interactions';
            results{6,2}= [];
        end
        if totvalidfactors>7
            results{6,1}='eight-way Interactions';
            results{6,2}= [];
        end
                 
        %create and save plotstringcell for later plotting
        %-------------------------------
		plotstringcell=cell(1);
		%maineffects
		for i=1:size(validfactor,1)
            plotstringcell{i,1} = validfactor{i,1};
            plotstringcell{i,2} = i;
            plotstringcell{i,3} = validfactor{i,2};
		end
		%interactions
		zaehler = i+1;
		for i=2:size(validfactor,1)
            interactions = nchoosek(1:size(validfactor,1),i);
            for t=1:size(interactions,1)
                
                label = validfactor{interactions(t,1),1};
                nrofcells = validfactor{interactions(t,1),2};
                for s=2:i
                    label = [label,'X',validfactor{interactions(t,s),1}];
                    nrofcells = nrofcells * validfactor{interactions(t,s),2};
                end
                plotstringcell{zaehler,1} = label;
                plotstringcell{zaehler,2} = interactions(t,:);
                plotstringcell{zaehler,3} = nrofcells;
                zaehler = zaehler +1;
            end
		end
		plot2dlibfilepath= which('plot3d.m');
		plot2dlibfilepath(findstr(plot2dlibfilepath,'Plot3d.m'):findstr(plot2dlibfilepath,'Plot3d.m')+7)=[];
		file= [plot2dlibfilepath,'anovautil.mat'];
		save(file,'plotstringcell');
	
        
        nrofsubjects = size(anovadata,1);
		nroffactors = nrofvalidfactors;
		if ~isempty(validbetweenfactor)
            nrofbetweenfactors = size(validbetweenfactor,1);
		end
	
        
		%totmean,QS & df
		%--------------------------
		TotMean = mean(mean(anovadata));
		GrandMean = mean(mean(anovadata));
		TotMean = mean(mean(anovadata));
		TotQS = 0;
		for i=1:size(anovadata,1)
            for j=1:size(anovadata,2)
                TotQS=TotQS+((anovadata(i,j)-TotMean)^2);
            end
		end
		TotDf = prod(size(squeeze(anovadata))-1);
        TotSum = sum(anovadata(:));
        TotQSf = TotSum.^2 / (size(anovadata,1)*size(anovadata,2));
        
           
       
        %AllQSf
        %-----------------
        AllQSf = sum(sum(anovadata.^2));
		
        
            
		%analyze factor structure
		%------------------------------
		totcells = 1;
		for j=1:size(validfactor,1)
            totcells = totcells * validfactor{j,2};
		end
		if size(anovadata,2)~= totcells
            uiwait(errordlg('Number of columns of data does not match the product of factor gradations!','Error calculating factor interaction!:'));
            results = [];
            return
		end
		factorstructure = zeros(nroffactors,totcells);
		for factorzaehler=nroffactors:-1:1
            %check gradations
            nrofgradations = validfactor{factorzaehler,2};
            if round(totcells/nrofgradations)~=totcells/nrofgradations
                uiwait(errordlg(['Number of cells cannot be divided in n-gradations for factor ',validfactor{factorzaehler,1},'!'],'Error:'));
            end
            %step size
            step = 1;
            for bottomzaehler = factorzaehler+1:nroffactors
                step = step * validfactor{bottomzaehler,2};
            end
            %update factorstructure
            gradationsvec = linspace(1,nrofgradations,nrofgradations);
            gradationzaehler = 1;
            for columnzaehler=1:step:totcells-(step-1)
                factorstructure(factorzaehler,columnzaehler:columnzaehler+(step-1))=gradationsvec(gradationzaehler);
                gradationzaehler = gradationzaehler +1;
                if gradationzaehler > nrofgradations
                    gradationzaehler = 1;
                end
            end
		end
         
		%check between factor structure and subject in groups
		%--------------------------------------------------
        GroupMean = [];
        GroupSum = [];
        CellGroupMean = [];
        CellGroupMSum = [];
		if ~isempty(validbetweenfactor)
            nrofbetweenfactors = size(validbetweenfactor,1);
            index = [];
            for r=1:nrofbetweenfactors
                index = [index,validbetweenfactor{r,2}];
                if length(finddiffel(validbetweenfactor{r,4}))~=validbetweenfactor{r,2}
                    uiwait(errordlg(['Groupindexvector for between factor ',num2str(r),' contains more or less elements than gradations specified!'],'Error:'));
                    results = [];
                    return
                end
            end
            betweenconditionmat = zeros(prod(index),length(index));
            serieslength = size(betweenconditionmat,1);
            userdefmat = zeros(size(anovadata,1),length(index));
            for t=1:length(index)
                tmpvec = []
                while size(tmpvec,1)<size(betweenconditionmat,1)
                    for u=1:index(t)
                        tmpvec = [tmpvec; ones(serieslength/index(t),1)*u];
                    end
                end
                serieslength = serieslength/index(t); 
                betweenconditionmat(:,t)=tmpvec;
                userdefmat(:,t) = (validbetweenfactor{t,4})';
            end
            %replace zeros
            if ~isempty(find(userdefmat==0))
                userdefmat = userdefmat + 1;
            end
            betweensubjectcell = cell(size(betweenconditionmat,1),1);
			CellGroupMean = zeros(size(betweenconditionmat,1),size(anovadata,2));
			CellGroupSum = zeros(size(betweenconditionmat,1),size(anovadata,2));
            for e=1:size(betweenconditionmat,1)
                for f=1:size(userdefmat,1)
                    if betweenconditionmat(e,:)==userdefmat(f,:)
                        betweensubjectcell{e} = [betweensubjectcell{e} f];
                    end
                end
                CellGroupMean(e,:)= mean(anovadata(betweensubjectcell{e},:),1);
                CellGroupSum(e,:)= sum(anovadata(betweensubjectcell{e},:),1);
            end
            for z=1:length(betweensubjectcell)-1
                if length(betweensubjectcell{z})~=length(betweensubjectcell{z+1})
                    uiwait(errordlg('Unequal group sizes on a between factor! This analysis is not yet supported!','Error:'));
                    return
                end
            end
            betweenfactorstructure = betweenconditionmat;
            GroupMean = mean(CellGroupMean,2);
            GroupSum = sum(CellGroupSum,2);
            %total Grouping-Factor-SSs
            TotBetweenQS = 0;
            TotBetweenSum = 0;
            for cellc = 1: length(betweensubjectcell)
                TotBetweenQS = TotBetweenQS + length([betweensubjectcell{cellc}])*size(anovadata,2)*(GroupMean(cellc)-GrandMean)^2;
            end
            TotBetweenQSf = sum(GroupSum.^2)/(size(anovadata,2)*length(betweensubjectcell{1})) - TotQSf;
		end
	
        
        %subjectmean,QS & df (between)
		%--------------------------
		SubjectMean = mean(anovadata,2);
		SubjectSum = sum(anovadata,2);
        if ~isempty(betweensubjectcell)
             if size(anovadata,2)>1
				SubjectsQS=0;
                for k=1:size(anovadata,1)
                    for h=1:length(betweensubjectcell)
                        if ~isempty(find(betweensubjectcell{h}==k))
                            group = h;
                            break;
                        end
                    end
                    SubjectsQS = SubjectsQS + size(anovadata,2)*(SubjectMean(k)-GroupMean(group))^2;
                end
				SubjectsDf = subjects-1;
            else
                uiwait(errordlg('Cannot calculate repeated measures ANOVA with less than 2 subjects!','Error:'));
                return
            end
            SubjectKZ = sum((mean(anovadata,2)).^2)/size(anovadata,2);
        else
            if size(anovadata,2)>1
				SubjectsQS=0;
                for k=1:size(anovadata,1)
                    SubjectsQS = SubjectsQS + size(anovadata,2)*(SubjectMean(k)-TotMean)^2;
                end
				SubjectsDf = subjects-1;
            else
                uiwait(errordlg('Cannot calculate repeated measures ANOVA with less than 2 subjects!','Error:'));
                return
            end
            SubjectKZ = sum((mean(anovadata,2)).^2)/size(anovadata,2);
        end
        SubjectsQSf = sum((SubjectSum.^2),1)/size(anovadata,2) -  TotQSf;
        
        
        % within QSf
        WithinQSf = AllQSf - SubjectsQSf - TotBetweenQSf;
        
        
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        %%%%                  Haupteffekte                    %%%%
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        
        
        results{1,1}='main effects';
        resultstmp = results;
        pointwisestatus = 0;
        resultstmp{1,2}=calc_rm_anova_fast(anovadata,validfactor,validbetweenfactor,1,pointwisestatus,...
                                      CellMean,CellSum, CellGroupMean,CellGroupSum,SubjectMean,GrandMean,factorstructure,...
                                      betweenfactorstructure,betweensubjectcell,nroffactors,nrofbetweenfactors,...
                                      nrofsubjects,TotQS,TotDf,SubjectsQS,SubjectsDf,GroupMean,...
                                      TotQSf,SubjectsQSf,AllQSf,WithinQSf);
        
            
        
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        %%%%                  Interaktionen                   %%%%
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
       
        
        for r=2:totvalidfactors
            tmpdata=calc_rm_anova_fast(anovadata,validfactor,validbetweenfactor,r,pointwisestatus,...
                                    CellMean,CellSum,CellGroupMean,CellGroupSum,SubjectMean,GrandMean,factorstructure,...
                                    betweenfactorstructure,betweensubjectcell,nroffactors,nrofbetweenfactors,...
                                    nrofsubjects,TotQS,TotDf,SubjectsQS,SubjectsDf,GroupMean,...
                                    TotQSf,SubjectsQSf,AllQSf,WithinQSf);
            if isempty(tmpdata)
                resultstmp=[];
                return
            else
                resultstmp{r,2} = tmpdata;
            end
        end
        results=resultstmp;
        
        
        
        %normal
        %------------
        if ~faststatus
            
            %Modify Sum-Squares Error-Sum-Squares, Error-MS and calculate F- and p-Value:
            %-----------------------------------------------------------------
            %   When using grouping factors, ErrorQS will have to be modified
            %   again....(Winer(1971,pp. 548) --> grouping factor QS have to be removed out of all within-error-QSs
            
            
            %1:Name 2:ConditionQS(SS) 3:ConditionDf 4:ConditionMeanSquare(MS) 5:ErrorQS 6:ErrorDf 7:ErrorMeanSquare(MS)...
            %8:F-Value 9:p-Value
            
           
            %main-within-effects
%             for r=1:nrofvalidfactors
%                 %Error-SS
%                 results{1,2}{r,5} = results{1,2}{r,5}-SubjectsQS;
%                 %Subtract Main-Effect from Error-SS
%                 results{1,2}{r,5} = results{1,2}{r,5}-results{1,2}{r,2};
%                 if ~isempty(betweensubjectcell)
%                     %Subtract Total-Grouping-Factor-SSs from Error-SS
%                     results{1,2}{r,5} = results{1,2}{r,5} - TotBetweenQS;
%                 end
%                 %Error-MS
%                 results{1,2}{r,7} = results{1,2}{r,5} / results{1,2}{r,6};
%                 %F-Value
%                 results{1,2}{r,8}=  results{1,2}{r,4} / results{1,2}{r,7};
%                 %p-Value
%                 results{1,2}{r,9}=  1- fcdf(results{1,2}{r,8},results{1,2}{r,3},results{1,2}{r,6}); 
%             end
%             %main-between-effects
%             for r=nrofvalidfactors+1:totvalidfactors;
%                 %Subtract Main-Effect from Error-SS
%                 results{1,2}{r,5} = results{1,2}{r,5}-results{1,2}{r,2};
%                 %Error-MS
%                 results{1,2}{r,7} = results{1,2}{r,5} / results{1,2}{r,6};
%                 %Condition-MS
%                 results{1,2}{r,4} = results{1,2}{r,2} / results{1,2}{r,3};
%                 %F-Value
%                 results{1,2}{r,8}=  results{1,2}{r,4} / results{1,2}{r,7};
%                 %p-Value
%                 results{1,2}{r,9}=  1- fcdf(results{1,2}{r,8},results{1,2}{r,3},results{1,2}{r,6}); 
%             end
%             
%             
%             
%             
%             
%             %interactions
%             for r=2:totvalidfactors %counts up interaction-type
%                 for s=1:size(results{r,2},1) %counts up combinations of factors for r-way-interaction
%                     
%                     %within
%                     if isempty(find(results{r,2}{s,1}>nrofvalidfactors))
%                         
%                         %Subtract main-effects-SS
%                         for e=1:size(results{r,2}{s,1},2)
%                             %main-effect-QS from interaction-effect-QS
%                             fprintf(['Subtracting ',strrep(num2str(results{r,2}{s,1}(e)),'  ','-'),'-main-effect-QS from ',strrep(num2str(results{r,2}{s,1}),'  ','-'),'-interaction-effect-QS:\n']);
%                             results{r,2}{s,2}=results{r,2}{s,2}-results{1,2}{results{r,2}{s,1}(e),2};
%                             %QS =  results{r,2}{s,2}
%                             %and main-effect-error-QS from error-QS
%                             fprintf(['Subtracting ',strrep(num2str(results{r,2}{s,1}(e)),'  ','-'),'-main-effect-error-QS from ',strrep(num2str(results{r,2}{s,1}),'  ','-'),'-interaction-error-QS:\n']);
%                             results{r,2}{s,5}=results{r,2}{s,5}-results{1,2}{results{r,2}{s,1}(e),5};
%                             %QS =  results{r,2}{s,5}
%                             %and main-effect-QS from interaction-error-QS
%                             fprintf(['Subtracting ',strrep(num2str(results{r,2}{s,1}(e)),'  ','-'),'-main-effect-QS from ',strrep(num2str(results{r,2}{s,1}),'  ','-'),'-interaction-error-QS:\n']);
%                             results{r,2}{s,5}=results{r,2}{s,5}-results{1,2}{results{r,2}{s,1}(e),2};
%                         end
%                          
%                        
%                         %subtract lower order interaction-SS
%                         for f=r-1:-1:2 %f counts down the interaction-types
%                             
%                             for q=1:size(results{f,2},1) %q counts up combinations of factors for f-way-interaction
%                                 matchzaehler = 0;
%                                 
%                                 %find relevant lower order interactions
%                                 for v=1:size(results{f,2}{q,1},2) %v counts across numbers designating interaction type
%                                     if ~isempty(find(results{f,2}{q,1}(v)==results{r,2}{s,1}))
%                                         matchzaehler = matchzaehler+1;
%                                     end
%                                 end
%                                 if matchzaehler == f
%                                     
%                                     %subtract interaction-SS from condition-QS
%                                     fprintf(['Subtracting ',strrep(num2str(results{f,2}{q,1}),'  ','-'),'-interaction-effect-QS from ',strrep(num2str(results{r,2}{s,1}),'  ','-'),'-interaction-effect-QS:\n']);
%                                     results{r,2}{s,2}=results{r,2}{s,2}-results{f,2}{q,2};
%                                     %QS =  results{r,2}{s,2}
%                                     
%                                     %subtract interaction-SS from error-QS
%                                     fprintf(['Subtracting ',strrep(num2str(results{f,2}{q,1}),'  ','-'),'-interaction-effect-QS from ',strrep(num2str(results{r,2}{s,1}),'  ','-'),'-interaction-error-QS:\n']);
%                                     results{r,2}{s,5}=results{r,2}{s,5}-results{f,2}{q,2};
%                                     %QS =  results{r,2}{s,5}
%                                     
%                                     %and its error-QS from error-QS
%                                     fprintf(['Subtracting ',strrep(num2str(results{f,2}{q,1}),'  ','-'),'-interaction-error-QS from ',strrep(num2str(results{r,2}{s,1}),'  ','-'),'-interaction-error-QS:\n']);
%                                     results{r,2}{s,5}=results{r,2}{s,5}-results{f,2}{q,5};
%                                     %QS =  results{r,2}{s,5}
%                                 end
%                             end
%                         end
%                         
%                         %subtract interaction from error-QS 
%                         fprintf(['Subtracting ',strrep(num2str(results{r,2}{s,1}),'  ','-'),'-interaction-effect-QS from ',strrep(num2str(results{r,2}{s,1}),'  ','-'),'-interaction-error-QS:\n']);
%                         results{r,2}{s,5}=results{r,2}{s,5}-results{r,2}{s,2};
%                         %QS =  results{r,2}{s,5}
%                         
%                         %subtract subject-QS from Error-SS 
%                         fprintf(['Subtracting ','Subject-QS from ',strrep(num2str(results{r,2}{s,1}),'  ','-'),'-interaction-error-QS:\n']);
%                         results{r,2}{s,5}=results{r,2}{s,5}-SubjectsQS;
%                         %QS =  results{r,2}{s,5}
%                         
%                         
%                         %Condition-MS
%                         results{r,2}{s,4} = results{r,2}{s,2} / results{r,2}{s,3};
%                         %Error-MS
%                         results{r,2}{s,7} = results{r,2}{s,5} / results{r,2}{s,6};
%                         %F-Value
%                         results{r,2}{s,8}=  results{r,2}{s,4} / results{r,2}{s,7};
%                         %p-Value
%                         results{r,2}{s,9}=  1- fcdf(results{r,2}{s,8},results{r,2}{s,3},results{r,2}{s,6}); 
%                      
%                     %with between
%                     else
%                         
%                         %Subtract main-effects-SS
%                         for e=1:size(results{r,2}{s,1},2)
%                             %main-effect-QS from interaction-effect-QS
%                             fprintf(['Subtracting ',strrep(num2str(results{r,2}{s,1}(e)),'  ','-'),'-main-effect-QS from ',strrep(num2str(results{r,2}{s,1}),'  ','-'),'-interaction-effect-QS:\n']);
%                             results{r,2}{s,2}=results{r,2}{s,2}-results{1,2}{results{r,2}{s,1}(e),2};
%                              %main-effect-QS from error-QS
%                             fprintf(['Subtracting ',strrep(num2str(results{r,2}{s,1}(e)),'  ','-'),'-main-effect-QS from ',strrep(num2str(results{r,2}{s,1}),'  ','-'),'-error-QS:\n']);
%                             results{r,2}{s,5}=results{r,2}{s,5}-results{1,2}{results{r,2}{s,1}(e),2};
%                         end
%                          
%                        
%                         %subtract lower order interaction-SS
%                         for f=r-1:-1:2 %f counts down the interaction-types
%                             for q=1:size(results{f,2},1) %q counts up combinations of factors for f-way-interaction
%                                 matchzaehler = 0;
%                                 %find relevant lower order interactions
%                                 for v=1:size(results{f,2}{q,1},2) %v counts across numbers designating interaction type
%                                     if ~isempty(find(results{f,2}{q,1}(v)==results{r,2}{s,1}))
%                                         matchzaehler = matchzaehler+1;
%                                     end
%                                 end
%                                 if matchzaehler == f
%                                     %subtract interaction-SS from condition-QS
%                                     fprintf(['Subtracting ',strrep(num2str(results{f,2}{q,1}),'  ','-'),'-interaction-effect-QS from ',strrep(num2str(results{r,2}{s,1}),'  ','-'),'-interaction-effect-QS:\n']);
%                                     results{r,2}{s,2}=results{r,2}{s,2}-results{f,2}{q,2};
%                                     %subtract interaction-SS from error-QS
%                                     fprintf(['Subtracting ',strrep(num2str(results{f,2}{q,1}),'  ','-'),'-interaction-effect-QS from ',strrep(num2str(results{r,2}{s,1}),'  ','-'),'-interaction-error-QS:\n']);
%                                     results{r,2}{s,5}=results{r,2}{s,5}-results{f,2}{q,2};
%                                 end
%                             end
%                         end
%                         
%                         %find effect without between components
%                         %1:Name 2:ConditionQS(SS) 3:ConditionDf 4:ConditionMeanSquare(MS) 5:ErrorQS 6:ErrorDf 7:ErrorMeanSquare(MS)...
%                         %8:F-Value 9:p-Value
%                         order = length(find(results{r,2}{s,1}<nrofvalidfactors+1));
%                         effect = results{r,2}{s,1};
%                         effect(find(effect>nrofvalidfactors))=[];
%                         for t=1:size(results{order,2},1)
%                             if sum(results{order,2}{t,1}==effect)==length(effect)
%                                 ErrorQS = results{order,2}{t,5};
%                                 ErrorMS = results{order,2}{t,5} / results{r,2}{s,6};
%                                 ErrorDf = results{r,2}{s,6}; %calculated in 'calc_rm_anova' and differently than within
%                             end
%                         end
%                         
%                         results{r,2}{s,5}=ErrorQS;
%                         results{r,2}{s,6}=ErrorDf;
%                         results{r,2}{s,7}=ErrorMS;                   
%                         
%                         %Condition-MS
%                         results{r,2}{s,4} = results{r,2}{s,2} / results{r,2}{s,3};
%                         %Error-MS
%                         results{r,2}{s,7} = results{r,2}{s,5} / results{r,2}{s,6};
%                         %F-Value
%                         results{r,2}{s,8}=  results{r,2}{s,4} / results{r,2}{s,7};
%                         %p-Value
%                         results{r,2}{s,9}=  1- fcdf(results{r,2}{s,8},results{r,2}{s,3},results{r,2}{s,6}); 
%                       
%                     end
%                 end
%             end
         
        %fast
        %------------
        else
               
             %main-within-effects
            for r=1:nrofvalidfactors
                
                %Main-Effect_MS
                results{1,2}{r,4} = results{1,2}{r,2}/results{1,2}{r,3};
                %Subtract SubjectQSf from Error-SS
                results{1,2}{r,5} = results{1,2}{r,5}-SubjectsQSf;
                %Subtract Main-Effect-QSf from Error-SS
                results{1,2}{r,5} = results{1,2}{r,5}-results{1,2}{r,2};
                %Error-MS
                results{1,2}{r,7} = results{1,2}{r,5} / results{1,2}{r,6};
                %F-Value
                results{1,2}{r,8}=  results{1,2}{r,4} / results{1,2}{r,7};
                %p-Value
                results{1,2}{r,9}=  1- fcdf(results{1,2}{r,8},results{1,2}{r,3},results{1,2}{r,6}) ;
            end   
            %main-between-effects
            for r=nrofvalidfactors+1:totvalidfactors;
                %Subtract Main-Effect from Error-SS
                results{1,2}{r,5} = results{1,2}{r,5}-results{1,2}{r,2};
                %Error-MS
                results{1,2}{r,7} = results{1,2}{r,5} / results{1,2}{r,6};
                %Condition-MS
                results{1,2}{r,4} = results{1,2}{r,2} / results{1,2}{r,3};
                %F-Value
                results{1,2}{r,8}=  results{1,2}{r,4} / results{1,2}{r,7};
                %p-Value
                results{1,2}{r,9}=  1- fcdf(results{1,2}{r,8},results{1,2}{r,3},results{1,2}{r,6}); 
            end
            
            
            %1:Name 2:ConditionQS(SS) 3:ConditionDf 4:ConditionMeanSquare(MS) 5:ErrorQS 6:ErrorDf 7:ErrorMeanSquare(MS)...
            %8:F-Value 9:p-Value
            
            %interactions
            for r=2:totvalidfactors %counts up interaction-type
                for s=1:size(results{r,2},1) %counts up combinations of factors for r-way-interaction
                    
                    
                    %reiner within
                    %======================
                    if isempty(find(results{r,2}{s,1}>nrofvalidfactors))
                        
                        %Subtract main-effects-SS
                        for e=1:size(results{r,2}{s,1},2)
                            %main-effect-QS from interaction-effect-QS
                            results{r,2}{s,2}=results{r,2}{s,2}-results{1,2}{results{r,2}{s,1}(e),2}
                            %and main-effect-error-QS from error-QS
                            results{r,2}{s,5}=results{r,2}{s,5}-results{1,2}{results{r,2}{s,1}(e),5}
                            %QS =  results{r,2}{s,5}
                            %and main-effect-QS from interaction-error-QS
                            results{r,2}{s,5}=results{r,2}{s,5}-results{1,2}{results{r,2}{s,1}(e),2}
                        end
                         
                       
                        %subtract lower order interaction-SS
                        for f=r-1:-1:2 %f counts down the interaction-types
                            
                            for q=1:size(results{f,2},1) %q counts up combinations of factors for f-way-interaction
                                matchzaehler = 0;
                                
                                %find relevant lower order interactions
                                for v=1:size(results{f,2}{q,1},2) %v counts across numbers designating interaction type
                                    if ~isempty(find(results{f,2}{q,1}(v)==results{r,2}{s,1}))
                                        matchzaehler = matchzaehler+1;
                                    end
                                end
                                if matchzaehler == f
                                    
                                    %subtract interaction-SS from condition-QS
                                    results{r,2}{s,2}=results{r,2}{s,2}-results{f,2}{q,2}
                                    %QS =  results{r,2}{s,2}
                                    
                                    %subtract interaction-SS from error-QS
                                    results{r,2}{s,5}=results{r,2}{s,5}-results{f,2}{q,2}
                                    %QS =  results{r,2}{s,5}
                                    
                                    %and its error-QS from error-QS
                                    results{r,2}{s,5}=results{r,2}{s,5}-results{f,2}{q,5}
                                    %QS =  results{r,2}{s,5}
                                end
                            end
                        end
                        
                        %subtract interaction from error-QS 
                        results{r,2}{s,5}=results{r,2}{s,5}-results{r,2}{s,2}
                        %QS =  results{r,2}{s,5}
                        
                        %subtract subject-QS from Error-SS 
                        results{r,2}{s,5}=results{r,2}{s,5}-SubjectsQS
                        %QS =  results{r,2}{s,5}
                        
                        
                        %Condition-MS
                        results{r,2}{s,4} = results{r,2}{s,2} / results{r,2}{s,3}
                        %Error-MS
                        results{r,2}{s,7} = results{r,2}{s,5} / results{r,2}{s,6}
                        %F-Value
                        results{r,2}{s,8}=  results{r,2}{s,4} / results{r,2}{s,7}
                        %p-Value
                        results{r,2}{s,9}=  1- fcdf(results{r,2}{s,8},results{r,2}{s,3},results{r,2}{s,6})
                     
                    %mit between
                    %======================
                    else
                        
                        
                       %Subtract main-effects-SS
                        for e=1:size(results{r,2}{s,1},2)
                            %main-effect-QS from interaction-effect-QS
                            fprintf(['Subtracting ',strrep(num2str(results{r,2}{s,1}(e)),'  ','-'),'-main-effect-QS from ',strrep(num2str(results{r,2}{s,1}),'  ','-'),'-interaction-effect-QS:\n']);
                            results{r,2}{s,2}=results{r,2}{s,2}-results{1,2}{results{r,2}{s,1}(e),2};
                             %main-effect-QS from error-QS
                            fprintf(['Subtracting ',strrep(num2str(results{r,2}{s,1}(e)),'  ','-'),'-main-effect-QS from ',strrep(num2str(results{r,2}{s,1}),'  ','-'),'-error-QS:\n']);
                            results{r,2}{s,5}=results{r,2}{s,5}-results{1,2}{results{r,2}{s,1}(e),2};
                        end
                         
                       
                        %subtract lower order interaction-SS
                        for f=r-1:-1:2 %f counts down the interaction-types
                            for q=1:size(results{f,2},1) %q counts up combinations of factors for f-way-interaction
                                matchzaehler = 0;
                                %find relevant lower order interactions
                                for v=1:size(results{f,2}{q,1},2) %v counts across numbers designating interaction type
                                    if ~isempty(find(results{f,2}{q,1}(v)==results{r,2}{s,1}))
                                        matchzaehler = matchzaehler+1;
                                    end
                                end
                                if matchzaehler == f
                                    %subtract interaction-SS from condition-QS
                                    fprintf(['Subtracting ',strrep(num2str(results{f,2}{q,1}),'  ','-'),'-interaction-effect-QS from ',strrep(num2str(results{r,2}{s,1}),'  ','-'),'-interaction-effect-QS:\n']);
                                    results{r,2}{s,2}=results{r,2}{s,2}-results{f,2}{q,2};
                                    %subtract interaction-SS from error-QS
                                    fprintf(['Subtracting ',strrep(num2str(results{f,2}{q,1}),'  ','-'),'-interaction-effect-QS from ',strrep(num2str(results{r,2}{s,1}),'  ','-'),'-interaction-error-QS:\n']);
                                    results{r,2}{s,5}=results{r,2}{s,5}-results{f,2}{q,2};
                                end
                            end
                        end
                        
                        %find effect without between components
                        %1:Name 2:ConditionQS(SS) 3:ConditionDf 4:ConditionMeanSquare(MS) 5:ErrorQS 6:ErrorDf 7:ErrorMeanSquare(MS)...
                        %8:F-Value 9:p-Value
                        order = length(find(results{r,2}{s,1}<nrofvalidfactors+1));
                        effect = results{r,2}{s,1};
                        effect(find(effect>nrofvalidfactors))=[];
                        for t=1:size(results{order,2},1)
                            if sum(results{order,2}{t,1}==effect)==length(effect)
                                ErrorQS = results{order,2}{t,5};
                                ErrorMS = results{order,2}{t,5} / results{r,2}{s,6};
                                ErrorDf = results{r,2}{s,6}; %calculated in 'calc_rm_anova' and differently than within
                            end
                        end
                        
                        results{r,2}{s,5}=ErrorQS;
                        results{r,2}{s,6}=ErrorDf;
                        results{r,2}{s,7}=ErrorMS;                   
                        
                        %Condition-MS
                        results{r,2}{s,4} = results{r,2}{s,2} / results{r,2}{s,3};
                        %Error-MS
                        results{r,2}{s,7} = results{r,2}{s,5} / results{r,2}{s,6};
                        %F-Value
                        results{r,2}{s,8}=  results{r,2}{s,4} / results{r,2}{s,7};
                        %p-Value
                        results{r,2}{s,9}=  1- fcdf(results{r,2}{s,8},results{r,2}{s,3},results{r,2}{s,6});  
                        
                        
                    end
                end
            end
        end
        
       
        
        
        %Write report
        %----------------
        formatstring = '%7.3f';
        
        rowzaehler =1;
        
         %TotQS
        outstring{rowzaehler,1} = ['Total: '];
        rowzaehler = rowzaehler+1;
        outstring{rowzaehler,1} = '----------------------------';
        rowzaehler = rowzaehler+1;
        outstring{rowzaehler,1} = ['TotalQS: ',num2str(TotQS,formatstring),'; TotalDf: ',num2str(TotDf),';'];
        rowzaehler = rowzaehler+1;outstring{rowzaehler,1}='';
        rowzaehler = rowzaehler+1;
        
        
        %SubjectsQS
        outstring{rowzaehler,1} = ['Subjects: '];
        rowzaehler = rowzaehler+1;
        outstring{rowzaehler,1} = '----------------------------';
        rowzaehler = rowzaehler+1;
        outstring{rowzaehler,1} = ['SubjectsQS: ',num2str(SubjectsQS,formatstring),'; SubjectDf: ',num2str(SubjectsDf),';'];
        rowzaehler = rowzaehler+1;outstring{rowzaehler,1}='';
        rowzaehler = rowzaehler+1;
        
        %Main Effects
        outstring{rowzaehler,1} = 'Main Effects:';
        rowzaehler = rowzaehler+1;
        outstring{rowzaehler,1} = '----------------------------';
        rowzaehler = rowzaehler+1;
        
        
        for v=1:nrofvalidfactors
              if printSSMSstatus
                  outstring{rowzaehler,1}=[validfactor{v,1},': ConditionQS: ',num2str(results{1,2}{v,2},formatstring),...
                  ': ConditionMQS: ',num2str(results{1,2}{v,4},formatstring),'; ErrorQS: ',num2str(results{1,2}{v,5},formatstring),...
                  ': ErrorMQS: ',num2str(results{1,2}{v,7},formatstring),'; p = ',num2str(results{1,2}{v,9},formatstring),...
                  ';'];
              end
              outstring{rowzaehler,1}=[outstring{rowzaehler,1},validfactor{v,1},': p = ',num2str(results{1,2}{v,9},formatstring),...
                     '; F(',num2str(results{1,2}{v,3}),',',num2str(results{1,2}{v,6}),...
                     ')=',num2str(results{1,2}{v,8},formatstring),';'];
             rowzaehler = rowzaehler+1;
        end
        for v=nrofvalidfactors+1:totvalidfactors
             if printSSMSstatus
                  outstring{rowzaehler,1}=[validbetweenfactor{v-nrofvalidfactors,1},': ConditionQS: ',num2str(results{1,2}{v,2},formatstring),...
                  ': ConditionMQS: ',num2str(results{1,2}{v,4},formatstring),'; ErrorQS: ',num2str(results{1,2}{v,5},formatstring),...
                  ': ErrorMQS: ',num2str(results{1,2}{v,7},formatstring),'; p = ',num2str(results{1,2}{v,9},formatstring),...
                  ';'];
             end
             outstring{rowzaehler,1}=outstring{rowzaehler,1},[validbetweenfactor{v-nrofvalidfactors,1},': p = ',num2str(results{1,2}{v,9},formatstring),...
                 '; F(',num2str(results{1,2}{v,3}),',',num2str(results{1,2}{v,6}),...
                 ')=',num2str(results{1,2}{v,8},formatstring),';'];
             rowzaehler = rowzaehler+1;
        end
       
        outstring{rowzaehler,1}='';
        rowzaehler = rowzaehler+1;
        
        
        %interactions
        for w=2:size(results,1)
            
            outstring{rowzaehler,1}=[results{w,1},':'];
            rowzaehler = rowzaehler + 1;
            outstring{rowzaehler,1}='----------------------------';
            rowzaehler = rowzaehler + 1;
            
            for v=1:size(results{w,2},1)
                outstring{rowzaehler,1}='';
                if results{w,2}{v,1}(1)<=nrofvalidfactors
                    outstring{rowzaehler,1}=[outstring{rowzaehler,1} validfactor{results{w,2}{v,1}(1),1}];
                else
                    outstring{rowzaehler,1}=[outstring{rowzaehler,1} validbetweenfactor{results{w,2}{v,1}(1)-nrofvalidfactors,1}];
                end
                
                for t=2:size(results{w,2}{1},2)
                    if results{w,2}{v,1}(t)>nrofvalidfactors
                        outstring{rowzaehler,1}=[outstring{rowzaehler,1} ' x ' validbetweenfactor{results{w,2}{v,1}(t)-nrofvalidfactors,1}];
                    else
                        outstring{rowzaehler,1}=[outstring{rowzaehler,1} ' x ' validfactor{results{w,2}{v,1}(t),1}];
                    end
                end
                
                 outstring{rowzaehler,1}=[outstring{rowzaehler,1},': ConditionQS: ',num2str(results{w,2}{v,2},formatstring),...
                 '; ConditionMQS: ',num2str(results{w,2}{v,4},formatstring),'; ErrorQS: ',num2str(results{w,2}{v,5},formatstring),...
                 '; ErrorMQS: ',num2str(results{w,2}{v,7},formatstring),'; p = ',num2str(results{w,2}{v,9},formatstring),...
                 ';'];
                 
                 outstring{rowzaehler,1}=[outstring{rowzaehler,1},': p = ',num2str(results{w,2}{v,9},formatstring),...
                        '; F(',num2str(results{w,2}{v,3}),',',num2str(results{w,2}{v,6}),...
                        ')=',num2str(results{w,2}{v,8},formatstring),';'];
            
                rowzaehler = rowzaehler + 1;
            end
            outstring{rowzaehler,1}='';
            rowzaehler = rowzaehler + 1;
        end
       
        
        uigettext('Results:',outstring,'nomodal',1);
        hfactor = findobj('tag','hfactor');
        set(hfactor,'userdata',validfactor);
        set(findobj('tag','hanovadata'),'Userdata',anovadata);
        set(findobj('tag','hfactorp2d'),'userdata',factor);
        set(findobj('tag','hresults'),'userdata',results);
    
        
        
    %======================================
    %pointwise
    %======================================
    else
        
        hPlot2dList=get(hPlot2dMenuFig,'Userdata');
        hPlot3dList=get(hPlot3dMenuFig,'Userdata');
        ParaVec=get(hPlot3dList(62),'Userdata');
        NChan=ParaVec(16);
        NPoints = factor{1,2};
        FMat = zeros(NChan,NPoints);
        PMat = zeros(NChan,NPoints);
        nrofcells = customgradations;
        text1=['Channel #    ',int2str(1),' of ',int2str(NChan)];
        text2='';
        okfigure=infdlg('rmANOVA progress:',text1,text2,'','');
        set(okfigure,'position',[0.4 0.4 0.15 0.15]);
        chantext = findobj('Tag','msgtext');
        pointstext = findobj('Tag','statustext');
        
        if nroffactors > 0
            factor1nrofgradations = factor{2,2};
        else
            factor1nrofgradations = 1;
        end
        if nroffactors > 1
            factor2nrofgradations = factor{3,2};
        else
            factor2nrofgradations = 1;
        end
        if nroffactors > 2
            factor3nrofgradations = factor{4,2};
        else
            factor3nrofgradations = 1;
        end
        if nroffactors > 3 
            factor4nrofgradations = factor{5,2};
        else
            factor4nrofgradations = 1;
        end
        
        repeatintervalls = channelgroups*factor1nrofgradations*factor2nrofgradations*factor3nrofgradations*factor4nrofgradations;
        repeatchannelgroups = factor1nrofgradations*factor2nrofgradations*factor3nrofgradations*factor4nrofgradations;
        repeatfactor1 = 1
        repeatfactor2 = factor1nrofgradations;
        repeatfactor3 = factor1nrofgradations*factor2nrofgradations; 
        repeatfactor4 = factor1nrofgradations*factor2nrofgradations*factor3nrofgradations;
		
        
        validfactors = cell(1);
        nrofvalidfactors = 0;
        
        %factor 1
         %--------------
        if nroffactors > 0
           factor1nrofgradations = factor{2,2};
           if factor1nrofgradations>1
                nrofvalidfactors = nrofvalidfactors +1;
                validfactor{nrofvalidfactors,1}=factor{2,1};
                validfactor{nrofvalidfactors,2}=factor{2,2};
                validfactor{nrofvalidfactors,3}=factor{2,3};
            end
        else
            factor1nrofgradations = 1;    
        end
        
         %factor 2
        %--------------
        if nroffactors > 1
            factor2nrofgradations = factor{3,2};
            if factor2nrofgradations>1
                nrofvalidfactors = nrofvalidfactors +1;
                validfactor{nrofvalidfactors,1}=factor{3,1};
                validfactor{nrofvalidfactors,2}=factor{3,2};
                validfactor{nrofvalidfactors,3}=factor{3,3};
            end
        else
            factor2nrofgradations = 1;
        end
        
        %factor 3
        %--------------
        if nroffactors > 2
            factor3nrofgradations = factor{4,2};
            if factor3nrofgradations>1
                nrofvalidfactors = nrofvalidfactors +1;
                validfactor{nrofvalidfactors,1}=factor{4,1};
                validfactor{nrofvalidfactors,2}=factor{4,2};
                validfactor{nrofvalidfactors,3}=factor{4,3};
            end
        else
            factor3nrofgradations = 1;
        end
       
        %factor 4
        %--------------
        if nroffactors > 3 
            factor4nrofgradations = factor{5,2};
            if factor4nrofgradations>1
                nrofvalidfactors = nrofvalidfactors +1;
                validfactor{nrofvalidfactors,1}=factor{5,1};
                validfactor{nrofvalidfactors,2}=factor{5,2};
                validfactor{nrofvalidfactors,3}=factor{5,3};
            end
        else
            factor4nrofgradations=1;
        end
        
                      
        if nrofvalidfactors>1
            results = cell(1,2);
            results{2,1}='Two-way Interactions';
            results{2,2}= [];
        end
        if nrofvalidfactors>2
            results{3,1}='Three-way Interactions';
            results{3,2}= [];
        end
        if nrofvalidfactors>3
            results{4,1}='Four-way Interactions';
            results{4,2}= [];
        end
        if nrofvalidfactors>4
            results{5,1}='Five-way Interactions';
            results{5,2}= [];
        end
        if nrofvalidfactors>5
            results{6,1}='Six-way Interactions';
            results{6,2}= [];
        end      
               
        targeteffect = str2num(strrep(factor{1,5},'X',' '));
        
        
        
        for ChanInd=1:NChan
            text1=['Channel #    ',int2str(ChanInd),' of ',int2str(NChan)];
            set(chantext,'String',text1);
            pause(0.01);
            for PointInd = 1: NPoints
                
                
                anovadata = TotDataMat(ChanInd,PointInd,:);
                anovadata = reshape(squeeze(anovadata),subjects,customgradations);
				if size(anovadata,2)~=nrofcells
                    errordlg('Number of cells does not match the product of factor gradations! Quitting...','Factorial design:');
                    return
				end
				%totmean,QS & df
				%--------------------------
				TotMean = mean(mean(anovadata));				
				%subjectmean,QS & df (between)
				%--------------------------
				SubjectMean = mean(anovadata,2);
				SubjectQS=0;
                for k=1:size(anovadata,1)
                    SubjectQS = SubjectQS + size(anovadata,2)*(SubjectMean(k)-TotMean)^2;
                end
				SubjectsDf = subjects-1; 
				%cellmean,QS & df
				%--------------------------
				CellMean = mean(anovadata,1); 
                %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                %%%%                  Haupteffekte                    %%%%
                %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                results{1,1}='main effects';
                resultstmp = results;
                resultstmp{1,2}=calc_rm_anova(anovadata,validfactor,1);
                %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                %%%%                  Interaktionen                   %%%%
                %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                for r=2:nrofvalidfactors
                    tmpdata=calc_rm_anova(anovadata,validfactor,r);
                    if isempty(tmpdata)
                        resultstmp=[];
                        return
                    else
                        resultstmp{r,2} = tmpdata;
                    end
                end
                results=resultstmp;    
                %main-effects
                for r=1:nrofvalidfactors
                    %Error-SS
                    results{1,2}{r,5} = results{1,2}{r,5}-SubjectQS;
                    %Subtract Main-Effect from Error-SS
                    results{1,2}{r,5} = results{1,2}{r,5}-results{1,2}{r,2};
                    %Error-MS
                    results{1,2}{r,7} = results{1,2}{r,5} / results{1,2}{r,6};
                    %F-Value
                    results{1,2}{r,8}=  results{1,2}{r,4} / results{1,2}{r,7};
                    %p-Value
                    results{1,2}{r,9}=  fcdf(results{1,2}{r,8},results{1,2}{r,3},results{1,2}{r,6}); 
                    %pointwise
                    if length(targeteffect)==1 
                        if r==targeteffect
                            PMat(ChanInd,PointInd)=results{1,2}{r,9};
                            FMat(ChanInd,PointInd)=results{1,2}{r,8};
                        end
                    end 
                end
                
                %interactions
                for r=2:nrofvalidfactors %counts up interaction-type
                    for s=1:size(results{r,2},1) %counts up combinations of factors for r-way-interaction
                        %Subtract main-effects-SS
                        for e=1:size(results{r,2}{s,1},2)
                            results{r,2}{s,2}=results{r,2}{s,2}-results{1,2}{results{r,2}{s,1}(e),2}; %fprintf(['Subtracting ',strrep(num2str(results{r,2}{s,1}(e)),'  ','-'),'-main-effect-error-QS from ',strrep(num2str(results{r,2}{s,1}),'  ','-'),'-interaction-error-QS:\n']);
                            results{r,2}{s,5}=results{r,2}{s,5}-results{1,2}{results{r,2}{s,1}(e),5}; results{r,2}{s,5}=results{r,2}{s,5}-results{1,2}{results{r,2}{s,1}(e),2};
                        end
                        %subtract lower order interaction-SS
                        for f=r-1:-1:2 %f counts down the interaction-types
                            for q=1:size(results{f,2},1) %q counts up combinations of factors for f-way-interaction
                                matchzaehler = 0;
                                %find relevant lower order interactions
                                for v=1:size(results{f,2}{q,1},2) %v counts across numbers designating interaction type
                                    if ~isempty(find(results{f,2}{q,1}(v)==results{r,2}{s,1}))
                                        matchzaehler = matchzaehler+1;
                                    end
                                end
                                if matchzaehler == f
                                    results{r,2}{s,2}=results{r,2}{s,2}-results{f,2}{q,2};
                                    results{r,2}{s,5}=results{r,2}{s,5}-results{f,2}{q,2};
                                   results{r,2}{s,5}=results{r,2}{s,5}-results{f,2}{q,5};
                                end
                            end
                        end
                        results{r,2}{s,5}=results{r,2}{s,5}-results{r,2}{s,2};
                        results{r,2}{s,5}=results{r,2}{s,5}-SubjectQS;
                        results{r,2}{s,4} = results{r,2}{s,2} / results{r,2}{s,3};
                        results{r,2}{s,7} = results{r,2}{s,5} / results{r,2}{s,6};
                        results{r,2}{s,8}=  results{r,2}{s,4} / results{r,2}{s,7};
                        results{r,2}{s,9}=  fcdf(results{r,2}{s,8},results{r,2}{s,3},results{r,2}{s,6}); 
                        if sum(targeteffect==results{r,2}{s,1})==length(targeteffect)
                            PMat(ChanInd,PointInd)=results{r,2}{s,9};
                            FMat(ChanInd,PointInd)=results{r,2}{s,8};
                        end
                    end
                end
            end
        end
        
        close(findobj('tag','infdlg'));
        hList=get(hPlot2dMenuFig,'Userdata');
	    NListHdr=get(hList(51),'Userdata');
	    ActFileNo=get(hList(1),'Userdata');
        TargetSetNumber=ActFileNo;
        set(hList(NListHdr+(TargetSetNumber-1).*50+1),'Userdata',PMat);
		set(hList(NListHdr+(TargetSetNumber-1).*50+24),'Userdata',PMat);
        set(hList(NListHdr+(TargetSetNumber-1).*50+36),'Userdata',PMat);
        Plot2d('PlotData');
        Plot2d('AdjustAmp');
        
    end
    
%catch
%end
return