function [contourpic]=surfcdata2contourpic(CalcPotTmp,ColorMat,MinAmp,MaxAmp,ColorAmpTotStatus,contourintervall,NColor,CutRealBotVal);

%   surfcdata2contourpic generates a contourplot out of the vertex color values
%   of the sphere-model, saves it as a jpeg-file, reads in this file and
%   returns it as a picture matrix, that can then be used to texturize
%   a custom surface model.
%
%   See also EMEGS3D.

%   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<1;potential3dfilepath=which('potential.mat'); load(potential3dfilepath,'XScalp','YScalp','ZScalp','CalcPotTmp');end
if nargin<8;CutRealBotVal=0;end


%keep colormap for later reset
colormapold = colormap;

%data range  
maxdataamp = max(max(CalcPotTmp));
mindataamp = min(min(CalcPotTmp));
range= maxdataamp - mindataamp;
dataschwerpunkt = (maxdataamp+mindataamp)/2;

%user entered range
colorrange=MaxAmp-MinAmp;
schwerpunkt = (MaxAmp+MinAmp)/2;
meancolorrange = schwerpunkt;
          
%user relative to data
diffschwerpunkt = dataschwerpunkt-schwerpunkt;
if ColorAmpTotStatus
    colorstep = colorrange/NColor;
else
    colorstep = contourintervall;
end


    
    
%autoamp
autoampradio=findobj('String','Auto. Amp.');
AutoAmp=get(autoampradio,'Value');

%ColorAmpTotStatus is 1, if 'N-Color' is checked. 0 means 'Color-by-Amplitude'


if isempty(AutoAmp); AutoAmp=0; end


%Potentialentsprechungen der Farbwerte berechnen
%----------------------------------------------
if ~(MinAmp==0 & MaxAmp==0) | MinAmp == MaxAmp
	%Use N-Color ->  n colors for userrange
	%-------------
	if ColorAmpTotStatus==1
        
            
			nrcontours=ceil(colorrange/colorstep)-1;
            %Gerade anzahl konturen, ungerade anzahl farbewerte
             if mod(nrcontours,2)==0
                colorvaluevec(1)=meancolorrange;
				for j=2:2:nrcontours
                    colorvaluevec(j)=meancolorrange+(j)*0.5*(colorrange/NColor);
                    colorvaluevec(j+1)=meancolorrange-(j)*0.5*(colorrange/NColor);
				end
            %ungerade anzahl konturen, gerade anzahl farbewerte
            else
                for j=1:2:nrcontours+1
                    colorvaluevec(j)=meancolorrange-0.5*(colorrange/NColor)+(j+1)*0.5*(colorrange/NColor);
                    colorvaluevec(j+1)=meancolorrange+0.5*(colorrange/NColor)-(j+1)*0.5*(colorrange/NColor);
				end
            end
	
	%Use 'color-by-amplitude' -> number of colors depending on userrange
	%-----------------------
	else
        %bigger data range than userentered range -> bottom- and ceiling-effekt
        if (range-colorrange)>0
			meancolorrange=(MaxAmp+MinAmp)/2;
			nrcontours=ceil(colorrange/contourintervall)-1;
            if mod(nrcontours,2)==0
                colorvaluevec(1)=meancolorrange;
				for j=2:2:nrcontours
                    colorvaluevec(j)=meancolorrange+(j)*0.5*contourintervall;
                    colorvaluevec(j+1)=meancolorrange-(j)*0.5*contourintervall;
				end
            else
				for j=1:2:nrcontours+1
                    colorvaluevec(j)=meancolorrange+(j+1)*0.5*contourintervall-0.5*contourintervall;
                    colorvaluevec(j+1)=meancolorrange-(j+1)*0.5*contourintervall+0.5*contourintervall;
				end
            end
        %bigger userentered range than datarange  -> smaller color contrast
		else
            meanrange=MaxAmp-0.5*colorrange;
			nrcontours=ceil(colorrange/contourintervall)-1;
			meancolorrange=(MaxAmp+MinAmp)/2;
            if mod(nrcontours,2)==0
                colorvaluevec(1)=meanrange;
				for j=2:2:nrcontours
                    colorvaluevec(j)=meancolorrange+(j)*0.5*contourintervall;
                    colorvaluevec(j+1)=meancolorrange-(j)*0.5*contourintervall;
				end
            else
                for j=1:2:nrcontours+1
                    colorvaluevec(j)=meancolorrange+(j+1)*0.5*contourintervall-0.5*contourintervall;
                    colorvaluevec(j+1)=meancolorrange-(j+1)*0.5*contourintervall+0.5*contourintervall;
				end
				
            end
		end
       
	end
