function anovadraw(action,contmat)
%   This software is protected by german copyright and international treaties.             
%   Copyright 2004 Markus Junghöfer & Peter Peyk. All Rights Reserved.                     
%                                                                                          
%   THIS SOFTWARE AND DOCUMENTATION IS PROVIDED "AS IS," AND COPYRIGHT HOLDERS MAKE        
%   NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO,    
%   WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE    
%   OF THE SOFTWARE OR DOCUMENTATION WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS,
%   TRADEMARKS OR OTHER RIGHTS. COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT,       
%   INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE SOFTWARE      
%   OR DOCUMENTATION.                                                                      
if nargin<2; contmat = [];end
if nargin<1; action = 'plot'; end
global hPlot3dMenuFig 


%get data
%-------------
hPlot3dList=get(hPlot3dMenuFig,'Userdata');
if ~isempty(hPlot3dList) 
    anovadata = get(hPlot3dList(133),'userdata');
    factor = get(findobj('tag','hfactor'),'userdata');
    results = get(findobj('tag','hresults'),'userdata');
elseif ~isempty(findobj('tag','hanovadata'))
    anovadata = get(findobj('tag','hanovadata'),'userdata');
    factor = get(findobj('tag','hfactor'),'userdata');
    results = get(findobj('tag','hresults'),'userdata');
else
    uiwait(errordlg('Could not retrieve current anovadata!','Critical error:'));
end
uigettextfigure = findobj('tag','uigettextfigure');
curplotmodel = get(uigettextfigure,'userdata');

