%==================================================================
%
%	CalcWeightEditMat.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 [WeightEditMat,SumWeightEditMat,ChanEditStatusMat,WeightEditFilePath,WeightTrialStatus] = ...
	               CalcWeightEditMat(DataFilePath,NChan,NTrials,EditMatStatus,...
				   AbsEditMat,AbsThresVec,AbsTFMat,...
  				   StdEditMat,MaxStdThresVec,MinStdThresVec,StdTFMat,...
 				   TraEditMat,TraThresVec,TraTFMat,...
				   FlaEditMat,ch_ThetaCorr,ch_NoiseCorr,ch_CalcAvgRef)

%
%	Dieses Programm berechnet die NChan * NTrials Weight Matrix.
%	Sie kann zur Gewichtung der einzelnen Kanaele eines jeden Trials im spaeteren Mittelungsprozess verwendet werden.
%	
%=================================================================

if any(EditMatStatus==1)		
	WeightEditMat=ones(NChan,NTrials);		%Die weight Matrix ist per default eine Ones Matrix =>alle Kanaelw in allen trials wuerden genutzt
	ChanEditStatusMat=zeros(NChan,NTrials);	%Dies ist die Status Matrix, um die farbliche Kennzeichnung der Kanaele im Edit Menue zu bstimmen
											%0 falls der Kanal o.k ist
											%1 falls der Kanal auf Grund einer flat line nicht gewertet wird. 
											%2 falls der Kanal in Bezug zur absoluten Groesse schlecht gewertet wird. 
											%3 falls der Kanal in Bezug zur transit Groesse schlecht gewertet wird. 
											%4 falls der Kanal in Bezug zur std Groesse schlecht gewertet wird. 
											%5 falls 2 und 3, 6 falls 2 und 4 etc.
	if ch_NoiseCorr
		NoiseVec=zeros(1,NChan);
	else
		NoiseVec=ones(1,NChan);
	end


	if EditMatStatus(1)==1
		
		if ch_NoiseCorr
			NoiseVec=AbsTFMat(2,:);
		end
		[Size1,Size2]=size(AbsThresVec);
		if Size1==1 & Size2==NChan; AbsThresVec=AbsThresVec'; end
		for TrialInd=1:NTrials
			BadChanVec=find(AbsEditMat(:,TrialInd)>AbsThresVec);
			WeightEditMat(BadChanVec,TrialInd)=zeros(length(BadChanVec),1);
			%	Wird fuer jeden einzelnen guten Kanal pro Trial um 1 groesser 
			ChanEditStatusMat(BadChanVec,TrialInd)=2.*ones(size(BadChanVec));
		end
	end
	if EditMatStatus(2)==1
		if ch_NoiseCorr
			NoiseVec=NoiseVec+StdTFMat(2,:);
		end
		[Size1,Size2]=size(MaxStdThresVec);
		if Size1==1 & Size2==NChan; MaxStdThresVec=MaxStdThresVec'; end
		[Size1,Size2]=size(MinStdThresVec);
		if Size1==1 & Size2==NChan; MinStdThresVec=MinStdThresVec'; end
		for TrialInd=1:NTrials
			BadChanVec=find(StdEditMat(:,TrialInd)>MaxStdThresVec | StdEditMat(:,TrialInd)<MinStdThresVec);
			WeightEditMat(BadChanVec,TrialInd)=zeros(length(BadChanVec),1);
			ChanEditStatusMat(BadChanVec,TrialInd)=3.*ones(size(BadChanVec))+ChanEditStatusMat(BadChanVec,TrialInd);
		end
	end
	if EditMatStatus(3)==1
		if ch_NoiseCorr
			NoiseVec=NoiseVec+TraTFMat(2,:);
		end
		[Size1,Size2]=size(TraThresVec);
		if Size1==1 & Size2==NChan; TraThresVec=TraThresVec'; end
		for TrialInd=1:NTrials
			BadChanVec=find(TraEditMat(:,TrialInd)>TraThresVec);
			WeightEditMat(BadChanVec,TrialInd)=zeros(length(BadChanVec),1);
			ChanEditStatusMat(BadChanVec,TrialInd)=4.*ones(size(BadChanVec))+ChanEditStatusMat(BadChanVec,TrialInd);
		end
	end
	
	if EditMatStatus(4)==1
		if any(EditMatStatus(1:3)==1)
			WeightEditMat=WeightEditMat.*FlaEditMat;
		else
			WeightEditMat=FlaEditMat;
		end
		[j,k]=find(FlaEditMat==0);
		for i=1:length(j)
			ChanEditStatusMat(j(i),k(i))=1;
		end
	end
	
	SumWeightEditMat=sum(WeightEditMat);							%Dies ist die Summe ueber alle NChan und daher NTrials lang
	MinSumWeightEditMat=min(SumWeightEditMat);
	MaxSumWeightEditMat=max(SumWeightEditMat);
	MedSumWeightEditMat=median(SumWeightEditMat);
	MeanSumWeightEditMat=mean(SumWeightEditMat);
	fprintf(1,'Median of number of good channels per trial:  %g\n',MedSumWeightEditMat)
	fprintf(1,'Mean    of number of good channels per trial:  %g\n',MeanSumWeightEditMat)
	again=1;FirstPlot=1;
	MinWeightEdit=.9.*MaxSumWeightEditMat;
	while again
		GoodTrials=find(SumWeightEditMat>MinWeightEdit);  NGoodTrials=length(GoodTrials);
		BadTrials=find(SumWeightEditMat<=MinWeightEdit);  NBadTrials=length(BadTrials);
		WeightTrialStatus=zeros(NTrials,1);
		WeightTrialStatus(GoodTrials)=ones(NGoodTrials,1);
	
		fprintf(1,'Number of bad trials with this MinWeightEdit: %g\n',NBadTrials)
		fprintf(1,'Number of good trials with this MinWeightEdit: %g\n\n\n',NGoodTrials)
		if FirstPlot
			HistFig=figure('Units','normal','NumberTitle','off','Position',[.666,0,.333,.333],'Name','Hist of SumWeightEditVec');
			FirstPlot=0;
			x=[MinSumWeightEditMat:MaxSumWeightEditMat];
			[n,x]=hist(SumWeightEditMat,x);
			[xb,yb]=bar(x,n);
			plot(xb,yb)
			hold on
			plot([xb(1) xb(length(xb))], [0 0],'w--')
			if x(1)<x(length(x)) & max(yb)>0
				axis([x(1) x(length(x)) 0 max(yb)])
			end
			hMinWeightEditLine=line('XData',[MinWeightEdit MinWeightEdit],'YData',[ 0 max(yb)],'Color','r','LineStyle','--');
		end
		
		[XHoriz,YVert]=ginput(1);
		if YVert<0
			again=0;
			close(HistFig);
		else
			MinWeightEdit=XHoriz;		
			set(hMinWeightEditLine,'XData',[MinWeightEdit MinWeightEdit]);
		end
	end
	if ch_CalcAvgRef
		WeightEditFilePath=[DataFilePath '.WE.AR'];
	else
		WeightEditFilePath=[DataFilePath '.WE'];
	end
	fprintf('\n');clc; fprintf('Save this averaged data to file:\n\n'); fprintf(WeightEditFilePath); fprintf('\n\n'); 
	[ch_UseDefFileName]=IfEmptyInputBo(['Do you want to take this default file name ? Y/N'],[],[],1);
	if ~ch_UseDefFileName; WeightEditFilePath=[]; end
	SaveWeightEditMat=zeros(NChan,NTrials+1);
	SaveWeightEditMat(:,1:NTrials)=WeightEditMat;
	SaveWeightEditMat(:,NTrials+1)=NoiseVec';
	[WeightEditFilePath] = SaveData(SaveWeightEditMat,WeightEditFilePath,1);
else
	WeightEditMat=[];
	SumWeightEditMat=[];
	ChanEditStatusMat=zeros(NChan,NTrials);
	WeightEditFilePath=[];
	WeightTrialStatus=ones(NTrials,1);
end
return;