end

%Gleiche Abstände überprüfen
%----------------------------------------------
colorvaluevec=sort(colorvaluevec);
if length(colorvaluevec)>1 
	diffcolorvaluevec=round(diff(colorvaluevec)*100);
	idvec= sum(diffcolorvaluevec==diffcolorvaluevec(1));
	if idvec~=length(diffcolorvaluevec)
        uiwait(errordlg('Achtung: ungleiche Abstände der Farbwerte...'));
    end
elseif ~(MinAmp==0 & MaxAmp==0)  | MinAmp == MaxAmp
   uiwait(errordlg('Single contour plots cannot be filled!')); 
end

%Colormap erstellen
%-------------------
% colormappopup=findobj('tag','colormappopup');
% labelcell={'hsv';'hot';'cool';'jet';'pink';'flag';'copper';'gray'};
% colormapvalue=get(colormappopup,'Value');
% if ~ColorAmpTotStatus
%     NColor = round((MaxAmp-MinAmp) / NColor);
% end
% evalstring=['colormatnew=',labelcell{colormapvalue},'(NColor);'];
% eval(evalstring);
colormatnew = ColorMat;

potcontourpopup = findobj('tag','potcontourpopup');
cuttop = 0;
cutbottom = 0;
cutleft = 0;
cutright = 0;

%768 pixel Bildbreite
%======================
%links: 95
%rechts: 673

%contour
PotContourVal=get(potcontourpopup,'Value');
if iscell(PotContourVal)
    PotContourVal=PotContourVal{1};
else
    PotContourVal=PotContourVal(1);
end
%======================
if PotContourVal==3

	%---------------------------------------------------------------------------------
	%interpolation
    %======================
	interpmat = interp2(CalcPotTmp,4);
	fig=figure('Visible','off','tag','invisiblefigure');
	colormap(colormatnew);
	handle=findobj('tag','invisiblefigure');
	contourwerte=[];
	contourwerte(1)=min(min(CalcPotTmp));
	
	for k=2:length(colorvaluevec)
        contourwerte(k)=(colorvaluevec(k-1)+colorvaluevec(k))/2;
	end
	
	if length(colorvaluevec)<=1
        [C,h]=contour(interpmat,[contourwerte contourwerte]);
	elseif length(colorvaluevec)==2
        [C,h]=contourf(interpmat,contourwerte);
	else
        interpmat(find(interpmat<contourwerte(2)))=contourwerte(2)-(contourwerte(3)-contourwerte(2))/2;
        contourwerte(1)=contourwerte(2)-(contourwerte(3)-contourwerte(2));
        [C,h]=contourf(interpmat,contourwerte);
	end
    
    set(gca,'CLim',[MinAmp MaxAmp]);
	set(gcf,'units','points','position',[0 0 500 500],'PaperPositionMode','auto','PaperSize',[800 800]);
	set(gca,'units','normalized','position',[0 0 1 1]);
    view(0,90);
    axis equal;
	print(gcf,'-djpeg','-r0','contourplottmp.jpg');
	contourpic=imread('contourplottmp.jpg','jpg');
	contourpic = contourpic(1+cuttop:end-cutbottom,1+cutleft:end-cutright,:);
	%cutrealbot
    %======================
	if ~isempty(CutRealBotVal) & CutRealBotVal~=0 & CutRealBotVal~=1
		contourpic(end-(CutRealBotVal+1)*20:end,:,:)=[];
		contourpic=[contourpic;ones((CutRealBotVal+1)*20+200,size(contourpic,2),3)*255];
    elseif CutRealBotVal==1
        contourpic=[contourpic]; 
    else
        contourpic=[contourpic];  
	end
   
 	close(fig);
%-------------------------------------------------------------------------------

