function dummy = drawdiagram(LoopData)
%DRAWDIAGRAM  Draws Simulink diagram for SISO Tool feedback loop.

%   Author(s): K. Gondoly and P. Gahinet
%   Copyright 1986-2000 The MathWorks, Inc. 
%   $Revision: 1.4 $  $Date: 2000/06/14 20:18:25 $

% REVISIT
dummy = [];

%---Check if the User has Simulink
if exist('simulink'),
    Answer = questdlg(...
        {'Before the diagram can be drawn, the plant and '
        'compensator data must be exported to the workspace.'
        ' '
        'The data will be stored in the variable names used' 
        'in the SISO Tool and may overwrite data currently '
        'in the Workspace.'
        ' '
        'Do you wish to continue?'},...
        'Drawing Simulink Diagrams','Yes','No','Yes');
    if strcmp(Answer,'Yes')
        LocalDrawDiagram(LoopData)
    end
else
    WarnStr = {'Simulink must be included in your MATLAB path before',...
            'requesting a Simulink diagram of the closed-loop system'};
    warndlg(WarnStr,'SISO Tool Warning');
end 

%----------------- Local functions -----------------

%%%%%%%%%%%%%%%%%%%%%%%%
%%% LocalDrawDiagram %%%
%%%%%%%%%%%%%%%%%%%%%%%%
function LocalDrawDiagram(LoopData)

WatchFig = watchon;

% Find adequate name for new diagram
AllDiagrams = find_system('Type','block_diagram');
DiagramName = LoopData.SystemName;
if ~isempty(AllDiagrams)
   %---Look first for an exact match
   ExactMatch = strmatch(DiagramName,AllDiagrams,'exact');
   if ~isempty(ExactMatch)
      DiagramName = sprintf('%s_',DiagramName);
      % Look for an available name of the form DiagramName_xxx
      UsedInds = strmatch(DiagramName,AllDiagrams);
      if ~isempty(UsedInds)
         %---Look for minimum available number to use
         UsedNames = strvcat(AllDiagrams{UsedInds});
         %---Weed out names that don't end in scalar values.
         strVals = real(UsedNames(:,length(DiagramName)+1:end));
         strVals(find(strVals(:,1)<48 | strVals(:,1)>57),:)=[];
         RealVals = zeros(size(strVals,1),1);
         for ctR=1:size(strVals,1),
            RealVals(ctR,1) = str2double(char(strVals(ctR,:)));
         end
         if ~isnan(RealVals),
            NextInd = setdiff(1:max(RealVals)+1,RealVals);
            NextInd = NextInd(1);
         else
            NextInd=1;
         end
      else
         NextInd=1;
      end % if/else isempty(UsedInds)
      DiagramName = sprintf('%s%d',DiagramName,NextInd);
   end % if ~isempty(ExactMatch)
end % if ~isempty(AllDiagrams)

%---Open New Simulink diagram
NewDiagram = new_system;
set_param(NewDiagram,'Name',DiagramName);

% Write model data in workspace
assignin('base',LoopData.Plant.Name,LoopData.Plant.Model);
assignin('base',LoopData.Sensor.Name,LoopData.Sensor.Model);
assignin('base',LoopData.PreFilter.Name,LoopData.PreFilter.Model);
assignin('base',LoopData.Compensator.Name,zpk(LoopData.Compensator));

%---Open CSTBLOCKS, if not already open
BlockOpenFlag = find_system('Name','cstblocks');
if isempty(BlockOpenFlag)
   load_system('cstblocks');
end

CompBlock = add_block('cstblocks/LTI System',[DiagramName,'/Compensator']);
set_param(CompBlock,'MaskValueString',[LoopData.Compensator.Name,'|[]']);
InBlock = add_block('built-in/SignalGenerator',[DiagramName,'/Input']);
OutBlock = add_block('built-in/Scope',[DiagramName,'/Output']);
SumBlock = add_block('built-in/Sum',[DiagramName,'/Sum']);
PlantBlock = add_block('cstblocks/LTI System',[DiagramName,'/Plant']);
set_param(PlantBlock,'MaskValueString',[LoopData.Plant.Name,'|[]']);
SensorBlock = add_block('cstblocks/LTI System',[DiagramName,'/Sensor Dynamics']);
set_param(SensorBlock,'MaskValueString',[LoopData.Sensor.Name,'|[]']);
FilterBlock = add_block('cstblocks/LTI System',[DiagramName,'/Pre-filter']);
set_param(FilterBlock,'MaskValueString',[LoopData.PreFilter.Name,'|[]']);

%---Close CSTBLOCKS, if it wasn't open before
if isempty(BlockOpenFlag),
   close_system('cstblocks')
end

DiagramLocation = [70, 200, 549, 415];
OutPosition = [335, 41, 360, 70];
SumPosition = [75, 37, 105, 68];

if LoopData.FeedbackSign>0,
   SumStr='++';
else
   SumStr='+-';
end	

set_param(SumBlock,'Position',[165, 42, 195, 73],'Inputs',SumStr)
set_param(OutBlock,'Position',[440, 45, 465, 75])
set_param(InBlock,'Position',[15, 35, 45, 65])
set_param(NewDiagram,'Location',DiagramLocation)
set_param(FilterBlock,'Position',[65, 32, 130, 68])
set_param(SensorBlock,'Orientation','left');

open_system(NewDiagram)

% Diagram topology depends on loop configuration
switch LoopData.Configuration
case 1 % Forward
   PlantPos = [315, 42, 380, 78];
   SensorPos = [285, 112, 350, 148];
   CompPos = [220, 42, 285, 78];
   LinePos=[{[50 50; 60 50]};
      {[135 50; 160 50]};
      {[280 130; 150 130; 150 65; 160 65]};
      {[200 60;215 60]};
      {[290 60;310 60]};
      {[385 60;435 60]};
      {[400 60; 400 130;355 130]}];
case 2 % Feedback
   PlantPos = [255, 42, 320, 78];
   SensorPos = [310, 112, 375, 148];
   CompPos = [200, 112, 265, 148];
   set_param(CompBlock,'Orientation','left')
   LinePos=[{[305 130;270 130]};
      {[200 60;250 60]};
      {[195 130;150 130;150 65;160 65]};
      {[50 50;60 50]};
      {[135 50;160 50;]};
      {[325 60; 435 60]};
      {[400 60; 400 130; 380 130]}];
end 

set_param(PlantBlock,'Position',PlantPos)
set_param(SensorBlock,'Position',SensorPos)
set_param(CompBlock,'Position',CompPos)

for ctLine = 1:length(LinePos)
   add_line(NewDiagram,LinePos{ctLine});
end

open_system(NewDiagram);

watchoff(WatchFig)
