function [AMat]=MinNorm2Analyse(MMat,DipPos,FilePath,ResultPath)
%   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<4; ResultPath=[]; end
if nargin<3; FilePath=[]; end
if nargin<2; DipPos=[]; end
if nargin<1; MMat=[]; end

Dim=[51 51 51];
AMat=zeros(Dim);
Vox=[4 4 4];
Type=4;
Offset=0;
Origin=[25 28 25];
Descrip='spm_compatible';
Interp2Str='cubic';
[NDip,NPoints]=size(MMat);
if NPoints>1
	MMat=mean(MMat,2);
	fprintf(1,'Calculate mean of MinNorm matrix ...\n')
end
if isempty(DipPos)
	if NDip==655
		NShells=4;
	else
		NShells=1;
	end
	DLocFilePath=which(['DLoc_',int2str(NDip),'_',int2str(NShells),'_Cart.ascii']);
	DipPos=ReadData(DLocFilePath,1,[],'ascii','ascii')';
end
DipRad=sqrt(DipPos(:,1).^2+DipPos(:,2).^2+DipPos(:,3).^2);
DipPos(:,1)=DipPos(:,1).*0.81;
DipPos(:,2)=DipPos(:,2).*1.05;
DipPos(:,3)=DipPos(:,3).*0.85;
DipPos=round(DipPos.*250)+25;
MaxMaxMMat=max(max(MMat));
MaxVal=2.^16./2-1;
Scale=MaxMaxMMat./MaxVal;
MMat=MMat./Scale;
MaxMax=max(max(MMat));
fprintf(1,'\n');
fprintf(1,'Maximum Value: %g\n',MaxMaxMMat);
fprintf(1,'Scale:         %g\n',Scale);
for i=1:NDip
	AMat(DipPos(i,1),DipPos(i,2),DipPos(i,3))=MMat(i);%.*DipRad(i).^-2);
end
if MaxMax<100
    Message=char('Warning: Bad scaling writing integer16 analyse file !!!');
    Message=char(Message,['Maximum Value: ',num2str(MaxMax)]);
    Message=char(Message,['Scale:         ',num2str(Scale)]);
    hmsgbox=msgbox(Message,'Warning','warn');
    fprintf(1,'\n')
    fprintf(1,'Warning: Bad scaling writing integer16 analyse file !!! \n')
	fprintf(1,'Maximum Value: %g\n',MaxMax);
    fprintf(1,'Scale:         %g\n',Scale);
end
if isempty(FilePath)
	Path=pwd;
	File=['fEEG000'];
	FilePath=[Path,filesep,File];
end
if ~isempty(ResultPath)
    [File,Path]=SepFilePath(FilePath);
	FilePath=[ResultPath,filesep,File];
end
fprintf(1,'Write analyse formated data to file:\n')
disp(FilePath)
fprintf(1,'\n')

[s]=spm_hwrite([FilePath,'.hdr'],Dim,Vox,Scale,Type,Offset,Origin,Descrip);
fid=fopen([FilePath,'.img'],'w','l');
fwrite(fid,AMat,'int16');
fclose(fid);
return;