%areas
%======================
elseif PotContourVal==1

	%---------------------------------------------------------------------------------
	%interpolation
	interpmat = interp2(CalcPotTmp,4);
	fig=figure('Visible','off','tag','invisiblefigure');
    
	colormap(colormatnew);
	handle=findobj('tag','invisiblefigure');
	contourwerte=[];
	contourwerte(1)=min(min(CalcPotTmp));
	
	for k=2:length(colorvaluevec)
        contourwerte(k)=(colorvaluevec(k-1)+colorvaluevec(k))/2;
	end
	
	if length(colorvaluevec)<=1
        contour(interpmat,[contourwerte contourwerte]);
	elseif length(colorvaluevec)==2
        contour(interpmat,contourwerte);
	else
        interpmat(find(interpmat<contourwerte(2)))=contourwerte(2)-(contourwerte(3)-contourwerte(2))/2;
        contourwerte(1)=contourwerte(2)-(contourwerte(3)-contourwerte(2));
        clines=contour(interpmat,contourwerte,'.');
        if 0
            pointzaehler=1;
            hold on
            while 1
                if pointzaehler > size(clines,2)
                    break
                end
                for r=1:clines(2,pointzaehler)-1;
                    if pointzaehler+r+1<size(clines,2)+1
                        plot([clines(1,pointzaehler+r);clines(1,pointzaehler+r+1)], [clines(2,pointzaehler+r);clines(2,pointzaehler+r+1)],'bp','LineWidth',50);
                    end    
                end
                pointzaehler = pointzaehler + r +2;
            end
            hold off
        end
    
	end
  
    set(gca,'CLim',[MinAmp MaxAmp]);
	set(gcf,'units','points','position',[0 0 500 500],'PaperPositionMode','auto','PaperSize',[800 800]);
	set(gca,'units','normalized','position',[0 0 1 1]);
    view(0,90);
    axis equal;
	print(gcf,'-djpeg','-r0','contourplottmp.jpg');
    close(fig);
	contourpic=imread('contourplottmp.jpg','jpg');
	contourpic = contourpic(1+cuttop:end-cutbottom,1+cutleft:end-cutright,:);
	%cutrealbot
    %======================
	if ~isempty(CutRealBotVal) & CutRealBotVal~=0 & CutRealBotVal~=1
		contourpic(end-(CutRealBotVal+1)*20:end,:,:)=[];
		contourpic=[contourpic;ones((CutRealBotVal+1)*20+200,size(contourpic,2),3)*255];
	elseif CutRealBotVal==1 
        contourpic=[contourpic]; 
    else
        contourpic=[contourpic];  
	end
    
%smooth
%======================
elseif PotContourVal==2 
    %interpolation
    %======================
	interpmat = interp2(CalcPotTmp,4);
   	fig=figure('Visible','off','tag','invisiblefigure');
    colormap(colormatnew);
    surfmat = ones(size(interpmat));
    h = surf(surfmat,'CData',interpmat,'EdgeColor','none');
    if ~(MinAmp==0 & MaxAmp==0)  | MinAmp == MaxAmp
        set(gca,'CLim',[MinAmp MaxAmp]);
    else
        set(gca,'CLim',[-1 1]);
    end
	set(gcf,'units','points','position',[0 0 500 500],'PaperPositionMode','auto','PaperSize',[800 800]);
	set(gca,'units','normalized','position',[0 0 1 1]);
    view(0,90);
    axis equal;
	print(gcf,'-djpeg','-r0','contourplottmp.jpg');
    close(fig);
    
%     X = meshgrid(linespace(-0.15,0.15,Dim(1)));
%     Y = meshgrid(linespace(-0.1,0.1,Dim(2)));
%     Z = zeros(size(X));
%     surf(X,Y,Z);
    
    
	contourpic=imread('contourplottmp.jpg','jpg');
	contourpic = contourpic(1+cuttop:end-cutbottom,1+cutleft:end-cutright,:);
	%cutrealbot
    %======================
	if ~isempty(CutRealBotVal) & CutRealBotVal~=0 & CutRealBotVal~=1
		contourpic(end-(CutRealBotVal+1)*20:end,:,:)=[];
		contourpic=[contourpic;ones((CutRealBotVal+1)*20+200,size(contourpic,2),3)*255];
	elseif CutRealBotVal==1
        contourpic=[contourpic]; 
    else
        contourpic=[contourpic];  
	end
else
    fprintf(1,'Unknown PotContourVal %g',PotContourVal)
end

colormap(colormapold);

return

