function [OutFileMat]=AvgApp(AppFileMat,ValAroStatus)
%   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.                                                                      
%==================================================================
%
%	CalcApp.m
%
%	Markus Junghoefer	[1999]
%
%
%	Function definition
%	
%	[OutFileMat]=AvgApp(AppFileMat)
%
%
%
%=================================================================
if nargin<2; ValAroStatus=[]; end
if nargin<1; AppFileMat=[]; end
clc;
[ValAroStatus]=IfEmptyInputSpecVal(ValAroStatus,[1 2 3 4],2,'Analyse by','Valence [1]','Arousal [2]','Spat. Frequ. [3]','Complexity [4]');
if ValAroStatus==1	%Val
	ValAroString='Val';	
elseif ValAroStatus==2	%Aro
	ValAroString='Aro';	
elseif ValAroStatus==3	%Spat
	ValAroString='Spat';	
elseif ValAroStatus==4	%svd
	ValAroString='Svd';	
end

DefFilePath=SetDefPath(1,'*.app*');
[NFiles,AppFileMat,NonUse,BatchFilePath]=ReadFileNames(AppFileMat,DefFilePath,'Choose app. files or batch file:');
if NFiles==0; return; end
SetDefPath(2,BatchFilePath);

NPart=2;
NCalc=1;
hFig=figure('Units','normal','Position',[0 .5 .5 .5],'Name','Arousal','NumberTitle','off');

Message=char('Calc Index    :                                                 ;');
Message=char(Message,'File Index:');
Message=char(Message,'App File  : ');
Message=char(Message,'Aro File  : ');
Message=char(Message,'Ind File  : ');
Message=char(Message,'Part      : ');
Message=char(Message,'Trials    : ');
hmsgbox=msgbox(Message,'Info    :','help');

hChildMsgbox=get(hmsgbox,'Children');
set(hChildMsgbox(length(hChildMsgbox)),'Visible','off');


for FileInd=1:NFiles
	[AppFile,AppPath,AppFilePath]=GetFileNameOfMat(AppFileMat,FileInd);
	[AppMat,Version,LHeader,ScaleBins,NChan,NPoints,NTrials,SampRate,chAvgRef]=ReadAppData(AppFilePath,0);
		
	SubjectID=str2num(AppFile(1:2));
	RandStatusStr=AppFile(3);
	FSStatusStr=AppFile(4:5);
	ABStatusStr=AppFile(6);
	AroFile=['Mov',RandStatusStr,'AroMalVec'];
	AroFilePath=['BNC:Applications:MATLAB5:Geo:IAPS:',AroFile];
	AroFilePath=AroFilePath
	[AroVec,AroFile,AroPath,AroFilePath]=ReadData(AroFilePath,1,[],'ascii','ascii',[],[],'Arousal');
	
% 	if SubjectID<15 | SubjectID==16
%  		ValAroFile='AllHorHc2VisVec';
% 	else
%  		ValAroFile='AllHorHc2VisVec';
% 	end
	if SubjectID<15 | SubjectID==16
 		ValAroFile='AllSvd2';
	else
 		ValAroFile='AllSvd2';
	end
	ValAroFilePath=['BNC:Applications:MATLAB5:Geo:IAPS:',ValAroFile];
	ValAroFilePath=ValAroFilePath
	[ValAroVec,AroFile,AroPath,ValAroFilePath]=ReadData(ValAroFilePath,1,[],'ascii','ascii',[],[],ValAroString);
	
	ConFile=AppFile(1:9);
	ConFile(1:5)=AppFile(1:5);
	ConFile(6:9)='.CON';
	ConFilePath=[AppPath,ConFile]
	[ConVec,ConFile,ConPath,ConFilePath]=ReadData(ConFilePath,1,[],'ascii','ascii',[],[],'Condition',[],[],[],[],'*.CON');
	
	IndFilePath=AppFilePath(1:length(AppFilePath)-2);
	IndFilePath(length(IndFilePath)-1:length(IndFilePath))='ig';
	IndFilePath=IndFilePath
	[IndVec,IndFile,IndPath,IndFilePath]=ReadData(IndFilePath,1,[],'ascii','ascii',[],[],'Index',[],[],[],[],'*.ig');
	
	if strcmp(RandStatusStr,'N')
		if length(ConVec)~=352; 
			fprintf('length(ConVec)~=352'); return;
		end
		if strcmp(ABStatusStr,'A')