if ~isempty(find(curplotmodel))
	%analyze factor structure
	%------------------------------
	nroffactors = size(factor,1);
	totcells = 1;
	for j=1:size(factor,1)
        totcells = totcells * factor{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 = factor{factorzaehler,2};
        if round(totcells/nrofgradations)~=totcells/nrofgradations
            uiwait(errordlg(['Number of cells cannot be divided in n-gradations for factor ',factor{factorzaehler,1},'!'],'Error:'));
        end
        %step size
        step = 1;
        for bottomzaehler = factorzaehler+1:nroffactors
            step = step * factor{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
	%adjust factorstructure to order of selected effect
	%-------------------------------------------------
	factorstructure_old = factorstructure;
	nonused = 1:size(factor,1);
	for z=1:size(curplotmodel,1)
        if curplotmodel(z,1)~=0
            nonused(find(nonused == curplotmodel(z,1)))=[];
        end
	end
	nonusedzaehler = 1;
	for t=1:size(factorstructure_old)
        if t<=size(curplotmodel,1) & curplotmodel(t,1)~=0
            ordervec(t) = curplotmodel(t,1);
        else
            ordervec(t) = nonused(nonusedzaehler);
            nonusedzaehler = nonusedzaehler +1;
        end
	end
	factorstructure = factorstructure(ordervec,:);
	
    
	
    if strcmp(action,'scheffe')  | strcmp(action,'bonferroniholm')|  strcmp(action,'customcontrast')
        
        factorstructurenew = zeros(nroffactors,totcells);
		for factorzaehlernew=nroffactors:-1:1
            %check gradations
            nrofgradations = factor{factorzaehlernew,2};
            if round(totcells/nrofgradations)~=totcells/nrofgradations
                uiwait(errordlg(['Number of cells cannot be divided in n-gradations for factor ',factor{factorzaehlernew,1},'!'],'Error:'));
            end
            %step size
            step = 1;
            for bottomzaehler = factorzaehlernew+1:nroffactors
                step = step * factor{bottomzaehler,2};
            end
            %update factorstructure
            gradationsvecnew = linspace(1,nrofgradations,nrofgradations);
            gradationzaehlernew = 1;
            for columnzaehlernew=1:step:totcells-(step-1)
                factorstructurenew(factorzaehlernew,columnzaehlernew:columnzaehlernew+(step-1))=gradationsvecnew(gradationzaehlernew);
                gradationzaehlernew = gradationzaehlernew +1;
                if gradationzaehlernew > nrofgradations
                    gradationzaehlernew = 1;
                end
            end
		end
    
        curplotmodelnew = sort(curplotmodel,1);
        factorstructure_oldnew = factorstructure;
		nonusednew = 1:size(factor,1);
		for z=1:size(curplotmodelnew,1)
            if curplotmodelnew(z,1)~=0
                nonusednew(find(nonusednew == curplotmodelnew(z,1)))=[];
            end
		end
		nonusedzaehlernew = 1;
		for t=1:size(factorstructure_oldnew)
            if t<=size(curplotmodelnew,1) & curplotmodelnew(t,1)~=0
                ordervecnew(t) = curplotmodelnew(t,1);
            else
                ordervecnew(t) = nonusednew(nonusedzaehlernew);
                nonusedzaehlernew = nonusedzaehlernew +1;
            end
		end
		factorstructurenew = factorstructurenew(ordervecnew,:);
        
        
        
	end
        
	%nrofsubjects
	%-------------
	nrofsubjects = size(anovadata,1);
	
	%GrandMean
	%-------------
	GrandMean = mean(mean(anovadata));
	
	
	%load factor names
	%-------------------
	plot2dlibfilepath= which('plot3d.m');
	plot2dlibfilepath(findstr(plot2dlibfilepath,'Plot3d.m'):findstr(plot2dlibfilepath,'Plot3d.m')+7)=[];
	file= [plot2dlibfilepath,'anovautil.mat'];
	load(file,'plotstringcell');
	
	%allgemein
	%------------
	figure(uigettextfigure);
	anovaplotaxes=findobj('tag','anovaaxes');
       
	if isempty(anovaplotaxes)
        
        if  ~isempty(gca)
            axes(gca);
        else
            anovaplotaxes = axes('units','normalized','position',[0.1 0.1 0.8 0.7],'tag','anovaaxes');
        end    
    else 
            axes(anovaplotaxes);
	end
    
    invzachsetoggle = findobj('tag','invzachsetoggle');
    invzachse = get(invzachsetoggle,'Value');
    if invzachse ==1
        set(gca,'ZDir','reverse');
    else
        set(gca,'ZDir','normal');
    end
    invyachsetoggle = findobj('tag','invyachsetoggle');
    invyachse = get(invyachsetoggle,'Value');
    if invyachse ==1
        set(gca,'YDir','reverse');
    else
        set(gca,'YDir','normal');
    end
    invxachsetoggle = findobj('tag','invxachsetoggle');
    invxachse = get(invxachsetoggle,'Value');
    if invzachse ==1
        set(gca,'XDir','reverse');
    else
        set(gca,'XDir','normal');
    end
	
	
	%gruppvarstatus
    %---------------
    gruppvarradio = findobj('tag','gruppenradio');
    gruppenpopup = findobj('tag','gruppenpopup');
    gruppvarstatus = get(gruppvarradio,'Value');
    if gruppvarstatus
        gruppenvar = get(gruppenpopup,'Value');
    end
    
    
    %scatterstatus 
    %-----------------
    scatterradio = findobj('tag','scatterradio');
    scatterstatus = get(scatterradio,'Value');
    
    %errorbarstatus
    %------------------
    errorbarradio = findobj('tag','errorbarradio');
    errorbarpopup = findobj('tag','errorbarpopup')
    errorbarstatus = get(errorbarradio,'Value');
    
	%draw
	%-------------
	drawbutton=findobj('tag','drawbutton');
	
	%Generalformatting
	%---------------------------
	generalcoloredit=findobj('tag','generalcoloredit');
	generalmarkerpopup=findobj('tag','generalmarkerpopup');
	generalmarkerstring=get(generalmarkerpopup,'string');
	if ~isempty(get(generalmarkerpopup,'value'))
        generalmarker=generalmarkerstring{get(generalmarkerpopup,'Value')};
	else
        generalmarker=generalmarkerstring{1};
	end
	generalmarkersizepopup=findobj('tag','generalmarkersizepopup');
    generalmarkersizestring = get(generalmarkersizepopup,'String');
	if ~isempty(get(generalmarkersizepopup,'value'))
        generalmarkersize=str2num(generalmarkersizestring{get(generalmarkersizepopup,'Value')});
	else
        generalmarkersize=1;
	end
	generallinewidthpopup=findobj('tag','generallinewidthpopup');
	if ~isempty(get(generallinewidthpopup,'Value'))
        generallinewidth=get(generallinewidthpopup,'Value');
	else
        generallinewidth=1;
	end
	generalcolormap = [0 0 1;...%blue
                       1 0 0;...%red
                       0 1 0;...%green
                       0 0 0;...%black
                       1 1 0;...%yellow
                       1 0 1;...%purple
                       0 1 1];%turquoise;
	if strcmp(get(generalcoloredit,'Style'),'edit')
        generalcolor = str2num(get(generalcoloredit,'String'));
        generalcolor = generalcolor/max(generalcolor);
        if length(generalcolor)~=3
            uiwait(errordlg('Could not recognize custom color input!','Error:'));
            generalcolor = [ 0 0 0];
        end
	else
        generalcolor = generalcolormap(get(generalcoloredit,'Value'),:);
	end
	
	
	%Gruppen
	%-------------
	gruppenfarbenradio = findobj('Tag','gruppenfarbenradio');
	gruppenfarben = get(gruppenfarbenradio,'Value');
	gruppenradio = findobj('Tag','gruppenradio');
	gruppenpopup=findobj('tag','gruppenpopup');
	gruppenpopupcell=get(gruppenpopup,'String');
	gruppenvarstatus = get(gruppenradio,'Value');
	nullgruppenradio = findobj('tag','nullgruppenradio');
	nullgruppenstatus = get(nullgruppenradio,'Value');
	if isempty(nullgruppenstatus)
        nullgruppenstatus = 0;
	end
	if strcmp(get(gruppenpopup,'Enable'),'on')
        aktivegruppe=get(gruppenpopup,'Value');
	else
        aktivegruppe=[];
	end
	
	colormappopup=findobj('tag','colormappopup');
	colormapauswahl=get(colormappopup,'Value');
	colormapnames=get(colormappopup,'string');
    if length(colormapnames)>1
        colormapnames = colormapnames{1};
    end
    if iscell(colormapauswahl)
        colormapauswahl = colormapauswahl{1};
    end
	if ~isempty(colormapauswahl)
        colormap(eval([colormapnames{colormapauswahl},'(50)']));
	else
        colormap(eval('hsv(50)'));
	end
	colormapmat=colormap;
	
	%markermap
	%------------
	markermap={'+';'o';'*';'.';'x';'square';'diamond';'v';'^';'>';'<';'pentagram';'hexagram'};
	
	%markerauswahl veränder
	%------------------------
	markermap=shuffle(markermap);
	gruppensymboleradio=findobj('tag','gruppensymboleradio');
	symbolschemapopup=findobj('tag','symbolschemapopup');
	if ~isempty(get(gruppensymboleradio,'Value'))
        gruppensymbolestatus= get(gruppensymboleradio,'Value');
        if gruppensymbolestatus == 1
            if ~isempty(get(symbolschemapopup,'value'))
                symbolschema=get(symbolschemapopup,'value');
            else
                symbolschema=1;
            end
        end
	else
        gruppensymbolestatus = 0;
	end
	gruppenmarkersizepopup=findobj('tag','gruppenmarkersizepopup');
	if ~isempty(get(gruppenmarkersizepopup,'Value'))
        gruppenmarkersize=get(gruppenmarkersizepopup,'Value');
	else
        gruppenmarkersize=1;
	end
	
	
	%Mittelwertformat und -farbe
	%----------------------------
	mittelwertsymbolpopup = findobj('tag','mittelwertsymbolpopup');
	mittelwertfarbedit = findobj('tag','mittelwertfarbedit');
	mittelwertmarkersizepopup = findobj('tag','mittelwertmarkersizepopup');
	mittelwertlinewidthpopup = findobj('tag','mittelwertlinewidthpopup');
	if ~isempty(get(mittelwertsymbolpopup,'Value'))
        mittelwertsymbolstring=get(mittelwertsymbolpopup,'String');
        mittelwertsymbolvalue=get(mittelwertsymbolpopup,'Value');
        mittelwertsymbol=mittelwertsymbolstring{mittelwertsymbolvalue};
	else
        mittelwertsymbol='o';
	end
	
	if ~isempty(get(mittelwertmarkersizepopup,'Value'))
        mittelwertmarkersize=get(mittelwertmarkersizepopup,'Value');
	else
        mittelwertmarkersize='1';
	end  
	if ~isempty(get(mittelwertlinewidthpopup,'Value'))
        mittelwertlinewidth=get(mittelwertlinewidthpopup,'Value');
	else
        mittelwertlinewidth='1';
	end 
	
	
	
	%nr of cells 
	%-------------------
	
	nrofxcells = 1;
	nrofxkomponenten = 0;
	nrofycells = 1;
	nrofykomponenten = 0;
	nrofzcells = 1;
	nrofzkomponenten = 0;
    
    if strcmp(action,'scheffe') | strcmp(action,'bonferroniholm') | strcmp(action,'customcontrast')
        %sort to allow only one post-hoc config
        nrofxcellsnew = 1;
		nrofxkomponentennew = 0;
		nrofycellsnew = 1;
		nrofykomponentennew = 0;
		nrofzcellsnew = 1;
		nrofzkomponentennew = 0;
        for r=1:size(curplotmodelnew,1)
            if curplotmodelnew(r,1)==0 & curplotmodelnew(r,2)==0 & curplotmodelnew(r,3)==0 
                break
            else
                if curplotmodelnew(r,1)~=0
                    nrofxcellsnew=nrofxcellsnew*factor{curplotmodelnew(r,1),2};
                    nrofxkomponentennew = nrofxkomponentennew + 1;
                end
                if curplotmodelnew(r,2)~=0
                    nrofycellsnew=nrofycellsnew*factor{curplotmodelnew(r,2),2};
                    nrofxykomponentennew = nrofykomponentennew + 1;
                end
                if curplotmodelnew(r,3)~=0
                    nrofzcellsnew=nrofzcellsnew*factor{curplotmodelnew(r,3),2};
                    nrofzkomponentennew = nrofzkomponentennew + 1;
                end
            end
		end
    end
    
	for r=1:size(curplotmodel,1)
        if curplotmodel(r,1)==0 & curplotmodel(r,2)==0 & curplotmodel(r,3)==0 
            break
        else
            if curplotmodel(r,1)~=0
                nrofxcells=nrofxcells*factor{curplotmodel(r,1),2};
                nrofxkomponenten = nrofxkomponenten + 1;
            end
            if curplotmodel(r,2)~=0
                nrofycells=nrofycells*factor{curplotmodel(r,2),2};
                nrofxykomponenten = nrofykomponenten + 1;
            end
            if curplotmodel(r,3)~=0
                nrofzcells=nrofzcells*factor{curplotmodel(r,3),2};
                nrofzkomponenten = nrofzkomponenten + 1;
            end
        end
	end
	
	%farbenvec
	%---------------
	dist = floor(size(colormapmat,1)/nrofxcells);
	for k=1:nrofxcells
        farbenvec(k,:)=colormapmat((k-1)*dist+1,:);
	end   
	
	%factorstructure
	%------------------------
    if strcmp(action,'scheffe') | strcmp(action,'bonferroniholm') | strcmp(action,'customcontrast')
        factorstructure_ianew = factorstructurenew;
		komponentennew  = cell(nrofxkomponentennew ,2);
		nrofinteractioncellsnew  = 1;
		sizestringnew  = '';
        sizestringreversenew  = '';
		conditionindexstringnew  = '';
		for komponentenzaehler=1:nrofxkomponentennew 
            %Name der Komponente
            if gruppvarstatus
                if gruppenvar == curplotmodelnew (komponentenzaehler,1)
                    gruppvarordernew  = [komponentenzaehler];
                end
            end
            komponentennew {komponentenzaehler,1}=factor{curplotmodelnew (komponentenzaehler,1),1};
            %nrofgradations der Komponente
            komponentennew {komponentenzaehler,2}=factor{curplotmodelnew (komponentenzaehler,1),2};
            if ~isempty(sizestringnew)
                sizestringnew  = [sizestringnew ,',',num2str(komponentennew {komponentenzaehler,2})];
                sizestringreversenew  = [num2str(komponentennew {komponentenzaehler,2}),',',sizestringreversenew ];
                conditionindexstringnew  = [conditionindexstringnew ,',','factorstructure_ianew(',num2str(komponentenzaehler),',r)'];
            else
                sizestringnew  = [num2str(komponentennew {komponentenzaehler,2})];
                sizestringreversenew  = [num2str(komponentennew {komponentenzaehler,2})];
                conditionindexstringnew  = ['factorstructure_ianew (',num2str(komponentenzaehler),',r)'];
            end
            nrofinteractioncellsnew  = nrofinteractioncellsnew  * komponentennew {komponentenzaehler,2};
		end
    end
    
	factorstructure_ia = factorstructure;
	komponenten = cell(nrofxkomponenten,2);
	nrofinteractioncells = 1;
	sizestring = '';
    sizestringreverse = '';
	conditionindexstring = '';
	for komponentenzaehler=1:nrofxkomponenten
        %Name der Komponente
        if gruppvarstatus
            if gruppenvar == curplotmodel(komponentenzaehler,1)
                gruppvarorder = [komponentenzaehler];
            end
        end
        komponenten{komponentenzaehler,1}=factor{curplotmodel(komponentenzaehler,1),1};
        %nrofgradations der Komponente
        komponenten{komponentenzaehler,2}=factor{curplotmodel(komponentenzaehler,1),2};
        if ~isempty(sizestring)
            sizestring = [sizestring,',',num2str(komponenten{komponentenzaehler,2})];
            sizestringreverse = [num2str(komponenten{komponentenzaehler,2}),',',sizestringreverse];
            conditionindexstring = [conditionindexstring,',','factorstructure_ia(',num2str(komponentenzaehler),',r)'];
        else
            sizestring = [num2str(komponenten{komponentenzaehler,2})];
            sizestringreverse = [num2str(komponenten{komponentenzaehler,2})];
            conditionindexstring = ['factorstructure_ia(',num2str(komponentenzaehler),',r)'];
        end
        nrofinteractioncells = nrofinteractioncells * komponenten{komponentenzaehler,2};
	end
	
    
    
    
    
    %sizestring
    %----------------------
	if nrofxkomponenten==1
        sizestring = ['1,',sizestring];
        sizestringreverse = [sizestringreverse,',1'];
	end
    evalstring = ['InteractionMean = zeros(',sizestring,');']; %--->InteractionMean = zeros(.....);
	eval(evalstring);
    if strcmp(action,'scheffe') | strcmp(action,'bonferroniholm')
        evalstringnew = ['InteractionMeannew = zeros(',sizestringnew,');']; %--->InteractionMean = zeros(.....);
		eval(evalstring);
	end
    if strcmp(action,'scheffe') | strcmp(action,'bonferroniholm') | strcmp(action,'customcontrast')
        if nrofxkomponentennew==1
            sizestringnew = ['1,',sizestringnew];
            sizestringreversenew = [sizestringreversenew,',1'];
		end
        evalstring = ['InteractionMeannew = zeros(',sizestringnew,');']; %--->InteractionMean = zeros(.....);
		eval(evalstring);
	end  
	
    
    
	%conditionmat
	%--------------
	eval(['conditionmat = zeros(',sizestring,')']);
	conditionmat(1:end)=linspace(1,nrofinteractioncells,nrofinteractioncells);
	if strcmp(action,'scheffe') | strcmp(action,'bonferroniholm') | strcmp(action,'customcontrast')
        eval(['conditionmatnew = zeros(',sizestringnew,')']);
	    conditionmatnew(1:end)=linspace(1,nrofinteractioncellsnew,nrofinteractioncellsnew);
	end
    
    
	%conditionvec
	%---------------
	conditionvec = zeros(1,size(anovadata,2));
	%restzeilen löschen
	deletevec=[];
	deletezaehler=1;
	for r=1:nroffactors
       if isempty(find(curplotmodel(:,1)==r))
           deletevec(deletezaehler)=find(ordervec==r);
           deletezaehler=deletezaehler+1;
       end
	end
    if gruppvarstatus
        gruppvarhelp = zeros(size(factorstructure_ia,1),1);
        gruppvarhelp(gruppenvar)=1;
        gruppvarhelp(deletevec)=[];
        gruppenvar_ia = find(gruppvarhelp);
    end
	factorstructure_ia(deletevec,:)=[];
	evalstring = ['conditionvec(1,r)=conditionmat(',conditionindexstring,');'];
	for r=1:size(factorstructure_ia,2)
        eval(evalstring);
	end
    if strcmp(action,'scheffe') | strcmp(action,'bonferroniholm') | strcmp(action,'customcontrast')
         conditionvecnew = zeros(1,size(anovadata,2));
		%restzeilen löschen
		deletevecnew=[];
		deletezaehlernew=1;
		for r=1:nroffactors
           if isempty(find(curplotmodelnew(:,1)==r))
               deletevecnew(deletezaehlernew)=find(ordervecnew==r);
               deletezaehlernew=deletezaehlernew+1;
           end
		end
        if gruppvarstatus
            gruppvarhelpnew = zeros(size(factorstructure_ianew,1),1);
            gruppvarhelpnew(gruppenvar)=1;
            gruppvarhelpnew(deletevecnew)=[];
            gruppenvar_ianew = find(gruppvarhelpnew);
        end
		factorstructure_ianew(deletevecnew,:)=[];
		evalstring = ['conditionvecnew(1,r)=conditionmatnew(',conditionindexstringnew,');'];
		for r=1:size(factorstructure_ianew,2)
            eval(evalstring);
		end
	end
	
    
   
    
    %norepfactorstructure
    %------------------------
    norepfactorstructure_ia = factorstructure_ia;
    firstzaehler = 1;
    spaltenzaehler =2;
    while 1
        firstcolumn = norepfactorstructure_ia(:,firstzaehler);
        if sum(firstcolumn==norepfactorstructure_ia(:,spaltenzaehler))==length(firstcolumn)
            norepfactorstructure_ia(:,spaltenzaehler)=[];
            firstzaehler = 1;
            spaltenzaehler = 2;
        else
            spaltenzaehler = spaltenzaehler+1;
        end
        if spaltenzaehler >= size(norepfactorstructure_ia,2)
            firstzaehler = firstzaehler+1;
            spaltenzaehler = firstzaehler+1;
            if firstzaehler==size(norepfactorstructure_ia,2)
                break;
            end
        end
    end
    
    norepconditionvec = conditionvec;
    firstzaehler = 1;
    spaltenzaehler =2;
    while 1
        firstcolumn = norepconditionvec(firstzaehler);
        if firstcolumn==norepconditionvec(spaltenzaehler)
            norepconditionvec(spaltenzaehler)=[];
            firstzaehler = 1;
            spaltenzaehler = 2;
        else
            spaltenzaehler = spaltenzaehler+1;
        end
        if spaltenzaehler >= size(norepconditionvec,2)
            firstzaehler = firstzaehler+1;
            spaltenzaehler = firstzaehler+1;
            if firstzaehler==size(norepconditionvec,2)
                break;
            end
        end
    end
        
    
     
    
	%Calculate Mean
	%----------------
	CellMean = mean(anovadata,1);
	ConditionQS = 0;
	TestQS = 0;
	InteractionSubjectMean=zeros(nrofsubjects,size(InteractionMean,2));
	InteractionMean = zeros(1,nrofinteractioncells);
	InteractionErrorMat = zeros(nrofsubjects*length(find(conditionvec==1)),nrofinteractioncells);
    
    
%     conditionvec = conditionvec
%     factorstructure_ia = factorstructure_ia
%     
%     norepconditionvec = norepconditionvec
%     norepfactorstructure_ia = norepfactorstructure_ia
    
    
    InteractionMeanOrdered = InteractionMean;
    
	for r=1:nrofinteractioncells
        %InteractionMean
        %-------------------
        InteractionMean(r)=mean(CellMean(find(conditionvec==r)));
        InteractionMeanOrdered(find(norepconditionvec==r)) = InteractionMean(r);
        %InteractionSubjectMean
        %----------------------------
        InteractionSubjectMean(:,r)=mean(anovadata(:,find(conditionvec==r)),2);
        %InteractionErrorMat
        %-----------------------------------
        errortmp = anovadata(:,find(conditionvec==r));
        for s=1:length(find(conditionvec==r))
            InteractionErrorMat((s-1)*nrofsubjects+1:s*nrofsubjects,r)=errortmp(:,s);
        end
	end
    
    
    if strcmp(action,'scheffe') | strcmp(action,'bonferroniholm') | strcmp(action,'customcontrast')
   
		CellMeannew = mean(anovadata,1);
		ConditionQSnew = 0;
		TestQSnew = 0;
		InteractionSubjectMeannew=zeros(nrofsubjects,size(InteractionMeannew,2));
		InteractionMeannew = zeros(1,nrofinteractioncellsnew);
		InteractionErrorMatnew = zeros(nrofsubjects*length(find(conditionvecnew==1)),nrofinteractioncellsnew);
        norepfactorstructure_ianew = factorstructure_ianew;
        firstzaehlernew = 1;
        spaltenzaehlernew =2;
        while 1
            firstcolumnnew = norepfactorstructure_ianew(:,firstzaehlernew);
            if sum(firstcolumnnew==norepfactorstructure_ianew(:,spaltenzaehlernew))==length(firstcolumnnew)
                norepfactorstructure_ianew(:,spaltenzaehlernew)=[];
                firstzaehlernew = 1;
                spaltenzaehlernew = 2;
            else
                spaltenzaehlernew = spaltenzaehlernew+1;
            end
            if spaltenzaehlernew >= size(norepfactorstructure_ianew,2)
                firstzaehlernew = firstzaehlernew+1;
                spaltenzaehlernew= firstzaehlernew+1;
                if firstzaehlernew==size(norepfactorstructure_ianew,2)
                    break;
                end
            end
        end
        norepconditionvecnew = conditionvecnew;
        firstzaehlernew = 1;
        spaltenzaehlernew =2;
        while 1
            firstcolumnnew = norepconditionvecnew(firstzaehlernew);
            if firstcolumnnew==norepconditionvecnew(spaltenzaehlernew)
                norepconditionvecnew(spaltenzaehlernew)=[];
                firstzaehlernew = 1;
                spaltenzaehlernew = 2;
            else
                spaltenzaehlernew = spaltenzaehlernew+1;
            end
            if spaltenzaehlernew >= size(norepconditionvecnew,2)
                firstzaehlernew = firstzaehlernew+1;
                spaltenzaehlernew = firstzaehlernew+1;
                if firstzaehlernew==size(norepconditionvecnew,2)
                    break;
                end
            end
        end 
        
        %labels for post-hoc : factorstruct_ia_con
        %----------------------------
        factorstruct_ia_con = zeros(size(norepfactorstructure_ianew));
        for r=1:size(norepconditionvecnew,2)
            factorstruct_ia_con(:,r) = norepfactorstructure_ianew(:,find(norepconditionvecnew==r));
        end
        
        conditionvecnew = conditionvecnew
        factorstructure_ianew = factorstructure_ianew
        norepconditionvecnew = norepconditionvecnew
        norepfactorstructure_ianew= norepfactorstructure_ianew
        InteractionMeanOrderednew = InteractionMeannew;
		for r=1:nrofinteractioncells
            %InteractionMean
            %-------------------
            InteractionMeannew(r)=mean(CellMeannew(find(conditionvecnew==r)));
            InteractionMeanOrderednew(find(norepconditionvecnew==r)) = InteractionMeannew(r);
            %InteractionSubjectMean
            %----------------------------
            InteractionSubjectMeannew(:,r)=mean(anovadata(:,find(conditionvecnew==r)),2);
            %InteractionErrorMat
            errortmpnew = anovadata(:,find(conditionvecnew==r));
            for s=1:length(find(conditionvecnew==r))
                InteractionErrorMatnew((s-1)*nrofsubjects+1:s*nrofsubjects,r)=errortmpnew(:,s);
            end
		end
    end
    
    
    
    
    
	%bar-plot
	%-----------
    cla
    hold on
        if gruppvarstatus
            %adjust axes CLim
            evalstring = ['colormat = ',colormapnames{colormapauswahl},'(',num2str(factor{gruppenvar,2}),');'];
            eval(evalstring);
            colormap(colormat);
            if strcmp(generalmarker,'Bar')
                h=bar(1:size(InteractionMean,2),InteractionMean);
                view(0,90)
            elseif strcmp(generalmarker,'Bar3')
                h=bar3(1:size(InteractionMean,2),InteractionMean);
                view(92,3)
            else
                h=bar(1:size(InteractionMean,2),InteractionMean);
                set(h,'visible','off');
                for q=1:size(InteractionMean,2)
                    plot(q,InteractionMean(q),'Marker',generalmarker,'Color',generalcolor,'MarkerSize',generalmarkersize,'MarkerFaceColor',generalcolor);
                end
            end
            
            if strcmp(generalmarker,'Bar3')
                set(gca,'CLim',[1 factor{gruppenvar,2}]);
                colorvec = factorstructure_ia(gruppenvar_ia,:);
                CData = get(h,'CData');
                step = floor(size(CData,1)/nrofinteractioncells);
                for s=1:nrofinteractioncells
                    colorcellvec(s) = mean(colorvec(find(conditionvec == s)),2);
                    CData((s-1)*step+1:s*step,:)=colorcellvec(s);
                end
                set(h,'CData',CData);  
            else
                  set(gca,'CLim',[1 factor{gruppenvar,2}]);
                colorvec = factorstructure_ia(gruppenvar_ia,:);
                FaceVertexCData = get(h,'FaceVertexCData');
                step = floor(length(FaceVertexCData)/nrofinteractioncells);
                for s=1:nrofinteractioncells
                    colorcellvec(s) = mean(colorvec(find(conditionvec == s)),2);
                    FaceVertexCData((s-1)*step+1:s*step)=colorcellvec(s);
                end
                set(h,'FaceVertexCData',FaceVertexCData);   
            end
        else
            colormap(generalcolor);
            h=bar(1:size(InteractionMean,2),InteractionMean);
        end
        
        if errorbarstatus
            errorbartype = get(errorbarpopup,'Value');
            
            if strcmp(generalmarker,'Bar3')
                  if errorbartype == 1 %std dev
				    errors = std(InteractionErrorMat); 
                    
                elseif errorbartype == 2 %std error
				    errors = (std(InteractionErrorMat))/(sqrt(size(InteractionErrorMat,1))); 
                    
                elseif errorbartype == 3 %confidence intervall
                    
                    for s=1:size(InteractionErrorMat,2)
                        [hy(s),prob(s),ci(s,:),stats(s)] = ttest(InteractionErrorMat(:,s),0,0.05,0)
                    end
                    ci = ci';
                    ci(1,:)=abs(InteractionMean-ci(1,:));
                    ci(2,:)=[];
                    errors = ci;
                end
                
                for w=1:size(InteractionMean,2)
                    plot3([1;1],[w;w],[InteractionMean(w)-errors(w),InteractionMean(w)+errors(w)],'Color',[0 0 0]);
                end
                set(gcf,'Renderer','zbuffer')
                
                
                
            else
                if errorbartype == 1 %std dev
                    
				    errors = std(InteractionErrorMat); 
                    colormat = colormap;
					h = errorbar(1:size(InteractionMean,2),InteractionMean,errors,'.');
                    set(h,'Color',[0 0 0]); 
                    
                elseif errorbartype == 2 %std error
                    
				    errors = (std(InteractionErrorMat))/(sqrt(size(InteractionErrorMat,1))); 
                    colormat = colormap;
					h = errorbar(1:size(InteractionMean,2),InteractionMean,errors,'.');
                    set(h,'Color',[0 0 0]);
                    
                elseif errorbartype == 3 %confidence intervall
                    
                    for s=1:size(InteractionErrorMat,2)
                        [hy(s),prob(s),ci(s,:),stats(s)] = ttest(InteractionErrorMat(:,s),0,0.05,0)
                    end
                    ci = ci';
                    ci(1,:)=abs(InteractionMean-ci(1,:));
                    ci(2,:)=[];;
                    errors = ci;
                    colormat = colormap;
					h = errorbar(1:size(InteractionMean,2),InteractionMean,ci,'.');
                    set(h,'Color',[0 0 0]);
                end
            end
        end
        
        if scatterstatus
            for e=1:size(InteractionErrorMat,2)
                for f=1:size(InteractionErrorMat,1)
                     plot(e,InteractionErrorMat(f,e),'.','Color',colormat(colorcellvec(e),:));
                 end
             end
         end
	hold off
    
    if strcmp(action,'scheffe') 
        
        %generate contrast coefficients
        nrofcontrasts = nchoosek(nrofinteractioncells,2);
        coefficientmat = zeros(nrofcontrasts,nrofinteractioncells);
        offset = 0;
        for r=1:nrofinteractioncells
            addcontrasts = 0;
            for s=r+1:nrofinteractioncells
                coefficientmat(offset+s-r,r)=1;
                coefficientmat(offset+s-r,s)= -1;
                addcontrasts = addcontrasts +1;
            end
            offset = offset + addcontrasts;
        end
        
        %calculate contrasts
        signmat= ones(nrofinteractioncells,nrofinteractioncells);
        posthocorder = size(curplotmodelnew,1); %e.g. two-way-ia
        for t=1:posthocorder
            posthoctype(t) = curplotmodelnew(t,1); % e.g. [1 2]
        end
        curia =0;
        
        permuttype = perms(posthoctype);
        for u=1:size(results{posthocorder},1)
            for e=1:size(permuttype,1)
                if sum(results{posthocorder,2}{u,1}==permuttype(e,:))==posthocorder
                    if e>1
                        curia = u;
                        sortnamesstatus = 1;
                        break;
                    else
                        curia = u;
                        sortnamesstatus = 0;
                        break;
                    end
                end
            end
        end
        
        %error-variance
        var_res = results{posthocorder,2}{curia,7}*2/nrofsubjects;
        %error-df
        df_var_res = results{posthocorder,2}{curia,6};
        for r=1:nrofcontrasts
            D2=(sum(InteractionMeannew.*coefficientmat(r,:)))^2;
            f = D2 / var_res;
            p = 1-fcdf(f,1,df_var_res);
            posx = find(coefficientmat(r,:)==1);
            posy = find(coefficientmat(r,:)==-1);
            signmat(posx,posy)=p;
            signmat(posy,posx)=p;
        end
        
  
        signmat = (round(signmat*10000))/10000;
        signmat(find(signmat<0.00001))=0.00001;
        editfenster = findobj('tag','editfenster');
        rownames = factorstruct_ia_con';
        
        columnnames = factorstruct_ia_con;
        columnnamesrev = columnnames(:,norepconditionvecnew);
        columnnames = [zeros(posthocorder,posthocorder) columnnames];
        
        cellnames = zeros(size(signmat,1),posthocorder);
        ianame = [factor{posthoctype(1)}];
        for r=2:posthocorder
            ianame = [ianame,' X ',factor{posthoctype(r),1}];
        end
        
        tmpstring = get(editfenster,'String');
        tmpstring = char([],char(tmpstring),['All contrasts for ',ianame,':'],...
            '------------------------------------------------------','',num2str(columnnames,'%1d             '),[num2str(rownames,'%1d             '),num2str(signmat,'%1.5f  ')],[]);
        
        set(editfenster,'String',tmpstring);
        
    end
    
    if strcmp(action,'customcontrast') & isempty(contmat) 
        
        %generate contrast coefficients
        contrastdef(num2str(factorstruct_ia_con));
        plot2d('GetCustomContrastCoeff');
    end
    
    if strcmp(action,'customcontrast') & ~isempty(contmat) 
        if size(contmat,2)~=nrofinteractioncells
            uiwait(errordlg('You must define coefficients for every cell of the effect/interaction. Set 0 to ignore cells! Check that you selected the correct effect/interaction to be tested!','Coefficients incorrect:'));
            return
        end
        customcoeffmat = contmat;
        nrofcontrasts = size(customcoeffmat,1);
        
        %calculate contrasts
        signmat= ones(nrofinteractioncells,nrofinteractioncells);
        posthocorder = size(curplotmodelnew,1); %e.g. two-way-ia
        for t=1:posthocorder
            posthoctype(t) = curplotmodelnew(t,1); % e.g. [1 2]
        end
        curia =0;
        
        permuttype = perms(posthoctype);
        for u=1:size(results{posthocorder},1)
            for e=1:size(permuttype,1)
                if sum(results{posthocorder,2}{u,1}==permuttype(e,:))==posthocorder
                    if e>1
                        curia = u;
                        sortnamesstatus = 1;
                        break;
                    else
                        curia = u;
                        sortnamesstatus = 0;
                        break;
                    end
                end
            end
        end
      
        signvec = ones(nrofcontrasts,1);
        Fvec = ones(nrofcontrasts,1);
        %error-df
        df_var_res = results{posthocorder,2}{curia,6};
        for r=1:nrofcontrasts
            
            sum2coeff = sum(customcoeffmat(r,:).^2);
            var_res = results{posthocorder,2}{curia,7}* sum2coeff/nrofsubjects;
            D2=(sum(InteractionMeannew.*customcoeffmat(r,:)))^2;
            
            f = D2 / var_res;
            Fvec(r) = f;
            p = 1-fcdf(f,1,df_var_res);
            signvec(r) = p;
        end
        
  
        signmat = (round(signmat*10000))/10000;
        signmat(find(signmat<0.00001))=0.00001;
        editfenster = findobj('tag','editfenster');
        rownames = customcoeffmat;
        sztmp = size(num2str(rownames,'%1d '),2);
        columnnames = ['type',char(ones(1,round((sztmp-4)*1.7))*32),'F-Value      p'];
        
        cellnames = zeros(size(signmat,1),posthocorder);
        ianame = [factor{posthoctype(1)}];
        for r=2:posthocorder
            ianame = [ianame,' X ',factor{posthoctype(r),1}];
        end
        
        tmpstring = get(editfenster,'String');
        tmpstring = char([],char(tmpstring),['Custom contrasts:'],...
            '------------------------------------------------------',num2str(columnnames,'%1d             '),...
            [num2str(rownames,'%1d '),'    ',num2str(Fvec,'%1.5f  '),'    ',num2str(signvec,'%1.5f  ')],[]);
        
        set(editfenster,'String',tmpstring);
        
    end

	if strcmp(action,'bonferroniholm')
        
        %generate contrast coefficients
        [filename,filepath]= uigetfile('*.txt','Please choose contrast file with the contrast to step down:');
        RepConFilePath=[filepath filename];
		[ContMat,ContStr,ContFile,ContPath,ContFilePath]=ReadRepCon(RepConFilePath);
        ContMat = ContMat(:,2:end);
        if size(ContMat,2)~=nrofinteractioncells
            uiwait(errordlg('You must define coefficients for every cell of the effect/interaction. Set 0 to ignore cells! Check that you selected the correct effect/interaction to be tested!','Coefficients incorrect:'));
            return
        end
        customcoeffmat = ContMat;
        nrofcontrasts = size(customcoeffmat,1);
        
        %calculate contrasts
        signmat= ones(nrofinteractioncells,nrofinteractioncells);
        posthocorder = size(curplotmodelnew,1); %e.g. two-way-ia
        for t=1:posthocorder
            posthoctype(t) = curplotmodelnew(t,1); % e.g. [1 2]
        end
        curia =0;
        
        permuttype = perms(posthoctype);
        for u=1:size(results{posthocorder},1)
            for e=1:size(permuttype,1)
                if sum(results{posthocorder,2}{u,1}==permuttype(e,:))==posthocorder
                    if e>1
                        curia = u;
                        sortnamesstatus = 1;
                        break;
                    else
                        curia = u;
                        sortnamesstatus = 0;
                        break;
                    end
                end
            end
        end
      
        signvec = ones(nrofcontrasts,1);
        Fvec = zeros(nrofcontrasts,1);
        %error-df
        df_var_res = results{posthocorder,2}{curia,6};
        for r=1:nrofcontrasts
            
            sum2coeff = sum(customcoeffmat(r,:).^2);
            var_res = results{posthocorder,2}{curia,7}* sum2coeff/nrofsubjects;
            D2=(sum(InteractionMeannew.*customcoeffmat(r,:)))^2;
            
            f = D2 / var_res;
            Fvec(r) = f;
            p = 1-fcdf(f,1,df_var_res);
            signvec(r) = p;
        end
        
  
        [signvec,ord]=sort(signvec);
        Fvec = Fvec(ord);
        ContStr=ContStr(ord,:);
        customcoeffmat = customcoeffmat(ord,:);
        signmat = (round(signmat*10000))/10000;
        signmat(find(signmat<0.00001))=0.00001;
        editfenster = findobj('tag','editfenster');
        rownames = customcoeffmat;
        sztmp = size(num2str(rownames,'%1d '),2);
        columnnames = ['type',char(ones(1,round((sztmp-4)*1.7))*32),'F-Value      p     p_crit'];
        
        for r=1:nrofcontrasts
            alphavec(r,1)=0.05 / (nrofcontrasts-(r-1));
        end
        
        cellnames = zeros(size(signmat,1),posthocorder);
        ianame = [factor{posthoctype(1)}];
        for r=2:posthocorder
            ianame = [ianame,' X ',factor{posthoctype(r),1}];
        end
        
        tmpstring = get(editfenster,'String');
        tmpstring = char([],char(tmpstring),['Sorted contrasts:'],...
            '------------------------------------------------------',num2str(columnnames,'%1d             '),...
            [ContStr,char(ones(nrofcontrasts,4)*32),num2str(Fvec,'%1.5f  '),num2str(signvec,'%1.5f  '),num2str(alphavec,'%1.5f  ')]);
        
        set(editfenster,'String',tmpstring);
        
    end
	
else
    figure(uigettextfigure);
    cla 
end



return