function [results]= RmAnova(factor,keepolddata,pointwisestatus,outpath)

%  '[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 
%          factor{2,1}= the target factor string (or 'no target') 
%          factor{2,2}= the number of between factors
%          factor{2,3}= between factor subject vector
%   
%  subsequent rows can contain custom repeated measures factors 
%  with the name of the factor in the first column...
%
%          factor{3,1}='valence';
%
%  the number of gradations in the second column...
%
%          factor{3,2}=3;
%
%  and the names of the gradations in the third column as a nested
%  cell...
%
%          factor{3,3}{1}='pleasant';
%          factor{3,3}{2}='unpleasant';
%          factor{3,3}{3}='neutral;
%
%   a between factor definition has to be appended last.
%
%          factor{4,1}='attend';
%          factor{4,2}='2';
%          factor{4,3}{1}='attend';
%          factor{4,3}{2}='nonattend';
%
%  'results' is a cell array containing F-Values...
%
%   See also CALCRMANOVA, ANOVATOAVGFILES.

%   This software is protected by german copyright and international treaties.             
%   Copyright 2004 Markus Junghöfer, Peter Peyk, Andreas Keil, Olaf Hauk,                  
%   Thomas Gruber & Andrea de Cesarei.  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.      

if nargin<4;outpath = [];end

