function [OutFileMat]=AvgAppLH(AppFileMat,ValAroStatus)

%	AvgAppLH.m

%   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; ValAroStatus=[]; end
if nargin<1; AppFileMat=[]; end

clc;
[ValAroStatus]=IfEmptyInputSpecVal(ValAroStatus,[1 2],2,'Analyse by','Valence [1]','Arousal [2]');
if ValAroStatus==1	%Val
	ValAroString='Val';	
elseif ValAroStatus==2	%Aro
	ValAroString='Aro';	
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=4;
NCalc=2;
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);
	ValAroFile=['Mov',RandStatusStr,ValAroString];
	if SubjectID<15 | SubjectID==16
 		ValAroFile=[ValAroFile,'FemVec'];
	else
		ValAroFile=[ValAroFile,'MalVec'];
	end
	ValAroFilePath=['BNC:Applications:MATLAB5:Geo:IAPS:',ValAroFile];
	
	[ValAroVec,ValAroFile,ValAroPath,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
	
%	===========================================
%	===========================================
	
 	MeanValAroVec=mean(mean(ValAroVec1),mean(ValAroVec2));
% 	NTrials2Avg=0;
% 	NTrials2AvgDef=50;
% 	Int=0;
% 	while NTrials2Avg<NTrials2AvgDef
% 		Int=Int+.1;
% 		HL=MeanValAroVec+4-Int
% 		LL=MeanValAroVec-4+Int
% 		LHIndVec=find(ValAroVec2>HL & ValAroVec1<LL);
% 		NTrials2Avg=length(LHIndVec)
% 		plot(ValAroVec1)
% 		hold on
% 		plot(ValAroVec2,'r')
% 		plot([0 length(ValAroVec1)],[HL HL],'--')
% 		plot([0 length(ValAroVec1)],[LL LL],'--')
% 		pause(.1)
% 		hold off
% 	end
% 	
	HL=6;
	LL=4;
	ValAroVec1=ValAroVec1(IndVec);
	ValAroVec2=ValAroVec2(IndVec);
% 	Test1=find(ValAroVec1>HL)
% 	length(Test1)
% 	Test2=find(ValAroVec2<LL)
% 	length(Test2)

	for LHIndex=1:2
		if strcmp(RandStatusStr,'N')
			if LHIndex==1
				if strcmp(ABStatusStr,'A')
					LHIndVec=find(ValAroVec1>MeanValAroVec-.5 & ValAroVec1<MeanValAroVec+.5 & ValAroVec2>HL);
				elseif strcmp(ABStatusStr,'B')
					LHIndVec=find(ValAroVec2>MeanValAroVec-.5 & ValAroVec2<MeanValAroVec+.5 & ValAroVec1>HL);
				end
				[AvgFilePath]=PutFileExt2Mat(AppFilePath,['atvmh.ar'],4);
			elseif LHIndex==2
				if strcmp(ABStatusStr,'A')
					LHIndVec=find(ValAroVec1>MeanValAroVec-.5 & ValAroVec1<MeanValAroVec+.5 & ValAroVec2<LL);
				elseif strcmp(ABStatusStr,'B')
					LHIndVec=find(ValAroVec2>MeanValAroVec-.5 & ValAroVec2<MeanValAroVec+.5 & ValAroVec1<LL);
				end
				[AvgFilePath]=PutFileExt2Mat(AppFilePath,['atvml.ar'],4);
			end
		elseif strcmp(RandStatusStr,'R')
			if LHIndex==1
				LHIndVec=find(ValAroVec1<LL & ValAroVec2>HL);
				[AvgFilePath]=PutFileExt2Mat(AppFilePath,['atvlh.ar'],4);
			elseif LHIndex==2
				LHIndVec=find(ValAroVec2<LL & ValAroVec1>HL);
				[AvgFilePath]=PutFileExt2Mat(AppFilePath,['atvhl.ar'],4);
			end		
		end
		plot(ValAroVec1,'--')
		hold on
		plot(ValAroVec2,'--r')
		plot(LHIndVec,ValAroVec1(LHIndVec),'*b')
		plot(LHIndVec,ValAroVec2(LHIndVec),'*r')
		hold off
		pause(.1)
		
		NTrials2Avg=length(LHIndVec);
		App3dMat=zeros(NTrials2Avg,NChan,NPoints);
		[AvgFile,AvgPath]=SepFilePath(AvgFilePath);
			
		for TrialInd=1:NTrials2Avg
			SpecTrial=LHIndVec(TrialInd);
			fprintf('%g of %g trials done ! Spec. trial: %g \n',TrialInd,NTrials2Avg,SpecTrial)
			[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
end
