%==================================================================
%
%	DefinePattern.m
%
%	Markus Junghoefer	[1996]
%   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.                                                                      
%
%
%	Function definition
%
%

	function[Pattern,ch_Pattern]=DefinePattern(Pattern,ch_Pattern,ch_TakeOrCreate,...
									PatternFilePath,PatternPattern,ch_TakeKind,...
									PatternLength,ch_Graph,ch_NormKind,ch_Again,ch_Save);

%==================================================================
if nargin<11; ch_Save=[]; end
if nargin<10; ch_Again=[]; end
if nargin<9; ch_NormKind=[]; end
if nargin<8; ch_Graph=[]; end
if nargin<7; PatternLength=[]; end
if nargin<6; ch_TakeKind=[]; end
if nargin<5; PatternPattern=[]; end
if nargin<4; PatternFilePath=[]; end
if nargin<3; ch_TakeOrCreate=[]; end
if nargin<2; ch_Pattern=[]; end
if nargin<1; Pattern=[]; end

if PatternLength<2
	fprintf('Do not use DefinePattern because length of pattern < 2 !');
	Pattern=1;
	ch_Pattern=0;
	return;
end
[ch_Pattern]=IfEmptyInputBo(['Do you want to define a pattern ? Y/N'],[],ch_Pattern,1,1);
if ~ch_Pattern; return; end

fprintf('\n'); clc;
fprintf('Define a pattern:\n\n\n');
[ch_TakeOrCreate]=IfEmptyInputSpecVal(ch_TakeOrCreate,[1 2],2,...
					['Do you want to choose an existing file           [1]'],...
					['or do you want to create a file                    	[2]']);

%========================================================================

if ch_TakeOrCreate==1
	
	[Pattern,PatternFile,PatternPath] = ReadData(PatternFilePath,1,[],['int16'],['float32']);
	hfig=figure('Units','normal','NumberTitle','off','Position',[0,0.5,0.5,0.5],'Name','Read in Pattern:');
	plot(Pattern)
	pause
	close(hfig);
	