%			===========================================
%			================== A ======================

%			A => gering erregend - hoch erregend (L,H)

%			damit ist die Summe H + L
%			am geringsten fuer  H = min und  L = min == d1
%			am groessten  fuer  H = max und  L = max == d4

%			damit ist die Differenz H - L
%			am groessten positiv fuer  H >> L == d4
%			am geringsten positiv fuer H ~= L == d1

%			As1 => lL : lH
%			As4 => hL : hH
%			Ad1 => hL : lH
%			Ad4 => lL : hH
			ValAroVec2=ValAroVec([2:2:704]);
			ValAroVec1=ValAroVec([1:2:703]);
	elseif strcmp(ABStatusStr,'B')
%			===========================================
%			================== B ======================

%			B => hoch erregend - gering erregend (H,L)

%			damit ist die Summe H + L
%			am geringsten fuer  H = min und  L = min == d1
%			am groessten  fuer  H = max und  L = max == d4

%			damit ist die Differenz L-H
%			am groessten negativ fuer  H >> L == d1
%			am geringsten negativ fuer H ~= L == d4

%			Bs1 => lH : lL
%			Bs4 => hH : hL
%			Bd1 => hH : lL
%			Bd4 => lH : hL
			ValAroVecTmp=zeros(705,1); % da BatchIAPS fuer B von -42 bis 41 geht und Bild 0 somit nicht definiert ist
			ValAroVecTmp(2:705)=ValAroVec;
			ValAroVec=ValAroVecTmp;
			
			ValAroVec2=ValAroVec([2:2:704]);
			ValAroVec1=ValAroVec([1:2:703]);
			
			%Do not use first trial if A even if in Ind file; 
			NotOneIndVec=find(IndVec-1);
	 		IndVec=IndVec(NotOneIndVec);	
 		end
	elseif strcmp(RandStatusStr,'R')
		ValAroVecIndVec=ones(704,1);
		if strcmp(ABStatusStr,'A')
 			ValAroVecIndVec(1:2)=[0 0];
		elseif strcmp(ABStatusStr,'B')
 			ValAroVecIndVec(1)=0;
		end
		if strcmp(FSStatusStr,'06')
			if length(ConVec)==352; 
				ConVec=ConVec(1:length(ConVec)-1);
			end
			if IndVec(length(IndVec))==352; 
				IndVec=IndVec(1:length(IndVec)-1);
			end
			ValAroVec=ValAroVec(find(ValAroVecIndVec));
			ValAroVec2=ValAroVec([2:2:702]);
 			ValAroVec1=ValAroVec([1:2:701]);
		elseif strcmp(FSStatusStr,'10')
			ValAroVecIndVec([407 410 413 416])=zeros(4,1);	%Trigger in Rand nur alle drei Bilder => responses auf Bilder 407, 410, 413 und 416 wurden nicht detektiert
			ValAroVec=ValAroVec(find(ValAroVecIndVec));
			Test=length(ValAroVec)
			if length(ConVec)~=349; 
				fprintf('length(ConVec)~=349'); return;
			end
			ValAroVec2=ValAroVec([2:2:698]);
 			ValAroVec1=ValAroVec([1:2:697]);
		end
	end
	