printSSMSstatus = 0;
PrintSubtractionStatus = 0;
faststatus = 1;

 
global hPlot3dMenuFig hPlot2dMenuFig 
validbetweenfactor = [];
betweensubjectcell = [];
TotBetweenQSf = 0;
CellGroupSum = [];
betweenfactorstructure = [];
nrofbetweenfactors = 0;

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('emegs3d.m');
			plot2dlibfilepath(findstr(plot2dlibfilepath,'emegs3d.m'):findstr(plot2dlibfilepath,'emegs3d.m')+8)=[];
			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('emegs3d.m');
			plot2dlibfilepath(findstr(plot2dlibfilepath,'emegs3d.m'):findstr(plot2dlibfilepath,'emegs3d.m')+8)=[];
			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};
             if isempty(factor{end,1}) | strcmp(factor{end,1},'')
                nroffactors = nroffactors -1;
            end
			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};
            if isempty(factor{end,1}) | strcmp(factor{end,1},'')
                nroffactors = nroffactors -1;
            end
			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;
		
                
        validfactor = cell(1);
        nrofvalidfactors = 0;
        validbetweenfactors = cell(1);
        nrofvalidbetweenfactors = 0;
        
		%cellmean,QS & df
		%--------------------------
        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
        if ~isempty(validfactor) & ~isempty(validfactor{1})
			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');
        end
	
        
        nrofsubjects = size(anovadata,1);
		nroffactors = nrofvalidfactors;
		if ~isempty(validbetweenfactor)
            nrofbetweenfactors = size(validbetweenfactor,1);
		end
	
       
        
		%totmean,QS & df
		%--------------------------
        TotSum = sum(anovadata(:));
        TotSumSquare = TotSum.^2 / (size(anovadata,1)*size(anovadata,2));
      
        %AllQSf
        %-----------------
        AllQSf = sum(sum(anovadata.^2));
		AllSquareSum = AllQSf;
        
		%analyze factor structure
		%------------------------------
		totcells = 1;
        if ~isempty(validfactor) & ~isempty(validfactor{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
        else
            factorstructure = [];
        end
         
		%check between factor structure and subject in groups
		%--------------------------------------------------
        GroupSum = [];
        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);
			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
                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;
            GroupSum = sum(CellGroupSum,2);
        else
            betweenfactorstructure = [];
        end
	
        
        %subjectmean,QS & df (between)
		%--------------------------
		SubjectSum = sum(anovadata,2);
        if size(anovadata,1)>1
			SubjectsDf = subjects-1;
        else
            uiwait(errordlg('Cannot calculate repeated measures ANOVA with less than 2 subjects!','Error:'));
            return
        end
        SubjectSumSquare = sum((SubjectSum.^2),1)/size(anovadata,2);
        SubjectsQSf = SubjectSumSquare-  TotSumSquare;
        
        
        clc;
        if PrintSubtractionStatus
            fprintf(1,['Repeated-measures ANOVA:',char(10)]);
            fprintf(1,['TotSum = ',num2str(TotSum,'%5.5f'),char(10)]);
            fprintf(1,['TotSumSquare = ',num2str(TotSumSquare,'%5.5f'),char(10)]);
            fprintf(1,['SubjectSumSquare = ',num2str(SubjectSumSquare,'%5.5f'),char(10)]);
            fprintf(1,['SubjectsQSf = ',num2str(SubjectsQSf,'%5.5f'),char(10)]);
            fprintf(1,['AllSquareSum = ',num2str(AllSquareSum,'%5.5f'),char(10)]);
            fprintf(1,'\n\n');
        end
        
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        %%%%                  Haupteffekte                    %%%%
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        
        
        results{1,1}='main effects';
        resultstmp = results;
        pointwisestatus = 0;
        resultstmp{1,2}=CalcRmAnova(anovadata,validfactor,validbetweenfactor,1,pointwisestatus,...
                                      CellSum, CellGroupSum,factorstructure,...
                                      betweenfactorstructure,betweensubjectcell,nroffactors,nrofbetweenfactors,...
                                      nrofsubjects,SubjectsDf,...
                                      TotSumSquare,SubjectsQSf);
        
            
        
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        %%%%                  Interaktionen                   %%%%
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
       
        
        for r=2:totvalidfactors
            tmpdata=CalcRmAnova(anovadata,validfactor,validbetweenfactor,r,pointwisestatus,...
                                    CellSum,CellGroupSum,factorstructure,...
                                    betweenfactorstructure,betweensubjectcell,nroffactors,nrofbetweenfactors,...
                                    nrofsubjects,SubjectsDf,...
                                    TotSumSquare,SubjectsQSf);
            if isempty(tmpdata)
                resultstmp=[];
                return
            else
                resultstmp{r,2} = tmpdata;
            end
        end
        results=resultstmp;
        
        
        if PrintSubtractionStatus
            fprintf(1,['Start to subtract lower order effects from main-effect sumsquares and its error sumsquares...',char(10)]);
            fprintf(1,['=============================================================================================',char(10)]);
            fprintf(1,'\n\n');
        end

        %========================   
        %========================  
        %========================  
        %reines between design
        %========================
        %========================   
        %========================  
        
        if isempty(factorstructure) 
              
            %main-between-effect
            for r=1                
                if PrintSubtractionStatus
                    fprintf(1,[char(10)]);
                    fprintf(1,['Actual Effect (between):  ',validbetweenfactor{r,1},'(',num2str(r),')',char(10)]);
                    fprintf(1,['-------------------------------------------',char(10)]);
                end
                
                if PrintSubtractionStatus
                    %Main-Effect_MS 
                    fprintf(1,['EffectSS = ', num2str(results{1,2}{r,2}),char(10)]);
                    fprintf(1,['ErrorSS = ', num2str(results{1,2}{r,5}),char(10)]);
                end
                
                %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};
                
                %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   
        
        %========================   
        %========================  
        %========================  
        %reines within desing
        %========================   
        %========================  
        %========================  
        elseif isempty(betweenfactorstructure) 
            
            %main-within-effects
            for r=1:nrofvalidfactors
                
                if PrintSubtractionStatus
                    fprintf(1,[char(10)]);
                    fprintf(1,['Actual Effect (within):  ',validfactor{r,1},'(',num2str(r),')',char(10)]);
                    fprintf(1,['-------------------------------------------',char(10)]);
                end
                
                if PrintSubtractionStatus
                    %Main-Effect_MS 
                    fprintf(1,['EffectSS = ', num2str(results{1,2}{r,2}),char(10)]);
                    fprintf(1,['ErrorSS = ', num2str(results{1,2}{r,5}),char(10)]);
                end
                
                %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;
                if PrintSubtractionStatus
                    fprintf(1,[' - SubjectsQSf (',num2str(SubjectsQSf),') = ', num2str(results{1,2}{r,5}),char(10)]);
                end
                
                %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   
        
        
            %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
                       
                   if PrintSubtractionStatus
                        effectnum = results{r,2}{s,1};
                        effectstring = [];
                        effectstring = [validfactor{results{r,2}{s,1}(1),1}];
                        for o=2:length(effectnum)
                            effectstring = [effectstring,' X ',validfactor{results{r,2}{s,1}(o),1}];
                        end 
                        for j=1:length(effectnum)
                            if length(find(effectnum==j))>1
                                disp('there is a problem');
                            end
                        end
                        fprintf(1,[char(10)]);
                        fprintf(1,['Actual Effect (within):  ',effectstring,'  (',strrep(num2str(effectnum),'  ',' X '),')',char(10)]);
                        fprintf(1,['-------------------------------------------',char(10)]);
                    end
                        
                    
                
                    %Subtract main-effects-SS
                    for e=1:size(results{r,2}{s,1},2)
                        
                        %Main-Effect_MS 
                        if PrintSubtractionStatus
                            fprintf(1,['EffectSS = ', num2str(results{r,2}{s,2}),char(10)]);
                        end
                        
                        %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};
                        if PrintSubtractionStatus
                            fprintf(1,['- ',strrep(num2str(results{1,2}{results{r,2}{s,1}(e),1}),'  ',' X '),' (',num2str(results{1,2}{results{r,2}{s,1}(e),2}),') = ', num2str( results{r,2}{s,2}),char(10)]);
                        end
                        
                        if PrintSubtractionStatus
                            fprintf(1,['ErrorSS = ', num2str(results{r,2}{s,5}),char(10)]);
                        end
                        %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};
                        
                        if PrintSubtractionStatus
                            fprintf(1,['- ',strrep(num2str(results{1,2}{results{r,2}{s,1}(e),1}),'  ',' X '),' - Error (',num2str(results{1,2}{results{r,2}{s,1}(e),5}),') = ', num2str( results{r,2}{s,5}),char(10)]);
                        end
                        
                        %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};
                        
                        if PrintSubtractionStatus
                            fprintf(1,['- ',strrep(num2str(results{1,2}{results{r,2}{s,1}(e),1}),'  ',' X '),'  (',num2str(results{1,2}{results{r,2}{s,1}(e),2}),') = ', num2str(results{r,2}{s,5}),char(10)]);
                        end
                    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
                                
                                
                                if PrintSubtractionStatus
                                    fprintf(1,['EffectSS = ', num2str(results{r,2}{s,2}),char(10)]);
                                end
                                %subtract interaction-SS from condition-QS
                                results{r,2}{s,2}=results{r,2}{s,2}-results{f,2}{q,2};
                                
                                if PrintSubtractionStatus
                                    fprintf(1,['- ',strrep(num2str(results{f,2}{q,1}),'  ',' X '),' (',num2str(results{f,2}{q,2}),') = ', num2str(  results{r,2}{s,2}),char(10)]);
                                end
                                
                                %QS =  results{r,2}{s,2}
                                
                                if PrintSubtractionStatus
                                    fprintf(1,['ErrorSS = ', num2str(results{r,2}{s,5}),char(10)]);
                                end
                                
                                %subtract interaction-SS from error-QS
                                results{r,2}{s,5}=results{r,2}{s,5}-results{f,2}{q,2};
                                if PrintSubtractionStatus
                                    fprintf(1,['- ',strrep(num2str(results{f,2}{q,1}),'  ',' X '),' (',num2str(results{f,2}{q,2}),') = ', num2str(  results{r,2}{s,5}),char(10)]);
                                end
                                %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};
                                if PrintSubtractionStatus
                                    fprintf(1,['- ',strrep(num2str(results{f,2}{q,1}),'  ',' X '),' - Error (',num2str(results{f,2}{q,5}),') = ', num2str(  results{r,2}{s,5}),char(10)]);
                                end
                                %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};
                    if PrintSubtractionStatus
                        fprintf(1,['- ',strrep(num2str(results{r,2}{s,1}),'  ',' X '),'  (',num2str(results{r,2}{s,2}),') = ', num2str( results{r,2}{s,5}),char(10)]);
                    end  %QS =  results{r,2}{s,5}
                    
                    %subtract subject-QS from Error-SS 
                    results{r,2}{s,5}=results{r,2}{s,5}-SubjectsQSf;
                    if PrintSubtractionStatus
                        fprintf(1,['- SubjectsQS (',num2str(SubjectsQSf),') = ', num2str(results{r,2}{s,5}),char(10)]);
                    end 
                    %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});
                     
                end
            end
               
            
        %========================   
        %========================  
        %========================  
        %gemischtes design
        %========================   
        %========================  
        %========================  
        else
           %main-within-effects
            for r=1:nrofvalidfactors
                
                if PrintSubtractionStatus
                    fprintf(1,[char(10)]);
                    fprintf(1,['Actual Effect (within):  ',validfactor{r,1},'(',num2str(r),')',char(10)]);
                    fprintf(1,['-------------------------------------------',char(10)]);
                end
                if PrintSubtractionStatus
                    fprintf(1,['EffectSS = ', num2str(results{1,2}{r,2}),char(10)]);
                end
                %Main-Effect_MS
                results{1,2}{r,4} = results{1,2}{r,2}/results{1,2}{r,3};
                %Error-SS 
                if PrintSubtractionStatus
                    fprintf(1,['ErrorSS = ', num2str(results{1,2}{r,5}),char(10)]);
                end
                %Subtract SubjectQSf from Error-SS
                results{1,2}{r,5} = results{1,2}{r,5}-SubjectsQSf;
                if PrintSubtractionStatus
                    fprintf(1,['- SubjectQSf (',num2str(SubjectsQSf),') = ', num2str(results{1,2}{r,5}),char(10)]);
                end
                %Subtract Interaction with between factor from Error-SS!
                %(this is specific for mixed between-within-designs)
                effect = results{1,2}{r,1};
                betweeneffect=nrofvalidfactors + 1;
                effect = [effect betweeneffect];
                for t=1:size(results{2,2},1)
                    if sum(results{2,2}{t,1}==effect)==length(effect)
                        BIAQSf = results{2,2}{t,2};
                        %this interaction is not yet corrected, so subtract
                        %its lower order components
                        for ct = 1:length(results{2,2}{t,1})
                            BIAQSf  = BIAQSf - results{1,2}{results{2,2}{t,1}(ct),2};
                        end
                    end
                end
                results{1,2}{r,5} = results{1,2}{r,5}-BIAQSf;  
                if PrintSubtractionStatus
                    fprintf(1,['- ',strrep(num2str(effect),'  ',' X '),' (',num2str(BIAQSf),') = ', num2str(results{1,2}{r,5}),char(10)]);
                end
                %Subtract Main-Effect-QSf from Error-SS
                results{1,2}{r,5} = results{1,2}{r,5}-results{1,2}{r,2};
                if PrintSubtractionStatus
                    fprintf(1,['- ',strrep(num2str(results{1,2}{r,1}),'  ',' X '),' (',num2str(results{1,2}{r,2}),') = ', num2str( results{1,2}{r,5}),char(10)]);
                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;
                if PrintSubtractionStatus
                    fprintf(1,[char(10)]);
                    fprintf(1,['Actual Effect (between):  ',validbetweenfactor{r-nrofvalidfactors,1},'(',num2str(r),')',char(10)]);
                    fprintf(1,['-------------------------------------------',char(10)]);
                end
                if PrintSubtractionStatus
                    fprintf(1,['EffectSS = ', num2str(results{1,2}{r,2}),char(10)]);
                    fprintf(1,['ErrorSS = ', num2str(results{1,2}{r,5}),char(10)]);
                end
                %Subtract Main-Effect from Error-SS
                results{1,2}{r,5} = results{1,2}{r,5}-results{1,2}{r,2};
                if PrintSubtractionStatus
                    fprintf(1,['- ',strrep(num2str(results{1,2}{r,1}),'  ',' X '),' (',num2str(results{1,2}{r,2}),') = ', num2str( results{1,2}{r,5}),char(10)]);
                end
               %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
            
            if PrintSubtractionStatus
                fprintf(1,['\n\n']);
                fprintf(1,['Start to subtract lower order effects from interaction sumsquares...',char(10)]);
                fprintf(1,['====================================================================',char(10)]);
                fprintf(1,['\n\n']);
            end
                
            
            
            
            %interactions
            for r=2:totvalidfactors %counts up interaction-type
                for s=size(results{r,2},1):-1:1 %counts down combinations of factors for r-way-interaction
                                                %it is importan to count downwards, because then,between effects are
                                                %corrected first, who in turn are necessary to correct pure within
                                                %effects.
                    %reiner within
                    %======================
                    if isempty(find(results{r,2}{s,1}>nrofvalidfactors))
                        
                        if PrintSubtractionStatus
                            effectnum = results{r,2}{s,1};
                            effectstring = [];
                            effectstring = [validfactor{results{r,2}{s,1}(1),1}];
                            for o=2:length(effectnum)
                                if effectnum(o)>nrofvalidfactors
                                    effectstring = [effectstring,' X ',validbetweenfactor{results{r,2}{s,1}(o)-nrofvalidfactors,1}];
                                else
                                    effectstring = [effectstring,' X ',validfactor{results{r,2}{s,1}(o),1}];
                                end
                            end 
                            for j=1:length(effectnum)
                                if length(find(effectnum==j))>1
                                    disp('there is a problem');
                                end
                            end
                            fprintf(1,[char(10)]);
                            fprintf(1,['Actual Effect (within):  ',effectstring,'  (',strrep(num2str(effectnum),'  ',' X '),')',char(10)]);
                            fprintf(1,['-------------------------------------------',char(10)]);
                        end
                
                        %EffectSS
                        %===============================
                        %===============================
                        if PrintSubtractionStatus
                            fprintf(1,[char(10),'EffectSS:  ',num2str(results{r,2}{s,2}),char(10)]);
                        end
                        
                        %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};
                            if PrintSubtractionStatus
                                fprintf(1,['- ',strrep(num2str(results{r,2}{s,1}(e)),'  ',' X '),' (',num2str(results{1,2}{results{r,2}{s,1}(e),2}),') = ', num2str(results{r,2}{s,2}),char(10)]);
                            end        
                        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};
                                    if PrintSubtractionStatus
                                        fprintf(1,['- ',strrep(num2str(results{f,2}{q,1}),'  ',' X '),' (',num2str(results{f,2}{q,2}),') = ', num2str(results{r,2}{s,2}),char(10)]);
                                    end
                                    %and its interaction with the between
                                end
                            end
                        end
                        
                    %mit between
                    %======================
                    else
                        
                        if PrintSubtractionStatus
                            effectnum = results{r,2}{s,1};
                            effectstring = [];
                            if results{r,2}{s,1}(1)>nrofvalidfactors
                                effectstring = [validbetweenfactor{1,1}];
                            else
                                effectstring = [validfactor{results{r,2}{s,1}(1),1}];
                            end
                            for r=2:length(effectnum)
                                if effectnum(r)>nrofvalidfactors
                                    effectstring = [effectstring,' X ',validbetweenfactor{1,1}];
                                else
                                    effectstring = [effectstring,' X ',validfactor{effectnum(r),1}];
                                end
                            end
                            fprintf(1,[char(10)]);
                            fprintf(1,['Actual Effect (mixed):  ',effectstring,'  (',strrep(num2str(effectnum),'  ',' X '),')',char(10)]);
                            fprintf(1,['-------------------------------------------',char(10)]);
                        end
                        
                        
                       %EffectSS
                        %==========
                        if PrintSubtractionStatus
                            fprintf(1,[char(10),'EffectSS:  ',num2str(results{r,2}{s,2}),char(10)]);
                        end
                        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}; 
                            if PrintSubtractionStatus
                                fprintf(1,['- ',strrep(num2str(results{1,2}{results{r,2}{s,1}(e),1}),'  ',' X '),' (',num2str(results{1,2}{results{r,2}{s,1}(e),2}),') = ', num2str(results{r,2}{s,2}),char(10)]);
                            end
                        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};
                                    if PrintSubtractionStatus
                                        fprintf(1,['- ',strrep(num2str(results{f,2}{q,1}),'  ',' X '),' (',num2str(results{f,2}{q,2}),') = ', num2str( results{r,2}{s,2}),char(10)]);
                                    end
                                end
                            end
                        end
                    end
                end
            end
            
             if PrintSubtractionStatus
                fprintf(1,['\n\n']);
                fprintf(1,['Start to subtract lower order effects from error sumsquares...',char(10)]);
                fprintf(1,['====================================================================',char(10)]);
                fprintf(1,['\n\n']);
            end
            %ErrorSS
            %===============================
            %===============================
            %interactions
            for r=2:totvalidfactors %counts up interaction-type
                for s=size(results{r,2},1):-1:1 %counts down combinations of factors for r-way-interaction
                                                %it is importan to count downwards, because then,between effects are
                                                %corrected first, who in turn are necessary to correct pure within
                                                %effects.
        
                                                
                    %reiner within
                    %======================
                    if isempty(find(results{r,2}{s,1}>nrofvalidfactors))
                        
                         if PrintSubtractionStatus
                            effectnum = results{r,2}{s,1};
                            effectstring = [];
                            effectstring = [validfactor{results{r,2}{s,1}(1),1}];
                            for o=2:length(effectnum)
                                if effectnum(o)>nrofvalidfactors
                                    effectstring = [effectstring,' X ',validbetweenfactor{results{r,2}{s,1}(o)-nrofvalidfactors,1}];
                                else
                                    effectstring = [effectstring,' X ',validfactor{results{r,2}{s,1}(o),1}];
                                end
                            end 
                            for j=1:length(effectnum)
                                if length(find(effectnum==j))>1
                                    disp('there is a problem');
                                end
                            end
                            fprintf(1,[char(10)]);
                            fprintf(1,['Actual Effect (within):  ',effectstring,'  (',strrep(num2str(effectnum),'  ',' X '),')',char(10)]);
                            fprintf(1,['-------------------------------------------',char(10)]);
                        end
                        
                        
                        if PrintSubtractionStatus
                            fprintf(1,['ErrorSS:  ',num2str(results{r,2}{s,5}),char(10)]);
                        end
                       %Subtract main-effects-SS
                        for e=1:size(results{r,2}{s,1},2)
                            
                            %for within factors subtract error QS
                            if e<=nrofvalidfactors
                                results{r,2}{s,5}=results{r,2}{s,5}-results{1,2}{results{r,2}{s,1}(e),5};
                                betweeneffect=nrofvalidfactors + 1;
                                
                                effect = [results{r,2}{s,1}(e), betweeneffect];
                                if PrintSubtractionStatus
                                    fprintf(1,['looking for effect X between interaction:',num2str(effect),char(10)]);
                                end
                                for t=1:size(results{2,2},1)
                                    if sum(results{2,2}{t,1}==effect)==length(effect)
                                        BIAQSf = results{2,2}{t,2};
                                        results{r,2}{s,5} = results{r,2}{s,5} - BIAQSf;
                                        if PrintSubtractionStatus
                                            fprintf(1,['- ',strrep(num2str(results{2,2}{t,1}),'  ',' X '),' (',num2str(results{2,2}{t,2}),') = ', num2str(results{r,2}{s,5}),char(10)]);
                                        end
                                    end
                                end
                            end
                            
                            %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};
                            if PrintSubtractionStatus
                                fprintf(1,['- ',strrep(num2str(results{1,2}{results{r,2}{s,1}(e),1}),'  ',' X '),' (',num2str(results{1,2}{results{r,2}{s,1}(e),2}),') = ', num2str(results{r,2}{s,5}),char(10)]);
                            end
                        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
                                    if PrintSubtractionStatus
                                        fprintf(1,[strrep(num2str(results{r,2}{s,1}),'  ',' X '),' contains ',strrep(num2str(results{f,2}{q,1}),'  ',' X '),'....',char(10)]);
                                    end
                                    betweeneffect=nrofvalidfactors + 1;
                                    %only for effects without a between
                                    %component, also subtract the
                                    %corresponding between interaction
                                    if isempty(find(results{f,2}{q,1}==betweeneffect))
                                        effect = [results{f,2}{q,1}, betweeneffect];
                                        order = length(effect);
                                        for k=1:size(results{order,2},1)
                                            matchzaehler = 0;
                                            for g=1:order
                                                if ~isempty(find(effect(g)==results{order,2}{k,1}))
                                                    matchzaehler = matchzaehler+1;
                                                end
                                            end
                                            if matchzaehler==length(effect)
                                                %subtract X between interaction SS from error-QS
                                                results{r,2}{s,5}=results{r,2}{s,5}-results{order,2}{k,2};
                                                if PrintSubtractionStatus
                                                    fprintf(1,['- ',strrep(num2str(results{order,2}{k,1}),'  ',' X '),' (',num2str(results{order,2}{k,2}),') = ', num2str(results{r,2}{s,5}),char(10)]);
                                                end
                                            end
                                        end
                                    end
                                    %subtract interaction-SS from error-QS
                                    results{r,2}{s,5}=results{r,2}{s,5}-results{f,2}{q,2};
                                    if PrintSubtractionStatus
                                        fprintf(1,['- ',strrep(num2str(results{f,2}{q,1}),'  ',' X '),' (',num2str(results{f,2}{q,2}),') = ', num2str(results{r,2}{s,5}),char(10)]);
                                    end
                                    
                                    %and its error-QS from error-QS
                                    results{r,2}{s,5}=results{r,2}{s,5}-results{f,2}{q,5};
                                    if PrintSubtractionStatus
                                        fprintf(1,['- ',strrep(num2str(results{f,2}{q,1}),'  ',' X '),' - Error (',num2str(results{f,2}{q,5}),') = ', num2str(results{r,2}{s,5}),char(10)]);
                                    end
                                end
                            end
                        end
                        
                        
                        %subtract interaction from error-QS 
                        results{r,2}{s,5}=results{r,2}{s,5}-results{r,2}{s,2};
                        if PrintSubtractionStatus
                            fprintf(1,['- ',strrep(num2str(results{r,2}{s,1}),'  ',' X '),' (',num2str(results{r,2}{s,2}),') = ', num2str(results{r,2}{s,5}),char(10)]);
                        end
                        %QS =  results{r,2}{s,5}
                        
                        %subtract interaction X between from error-QS 
                        betweeneffect=nrofvalidfactors + 1;
                        effect = [results{r,2}{s,1}, betweeneffect];
                        order = length(effect);
                        for k=1:size(results{order,2},1)
                            matchzaehler = 0;
                            for g=1:order
                                if ~isempty(find(effect(g)==results{order,2}{k,1}))
                                    matchzaehler = matchzaehler+1;
                                end
                            end
                            if matchzaehler==length(effect)
                                results{r,2}{s,5}=results{r,2}{s,5}-results{order,2}{k,2};
                                if PrintSubtractionStatus
                                    fprintf(1,['- ',strrep(num2str(results{order,2}{k,1}),'  ',' X '),' (',num2str(results{order,2}{k,2}),') = ', num2str(results{r,2}{s,5}),char(10)]);
                                end
                            end
                        end
                        
                        %subtract between main effect from error-QS 
                        results{r,2}{s,5}= results{r,2}{s,5} - results{1,2}{betweeneffect,2};
                        if PrintSubtractionStatus
                            fprintf(1,['- ',strrep(num2str(results{1,2}{betweeneffect,1}),'  ',' X '),' (',num2str(results{1,2}{betweeneffect,2}),') = ', num2str(results{r,2}{s,5}),char(10)]);
                         end
                        
                        %subtract subject-QS from Error-SS 
                        results{r,2}{s,5}=results{r,2}{s,5}-SubjectsQSf;
                        if PrintSubtractionStatus
                            fprintf(1,['- SubjectsQS (',num2str(SubjectsQSf),') = ', num2str(results{r,2}{s,5}),char(10)]);
                        end                   
                        %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     
                        
                         if PrintSubtractionStatus
                            effectnum = results{r,2}{s,1};
                            effectstring = [];
                            effectstring = [validfactor{results{r,2}{s,1}(1),1}];
                            for o=2:length(effectnum)
                                if effectnum(o)>nrofvalidfactors
                                    effectstring = [effectstring,' X ',validbetweenfactor{results{r,2}{s,1}(o)-nrofvalidfactors,1}];
                                else
                                    effectstring = [effectstring,' X ',validfactor{results{r,2}{s,1}(o),1}];
                                end
                            end 
                            for j=1:length(effectnum)
                                if length(find(effectnum==j))>1
                                    disp('there is a problem');
                                end
                            end
                            fprintf(1,[char(10)]);
                            fprintf(1,['Actual Effect (within):  ',effectstring,'  (',strrep(num2str(effectnum),'  ',' X '),')',char(10)]);
                            fprintf(1,['-------------------------------------------',char(10)]);
                        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))=[];
                        if PrintSubtractionStatus
                            fprintf(1,['Taking ErrorSS from corresponding non-between effect (assuming fixed effects):',char(10)]);
                        end
                        for t=1:size(results{order,2},1)
                            if sum(results{order,2}{t,1}==effect)==length(effect)
                                foundeffect = results{order,2}{t,1};
                                ErrorSS = 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
                        if PrintSubtractionStatus
                            fprintf(1,[strrep(num2str(foundeffect),'  ',' X '),' - ErrorSS :',num2str(ErrorSS),char(10)]);
                        end
                        results{r,2}{s,5}=ErrorSS;
                        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;
        
              
        
        %SubjectsQS
        outstring{rowzaehler,1} = ['Subjects: '];
        rowzaehler = rowzaehler+1;
        outstring{rowzaehler,1} = '----------------------------';
        rowzaehler = rowzaehler+1;
        outstring{rowzaehler,1} = ['SubjectsQS: ',num2str(SubjectsQSf,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),'; F(',num2str(results{1,2}{v,3}),',',num2str(results{1,2}{v,6}),...
                  ')=',num2str(results{1,2}{v,8},formatstring),'; p = ',num2str(results{1,2}{v,9},formatstring)];
              else
                  outstring{rowzaehler,1}=[validfactor{v,1},': F(',num2str(results{1,2}{v,3}),',',num2str(results{1,2}{v,6}),...
                  ')=',num2str(results{1,2}{v,8},formatstring),';  p = ',num2str(results{1,2}{v,9},formatstring)];
              end
             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),'; F(',num2str(results{1,2}{v,3}),',',num2str(results{1,2}{v,6}),...
                 ')=',num2str(results{1,2}{v,8},formatstring),': p = ',num2str(results{1,2}{v,9},formatstring),';'];
            else
                outstring{rowzaehler,1}=[validbetweenfactor{v-nrofvalidfactors,1},': F(',num2str(results{1,2}{v,3}),',',num2str(results{1,2}{v,6}),...
                 ')=',num2str(results{1,2}{v,8},formatstring),': p = ',num2str(results{1,2}{v,9},formatstring),';'];
            end
             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
                if printSSMSstatus
                     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),'; F(',num2str(results{w,2}{v,3}),',',num2str(results{w,2}{v,6}),...
                     ')=',num2str(results{w,2}{v,8},formatstring),'; p = ',num2str(results{w,2}{v,9},formatstring),'; '];
                else
                     outstring{rowzaehler,1}=[outstring{rowzaehler,1},': F(',num2str(results{w,2}{v,3}),',',num2str(results{w,2}{v,6}),...
                     ')=',num2str(results{w,2}{v,8},formatstring),'; p = ',num2str(results{w,2}{v,9},formatstring),'; '];
                end
                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
        
        DefPath=SetDefPath('r');
        if ~isempty(DefPath);
		    [DefFile,DefPath]=SepFilePath(DefPath);
		    if strcmp(DefPath(end),filesep)
			    DefPath=DefPath(1:length(DefPath)-1);
		    end
		    eval(['cd ',DefPath]);
	    end	
        if isempty(outpath)
            [nouse,outpath] = uiputfile(pwd,'Where do you wish to save the results?');
        else
            if exist(outpath)~=7
                [nouse,outpath] = uiputfile(pwd,'Where do you wish to save the results?');
            end
        end
                
        
        hPlot2dList=get(hPlot2dMenuFig,'Userdata');
        hPlot3dList=get(hPlot3dMenuFig,'Userdata');
        ParaVec=get(hPlot3dList(62),'Userdata');
        NChan=ParaVec(16);
        NPoints=ParaVec(19);  
        FMat = zeros(NChan,NPoints);
        PMat = zeros(NChan,NPoints);
        nrofcells = customgradations;
        text1=['Sensor #    ',int2str(1),' of ',int2str(NChan)];
        text2='';
        if ~isempty(findobj('tag','infdlg'));
            close(findobj('tag','infdlg'));
        end
        okfigure=infdlg('rmANOVA progress:',text1,text2,'','');
        set(okfigure,'position',[0.4 0.4 0.20 0.15]);
        uicontrol(okfigure,'units','normalized','position',[0.1 0.7 0.8 0.2],...
        'BackgroundColor',[0.83 0.81 0.79],'style','text','string','Calculating ANOVA model for each sensor and time point ...');
        chantext = findobj('Tag','msgtext');
        pointstext = findobj('Tag','statustext');
        targeteffect = str2num(strrep( factor{2,1},'X',' '));
         
        
        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;
		 
        validfactor = cell(1);
        nrofvalidfactors = 0;
        validbetweenfactors = cell(1);
        nrofvalidbetweenfactors = 0;
        
        %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
        
        
        %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
        if ~isempty(validfactor) & ~isempty(validfactor{1})
			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('emegs3d.m');
			plot2dlibfilepath(findstr(plot2dlibfilepath,'emegs3d.m'):findstr(plot2dlibfilepath,'emegs3d.m')+8)=[];
			file= [plot2dlibfilepath,'anovautil.mat'];
			save(file,'plotstringcell');
        end
	
        
        nrofsubjects = factor{1};
		nroffactors = nrofvalidfactors;
		if ~isempty(validbetweenfactor)
            nrofbetweenfactors = size(validbetweenfactor,1);
		end
          
        %analyze factor structure
		%------------------------------
		totcells = 1;
        factorstructure = [];
        if ~isempty(validfactor) & ~isempty(validfactor{1})
			for j=1:size(validfactor,1)
                totcells = totcells * validfactor{j,2};
			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
        end
         
		%check between factor structure and subject in groups
		%--------------------------------------------------
        GroupSum = [];
        CellGroupMSum = [];
        betweenfactorstructure = [];
		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(nrofsubjects,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);
            
            for e=1:size(betweenconditionmat,1)
                for f=1:size(userdefmat,1)
                    if betweenconditionmat(e,:)==userdefmat(f,:)
                        betweensubjectcell{e} = [betweensubjectcell{e} f];
                    end
                end
            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;
		end
                
             
        
        %reshape data matrix
        %-----------------------------------
        try
            TotDataMat = reshape(TotDataMat,[NChan,NPoints,subjects,customgradations]);
        catch
            uiwait(errordlg(char('A size-error occured when transforming the exported data. Check your input for ','number of subjects,number of channelgroups etc. and their correspondance to your batchfile!')));
            return
        end
                
        % CellSum
		%--------------------------
        CellSum = sum(TotDataMat,3);
		
		%TotSumSquare
		%--------------------------
        TotSum = sum(sum(TotDataMat,4),3);
        TotSumSquare = (TotSum.^2) ./ (subjects*customgradations);
      
        %AllQSf
        %-----------------
        AllQSf = sum(sum((TotDataMat.^2),4),3);
		AllSquareSum = AllQSf;
        
        %CellGroupSum & GroupSum
        %-----------------
		if ~isempty(validbetweenfactor)
			CellGroupSum = zeros(NChan,NPoints,size(betweenconditionmat,1),customgradations);
            for e=1:size(betweenconditionmat,1)
                CellGroupSum(:,:,e,:)= sum(TotDataMat(:,:,betweensubjectcell{e},:),3);
            end
            betweenfactorstructure = betweenconditionmat;
            GroupSum = sum(CellGroupSum,4);
        end
          
        %subjectmean,QS & df (between)
		%--------------------------
		SubjectSum = sum(TotDataMat,4);
        if subjects>1
			SubjectsDf = subjects-1;
        else
            uiwait(errordlg('Cannot calculate repeated measures ANOVA with less than 2 subjects!','Error:'));
            return
        end
        SubjectSumSquare = (sum((SubjectSum.^2),3))./customgradations;
        SubjectsQSf = SubjectSumSquare -  TotSumSquare;
                
                     
                
         
        TotResults = cell(NChan,NPoints);
        
        for ChanInd=1:NChan
             
            text1=['Sensor #    ',int2str(ChanInd),' of ',int2str(NChan)];
            set(chantext,'String',text1);
            pause(0.01);
            
            for PointInd = 1: NPoints
                
                text2=['Point #    ',int2str(PointInd),' of ',int2str(NPoints)];
                set(pointstext,'String',text2);
                
                
				anovadata = squeeze(TotDataMat(ChanInd,PointInd,:,:));
                CellSumIn = squeeze(CellSum(ChanInd,PointInd,:));
		        if ~isempty(validbetweenfactor)
                    CellGroupSumIn = squeeze(CellGroupSum(ChanInd,PointInd,:,:));
                else
                    CellGroupSumIn = [];
                end
                TotSumSquareIn = squeeze(TotSumSquare(ChanInd,PointInd));
                SubjectsQSfIn = squeeze(SubjectsQSf(ChanInd,PointInd));
                
                
                
                %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                %%%%                  Haupteffekte                    %%%%
                %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                
                
                results{1,1}='main effects';
                resultstmp = results;
                pointwisestatus = 0;
                resultstmp{1,2}=CalcRmAnova(anovadata,validfactor,validbetweenfactor,1,1,...
                                              CellSumIn, CellGroupSumIn,factorstructure,...
                                              betweenfactorstructure,betweensubjectcell,nroffactors,nrofbetweenfactors,...
                                              nrofsubjects,SubjectsDf,...
                                              TotSumSquareIn,SubjectsQSfIn);
                
                %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                %%%%                  Interaktionen                   %%%%
                %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
               
                
                for r=2:totvalidfactors
                    tmpdata=CalcRmAnova(anovadata,validfactor,validbetweenfactor,r,1,...
                                            CellSumIn,CellGroupSumIn,factorstructure,...
                                            betweenfactorstructure,betweensubjectcell,nroffactors,nrofbetweenfactors,...
                                            nrofsubjects,SubjectsDf,...
                                            TotSumSquareIn,SubjectsQSfIn);
                    if isempty(tmpdata)
                        resultstmp=[];
                        return
                    else
                        resultstmp{r,2} = tmpdata;
                    end
                end
                results=resultstmp;
                
               
		
                %========================   
                %========================  
                %========================  
                %reines between design
                %========================
                %========================   
                %========================  
                
                if isempty(factorstructure) 
                      
                    %main-between-effect
                    for r=1                
                        if PrintSubtractionStatus
                            fprintf(1,[char(10)]);
                            fprintf(1,['Actual Effect (between):  ',validbetweenfactor{r,1},'(',num2str(r),')',char(10)]);
                            fprintf(1,['-------------------------------------------',char(10)]);
                        end
                        
                        if PrintSubtractionStatus
                            %Main-Effect_MS 
                            fprintf(1,['EffectSS = ', num2str(results{1,2}{r,2}),char(10)]);
                            fprintf(1,['ErrorSS = ', num2str(results{1,2}{r,5}),char(10)]);
                        end
                        
                        %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};
                        
                        %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   
                    
                %========================   
                %========================  
                %========================  
                %reines within desing
                %========================   
                %========================  
                %========================  
                elseif isempty(betweenfactorstructure) 
                    %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}-SubjectsQSfIn;
                        %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}) ;
                        if length(targeteffect)==1 
                            if r==targeteffect
                                PMat(ChanInd,PointInd)=1-results{1,2}{r,9};
                                FMat(ChanInd,PointInd)=results{1,2}{r,8};
                            end
                        end 
                    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
                            %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};
                                %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};
                                        %subtract interaction-SS from error-QS
                                        results{r,2}{s,5}=results{r,2}{s,5}-results{f,2}{q,2};
                                        %and its error-QS from error-QS
                                        results{r,2}{s,5}=results{r,2}{s,5}-results{f,2}{q,5};
                                    end
                                end
                            end
                            %subtract interaction from error-QS 
                            results{r,2}{s,5}=results{r,2}{s,5}-results{r,2}{s,2};
                            %subtract subject-QS from Error-SS 
                            results{r,2}{s,5}=results{r,2}{s,5}-SubjectsQSfIn;
                            %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});
                            if length(targeteffect)>1
                                if sum(targeteffect==results{r,2}{s,1})==length(targeteffect)
                                    PMat(ChanInd,PointInd)=1-results{r,2}{s,9};
                                    FMat(ChanInd,PointInd)=results{r,2}{s,8};
                                end
                            end
                        end
                    end
                       
                    
                %========================   
                %========================  
                %========================  
                %gemischtes design
                %========================   
                %========================  
                %========================  
                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}-SubjectsQSfIn;
                        %Subtract Interaction with between factor from Error-SS!
                        %(this is specific for mixed between-within-designs)
                        effect = results{1,2}{r,1};
                        betweeneffect=nrofvalidfactors + 1;
                        effect = [effect betweeneffect];
                        for t=1:size(results{2,2},1)
                            if sum(results{2,2}{t,1}==effect)==length(effect)
                                BIAQSf = results{2,2}{t,2};
                                %this interaction is not yet corrected, so subtract
                                %its lower order components
                                for ct = 1:length(results{2,2}{t,1})
                                    BIAQSf  = BIAQSf - results{1,2}{results{2,2}{t,1}(ct),2};
                                end
                            end
                        end
                        results{1,2}{r,5} = results{1,2}{r,5}-BIAQSf; 
                        %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}) ;
                        if length(targeteffect)==1 
                            if r==targeteffect
                                PMat(ChanInd,PointInd)=1-results{1,2}{r,9};
                                FMat(ChanInd,PointInd)=results{1,2}{r,8};
                            end
                        end 
                    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}); 
                        if length(targeteffect)==1 
                            if r==targeteffect
                                PMat(ChanInd,PointInd)=1-results{1,2}{r,9};
                                FMat(ChanInd,PointInd)=results{1,2}{r,8};
                            end
                        end 
                        
                    end
                
                    %interactions
                    for r=2:totvalidfactors %counts up interaction-type
                        for s=size(results{r,2},1):-1:1 %counts down combinations of factors for r-way-interaction
                                                        %it is importan to count downwards, because then,between effects are
                                                        %corrected first, who in turn are necessary to correct pure within
                                                        %effects.
                            %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};
                                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};
                                            if PrintSubtractionStatus
                                                fprintf(1,['- ',strrep(num2str(results{f,2}{q,1}),'  ',' X '),' (',num2str(results{f,2}{q,2}),') = ', num2str(results{r,2}{s,2}),char(10)]);
                                            end
                                            %and its interaction with the between
                                        end
                                    end
                                end
                                
                            %mit between
                            %======================
                            else
                               %EffectSS
                                %==========
                                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}; 
                                    if PrintSubtractionStatus
                                        fprintf(1,['- ',strrep(num2str(results{1,2}{results{r,2}{s,1}(e),1}),'  ',' X '),' (',num2str(results{1,2}{results{r,2}{s,1}(e),2}),') = ', num2str(results{r,2}{s,2}),char(10)]);
                                    end
                                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};
                                            if PrintSubtractionStatus
                                                fprintf(1,['- ',strrep(num2str(results{f,2}{q,1}),'  ',' X '),' (',num2str(results{f,2}{q,2}),') = ', num2str( results{r,2}{s,2}),char(10)]);
                                            end
                                        end
                                    end
                                end
                            end
                        end
                    end
                   
                    %ErrorSS
                    %===============================
                    %===============================
                    %interactions
                    for r=2:totvalidfactors %counts up interaction-type
                        for s=size(results{r,2},1):-1:1 %counts down combinations of factors for r-way-interaction
                                                        %it is importan to count downwards, because then,between effects are
                                                        %corrected first, who in turn are necessary to correct pure within
                                                        %effects. 
                            %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)
                                    %for within factors subtract error QS
                                    if e<=nrofvalidfactors
                                        results{r,2}{s,5}=results{r,2}{s,5}-results{1,2}{results{r,2}{s,1}(e),5};
                                        betweeneffect=nrofvalidfactors + 1;
                                        effect = [results{r,2}{s,1}(e), betweeneffect];
                                        for t=1:size(results{2,2},1)
                                            if sum(results{2,2}{t,1}==effect)==length(effect)
                                                BIAQSf = results{2,2}{t,2};
                                                results{r,2}{s,5} = results{r,2}{s,5} - BIAQSf;
                                                
                                            end
                                        end
                                    end
                                    
                                    %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
                                            betweeneffect=nrofvalidfactors + 1;
                                            %only for effects without a between
                                            %component, also subtract the
                                            %corresponding between interaction
                                            if isempty(find(results{f,2}{q,1}==betweeneffect))
                                                effect = [results{f,2}{q,1}, betweeneffect];
                                                order = length(effect);
                                                for k=1:size(results{order,2},1)
                                                    matchzaehler = 0;
                                                    for g=1:order
                                                        if ~isempty(find(effect(g)==results{order,2}{k,1}))
                                                            matchzaehler = matchzaehler+1;
                                                        end
                                                    end
                                                    if matchzaehler==length(effect)
                                                        %subtract X between interaction SS from error-QS
                                                        results{r,2}{s,5}=results{r,2}{s,5}-results{order,2}{k,2};
                                                        
                                                    end
                                                end
                                            end
                                            %subtract interaction-SS from error-QS
                                            results{r,2}{s,5}=results{r,2}{s,5}-results{f,2}{q,2};
                                            %and its error-QS from error-QS
                                            results{r,2}{s,5}=results{r,2}{s,5}-results{f,2}{q,5};
                                        end
                                    end
                                end
                                
                                
                                %subtract interaction from error-QS 
                                results{r,2}{s,5}=results{r,2}{s,5}-results{r,2}{s,2};
                                %subtract interaction X between from error-QS 
                                betweeneffect=nrofvalidfactors + 1;
                                effect = [results{r,2}{s,1}, betweeneffect];
                                order = length(effect);
                                for k=1:size(results{order,2},1)
                                    matchzaehler = 0;
                                    for g=1:order
                                        if ~isempty(find(effect(g)==results{order,2}{k,1}))
                                            matchzaehler = matchzaehler+1;
                                        end
                                    end
                                    if matchzaehler==length(effect)
                                        results{r,2}{s,5}=results{r,2}{s,5}-results{order,2}{k,2};
                                    end
                                end
                                
                                %subtract between main effect from error-QS 
                                results{r,2}{s,5}= results{r,2}{s,5} - results{1,2}{betweeneffect,2};
                                %subtract subject-QS from Error-SS 
                                results{r,2}{s,5}=results{r,2}{s,5}-SubjectsQSfIn;              
                                %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     
                               
                                
                                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)
                                        foundeffect = results{order,2}{t,1};
                                        ErrorSS = 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}=ErrorSS;
                                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});  
                                
                                matchzaehler = 0;
                                for qwr = 1:length(targeteffect)
                                    if ~isempty(find(results{r,2}{s,1}==targeteffect(qwr)))
                                        matchzaehler = matchzaehler + 1;
                                    end
                                end
                                        
                                if matchzaehler==length(targeteffect) & length(results{r,2}{s,1})==length(targeteffect)
                                    PMat(ChanInd,PointInd)=1-results{r,2}{s,9};
                                    FMat(ChanInd,PointInd)=results{r,2}{s,8};
                                end
                            end
                        end
                    end
                end 
                TotResults{ChanInd,PointInd} = results;
            end
        end 
        
        tmppath= which('emegs3d.m');
		tmppath(findstr(tmppath,'emegs3d.m'):findstr(tmppath,'emegs3d.m')+8)=[];
		filename= 'RMANOVA.mat';
        file = [tmppath filename];
        save(file,'TotResults','factor','validfactor','validbetweenfactor');
        AnovaToAvgFiles(factor,validfactor,validbetweenfactor,TotResults,outpath);
        close(findobj('tag','infdlg'));
        ok
        
    end
    
%catch
%end
return