elseif ch_TakeOrCreate==2
	
	%========================================================================
	fprintf('\n'); clc;
	fprintf('Start to define pattern:\n\n\n')
	fprintf('Do you want to\n\n')
	if isempty(PatternPattern)
		[ch_TakeKind]=IfEmptyInputSpecVal(ch_TakeKind,[1 2 3],3,...
		['define a boxcar as pattern                             [1]'],...
		['insert a special function or                           [2]'],...
		['insert the pattern graphically ?                       [3]']);
	else
		[NChanPattern,NPointsPattern]=size(PatternPattern);
		if NChanPattern==1
			[ch_TakeKind]=IfEmptyInputSpecVal(ch_TakeKind,[1 2 3 4],3,...
			['define a boxcar as pattern                           [1]'],...
			['insert a special function                            [2]'],...
			['insert the pattern graphically or                    [3]'],...
			['choose a part of the given vector as pattern ?       [4]']);
		else
			[ch_TakeKind]=IfEmptyInputSpecVal(ch_TakeKind,[1 2 3 4],4,...
			['define a boxcar as pattern                                        [1]'],...
			['insert a special function                                         [2]'],...
			['insert the pattern graphically or                                 [3]'],...
			['choose a part of the given matrix as pattern ?                    [4]']);
		end
	end
	if ch_TakeKind~=4
		[PatternLength]=IfEmptyInputVal(['Please insert the length of the pattern:'],[],PatternLength,250,1);
	end
	if ch_TakeKind==1
		Pattern=ones(PatternLength,1);
	elseif ch_TakeKind==2
		fprintf('\n');clc;
		fprintf('\n')
		fprintf('Please choose your special calculation file:\n\n');
		fprintf('(like CalcCalcPattern)');pause(1);
		[CalcFileTmp,CalcPath,CalcFilePath]=ReadFilePath([],[],['Choose File:']);
		Pattern=[1:PatternLength];
		CalcFile=[]; CalcFile=CalcFileTmp(1:length(CalcFileTmp)-2);
		eval(['Pattern=' CalcFile '(Pattern);'])
		[Pattern]=norm_1(Pattern,[],2);
		fprintf('\n');clc;
		[Pattern] = CalcFrequWin(Pattern);
		figure('Units','normal','NumberTitle','off','Position',[0,0.5,0.5,0.5],'Name','Define Pattern:');
		plot([1:PatternLength],zeros(1,PatternLength),'--w')
		hold on
		plot([1:PatternLength],Pattern,'--m')	
		axis([1 PatternLength -1 1])
	elseif ch_TakeKind==3
		[ch_Graph,k]=IfEmptyInputSpecVal(ch_Graph,[1 2],1,...
		'Do you want to use\n',...
		'Polyfit or           [1]',...
		'Direct               [2]');
		figure('Units','normal','NumberTitle','off','Position',[0,0.5,0.5,0.5],'Name','Define Pattern:');
		Pattern=[1:PatternLength];
		Again=1;
		while Again
			x=[];y=[];yi=[];p=[];f=[];clf;Stop=0;Index=0;
			while ~Stop
				Index=Index+1;
				plot(zeros(1,PatternLength),'--w')
				axis([1 PatternLength -1 1])	
				[xTmp,yTmp]=ginput(1);
				clf;
				plot(zeros(1,PatternLength),'--w')
				axis([1 PatternLength -1 1])	
				if xTmp>PatternLength | xTmp<1 | yTmp<-1 | yTmp>1; 
					Stop=1;
				else
					hold on
					x(Index)=round(xTmp);
					y(Index)=yTmp;
					plot(x,y,'om');
					hold on	
					if Index>3
						if ch_Graph==1
							if Index<9; PolyInd=Index-1; else; PolyInd=8; end
							p=polyfit(x,y,PolyInd);
							f=polyval(p,x);
						else
							f=y;
							x=x;
						end
						plot(x,f,'-y');
					end
					axis([1 PatternLength -1 1])	
				end
			end
			clf;
			Pattern=spline(x,f,[1:PatternLength]);
			plot([1:PatternLength],Pattern,'--m')
			hold on
			plot(x,f,'om');
			plot([1:PatternLength],zeros(1,PatternLength),'--w')
			axis([1 PatternLength -1 1]);
			if ch_NormKind~=0
				[Pattern,NormStatus]=norm_1(Pattern,ch_NormKind,2);
				[x,status]=norm_1(x,NormStatus);
				[Pattern] = CalcFrequWin(Pattern)
			end
			clf;
			plot([1:PatternLength],Pattern,'--m');
			hold on
			plot(x,f,'om');
			plot([1:PatternLength],zeros(1,PatternLength),'--w')
			axis([1 PatternLength -1 1])
			[Again]=IfEmptyInputBo(['Again ? Y/N'],[],ch_Again,1,1);
		end
	elseif ch_TakeKind==4
		Ok=0;
		while ~Ok
			clf;
			x=[];
			if NChanPattern>1
				
				hfig1=figure('Units','normal','NumberTitle','off','Position',[0,0.5,0.5,0.5],'Name','Choose a trial:');
				fprintf('\n');clc;fprintf('Please choose the pattern you want to take:');
				pause(2);ch_Take=0;
				NChanIndex=0;
				while ch_Take==0
					NChanIndex=NChanIndex+1;
					if NChanIndex>NChanPattern; NChanIndex=1; end
					plot(PatternPattern(NChanIndex,:))
					fprintf('\n');clc;
					fprintf(1,'This is the %g trial in this cell !\n',NChanIndex)
					[ch_Take]=IfEmptyInputBo(['Do you want to take this trial ?'],[],[],0,0);
				end
				PatternPatternTmp=PatternPattern(NChanIndex,:); PatternPattern=[]; PatternPattern=PatternPatternTmp; PatternPatternTmp=[];
			end
			
			[PattPlotStart]=IfEmptyInputValInt('Please insert the start of the plot intervall:',[],[],1,1,length(PatternPattern)-1,1);
			[PattPlotEnd  ]=IfEmptyInputValInt('Please insert the end of the plot intervall:',[],[],length(PatternPattern),PattPlotStart+1,length(PatternPattern));

			fprintf('\n');clc;fprintf('Please insert start and end of pattern intervall:');
			hfig2=figure('Units','normal','NumberTitle','off','Position',[0,0.5,0.5,0.5],'Name','Choose a pattern:');
			PlotPatternPattern=PatternPattern(PattPlotStart:PattPlotEnd);
			plot(PlotPatternPattern)
			hold on
			for i=1:2
				[xTmp,yTmp]=ginput(1);
				x(i)=round(xTmp);
				plot(x,PlotPatternPattern(x),'mo');
			end
			[x(1)]=IfEmptyInputValInt(['Start of pattern to calculate:'],[],...
											  [],x(1),1,length(PlotPatternPattern)-1,1);
			[x(2)]=IfEmptyInputValInt(['End of pattern to calculate:'],[],...
											  [],x(2),x(1)+1,length(PlotPatternPattern),1);
			[Ok]=IfEmptyInputBo(['Ok ? Y/N'],[],[],1,1);
			close(hfig1); close(hfig2); 
		end
		Pattern=[PlotPatternPattern(x(1):x(2))];
	end
	[ch_Save]=IfEmptyInputBo(['Do you want to'],['save this chosen pattern ? Y/N'],ch_Save,1,1);
	SaveData(Pattern,[],ch_Save,['Save Pattern to file...'],['int16'],['float32']);
end

%==============================================================================================

return;