%	===========================================
%	===========================================
% test=ValAroVec2-ValAroVec1
% return
% 

	ValAroVec2=ValAroVec2(IndVec);
	ValAroVec1=ValAroVec1(IndVec);

	DiffValAroVec=ValAroVec2-ValAroVec1;
	SumValAroVec=ValAroVec2+ValAroVec1;
	

	for CalcInd=1:NCalc
		if ValAroStatus==1	%Val
			if CalcInd==1
				CalcString='vd';
				ValAroVec=DiffValAroVec;
			else
				CalcString='vs';
				ValAroVec=SumValAroVec;
			end
		elseif ValAroStatus==2	%Aro
			if CalcInd==1
				CalcString='ad';
				ValAroVec=DiffValAroVec;
			else
				CalcString='as';
				ValAroVec=SumValAroVec;
			end
		elseif ValAroStatus==3	%Spat
			if CalcInd==1
				CalcString='hcd';
				ValAroVec=DiffValAroVec;
			else
				CalcString='hcs';
				ValAroVec=SumValAroVec;
			end
		elseif ValAroStatus==4	%svd
			if CalcInd==1
				CalcString='svdd';
				ValAroVec=DiffValAroVec;
			else
				CalcString='svds';
				ValAroVec=SumValAroVec;
			end
		end
		[SortValAroVec,SortAroIndVec]=sort(ValAroVec);
		
		NValAroVec=length(ValAroVec);
		NTrials2Avg=floor(NValAroVec./NPart);
		App3dMat=zeros(NTrials2Avg,NChan,NPoints);
	
		for PartInd=1:NPart
		
			[AvgFilePath]=PutFileExt2Mat(AppFilePath,['at',CalcString,int2str(NPart),'.'int2str(PartInd),'.ar'],4);
			[AvgFile,AvgPath]=SepFilePath(AvgFilePath);
			
			Message=char(['Calc Index: ',num2str(CalcInd),' of ',num2str(NCalc)]);
			Message=char(Message,['File Index: ',num2str(FileInd),' of ',num2str(NFiles)]);
			Message=char(Message,['App File  : ', AppFile]);
			Message=char(Message,['Aro File  : ',AroFile]);
			Message=char(Message,['Ind File  : ',IndFile]);
			Message=char(Message,['Avg File  : ',AvgFile]);
			Message=char(Message,['Part      : ',num2str(PartInd)]);
			Message=char(Message,['Trials    : ',num2str(NTrials2Avg)]);
			set(hChildMsgbox(1),'String',Message);	
       		pause(.01);
		% 	NTrials2Avg=PartInd.*25;

			SortSortAroIndVec=sort(SortAroIndVec((PartInd-1).*NTrials2Avg+1:PartInd.*NTrials2Avg));	
			
			plot(ValAroVec)
			hold on
			plot(SortSortAroIndVec,ValAroVec(SortSortAroIndVec),'*r')
			hold off
			pause(.1)
	
 			for TrialInd=1:NTrials2Avg
				SpecTrial=SortSortAroIndVec(TrialInd);
				ValAro2=ValAroVec2(SpecTrial);
				ValAro1=ValAroVec1(SpecTrial);
				ValAro=ValAroVec(SpecTrial);
				if CalcInd==1
					fprintf('%g of %g trials; Diff = ValAro2 - ValAro1; %g = %g - %g ; %g of %g trials done ! Spec. trial: %g \n',TrialInd,NTrials2Avg,ValAro,ValAro2,ValAro1,TrialInd,NTrials2Avg,SpecTrial)
				else
					fprintf('%g of %g trials; Sum = ValAro1 + ValAro2; %g = %g - %g ; %g of %g trials done ! Spec. trial: %g \n',TrialInd,NTrials2Avg,ValAro,ValAro1,ValAro2,TrialInd,NTrials2Avg,SpecTrial)
				end	
				[AppMat,Version,LHeader,ScaleBins,NChan,NPoints,NTrials,SampRate,chAvgRef]=ReadAppData(AppFilePath,SpecTrial);
				App3dMat(TrialInd,:,:)=AppMat;
			end
			AvgMat=mean(App3dMat);
			StdMat=std(App3dMat);
			SaveAvgFile(AvgFilePath,AvgMat,ones(NChan,1).*NTrials2Avg,StdMat,SampRate,ones(NChan,1).*NTrials2Avg,ones(NChan,1).*NTrials2Avg);
		end %NPart
	end %NFiles
end %NCalc
return;
