function[NMegChan,PmgSetFilePath]=WritePmgSet(SetFilePath,PmgFilePath)
%   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.                                                                      
%==================================================================
%
%	WritePmgSet.m
%
%	Markus Junghoefer	[2000]
%
%
%	
%	Function definition	
%=================================================================
if nargin<2; PmgFilePath=[]; end
if nargin<1; SetFilePath=[]; end
File=[];
Path=[];
String='Choose MSI set file:';
[DefPath]=SetDefPath(1,'*.set');
[SetFile,SetPath,SetFilePath]=ReadFilePath(SetFilePath,DefPath,String);
SetDefPath(2,SetPath);
if SetFile==0; MsiFilePath=[]; return; end
if exist(SetFilePath,'file')~=2
	Message=char('Sorry,');
	Message=char(Message,'unable to find MSI set file:');
	Message=char(Message,'');
	Message=char(Message,[OldSetFilePath]);
	Message=char(Message,'');
	hmsgbox=msgbox(Message,'Info','help'); 
	return;
end
if isempty(PmgFilePath)
	PmgFilePath=[SetFilePath,'.pmg'];
end

SetFid=fopen(SetFilePath,'rt');
PmgFid=fopen(PmgFilePath,'wt');
NMegChanKeyword='MSI.SigAChanCount:'
BeginKeyword='MSI.Position_Information.Begin:'
while feof(SetFid) == 0
   	Line=fgetl(SetFid);
	Matches=findstr(Line,NMegChanKeyword);
	Num=length(Matches);
	if Num>0
		TestLine=sprintf(['%s\t%%d'],NMegChanKeyword);
	    NMegChan=sscanf(Line,TestLine,1);
    end
    Matches=findstr(Line,BeginKeyword);
	Num=length(Matches);
	if Num>0
        for ChanInd=1:NMegChan
            Line=fgetl(SetFid);
            fprintf(PmgFid,'%s\n',Line);
		end
    end
end
fclose(SetFid);
fclose(PmgFid);
return;
