%% 	comments
%	sConfig - Struct mit Konfigurationsdaten, die für das Projekt benutzt werden sollen
%       sConfig.avBlockType - bestimmter Blocktyp, der gesucht werden soll (Im Beispiel BusCreator bzw. BusSelector)
%	strModelName - .mdl-Datei, die zu öffnen ist
%%

%set working model
load_system(strModelname)
%get line handles
avModelLineHandle = find_system(gcs,'FindAll','on','Type','line');
%get block type
for nBlockType = 1:length(sConfig.avBlockType),
%set port direction variable
	switch sConfig.avBlockType{nBlockType}
	case 'BusCreator',
	PortDir = ('Inport');
	case 'BusSelector',
	PortDir = ('Outport');
end
%get lines and parameters concurrent to specified block
for nBlock = 1:length(sWork.avBlockList{nBlockType}),
	%get line handles of current block
	avBlockLineHandles = get_param(sWork.avBlockList{nBlockType}{nBlock}, 'LineHandles');
	%get number of port direction    
	for nPort = 1:length(avBlockLineHandles.(PortDir)),
		%get line handle (nPort = line, nBlockType = row)
		avLinePortHandles{nPort, nBlockType} = avBlockLineHandles.(PortDir)(nPort);
		%get line name (nPort = line, nBlockType = row)
		avLineNames{nPort, nBlockType} = get_param(avLinePortHandles{nPort, nBlockType},'Name'); 
		%delete old line connections and connect blocks 
		for nLine = 1:length(avModelLineHandle)
			%check wether a model line fits to a specified block line
			if (avLinePortHandles{nPort, nBlockType} == avModelLineHandle(nLine)),
				%get block and port handles to determine block src/dst block name and port number
				switch sConfig.avBlockType{nBlockType},
					case 'BusCreator'
					avBlockHandle = get_param(avModelLineHandle(nLine), 'SrcBlockHandle');
					avPortHandle  = get_param(avModelLineHandle(nLine), 'SrcPortHandle');                                    
					case 'BusSelector'
					avBlockHandle = get_param(avModelLineHandle(nLine), 'DstBlockHandle');
					avPortHandle  = get_param(avModelLineHandle(nLine), 'DstPortHandle');                                        
				end
				%get name and port number of connected block
				avBlockNames  = get_param(avBlockHandle, 'Name');
				avPortNumbers = get_param(avPortHandle, 'PortNumber');
				%delete selected line
				delete_line(avModelLineHandle(nLine));
				%add_line to new block by blockname
				switch sConfig.avBlockType{nBlockType}
					case 'BusCreator'
					add_line(gcs,([avBlockNames,'/',num2str(avPortNumbers)]),([avLineNames{nPort, nBlockType},'/1']), 'autorouting','on')
					case 'BusSelector'
					add_line(gcs,([avLineNames{nPort, nBlockType},'/1']),([avBlockNames,'/',num2str(avPortNumbers)]), 'autorouting','on')
					end
				%jump out of loop, because only one line can fit
				break;  
			end 
			end
		end                
	end
end
%save system
save_system(gcs);