function [SensorMatOut,CotOut]=AdjustMEGSensorMat(SensorMatIn,CotIn,RotDegVal);

%   AdjustMEGSensorMat

%   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<3; RotDegVal=0; end 
if nargin<2; return; end

%============Rotate SensorMatIn around z axis==========================
SensorMatOut=SensorMatIn;
SensorMatOut(:,1)=-1.*SensorMatIn(:,2);
SensorMatOut(:,2)=SensorMatIn(:,1);
SensorMatOut(:,4)=-1.*SensorMatIn(:,5);
SensorMatOut(:,5)=SensorMatIn(:,4);
CotOut=CotIn;
CotOut(1)=-1.*CotIn(2);
CotOut(2)=CotIn(1);
%=============Subtract center of sphere (cot) from sensor positions=====
NChan=size(SensorMatIn,1);
for ChanInd=1:NChan
	SensorMatOut(ChanInd,1:3)=SensorMatOut(ChanInd,1:3)-CotOut;
end
%=============Rotate RotDegVal degrees backward around x-axis (LPA-RPA)==
if RotDegVal~=0
    SensorMatOut(:,1:3)=XRotation(SensorMatOut(:,1:3),RotDegVal);
	SensorMatOut(:,4:6)=XRotation(SensorMatOut(:,4:6),RotDegVal);
end
%=================================================================
SensorMatOut=SensorMatOut';
return;
