% main
clear msRes msTuning
colorSet = colormap('lines');

for modelId = 1:4;
modelName = {'res0', 'res1', 'res8', 'resInf'};

%load([modelName{modelId},'.mat']);
msSpace = -0.1:0.1:9;
gp = model(modelId);

nFreq = 400;

%msRes = zeros(length(msSpace),4);
%dMs = [.05 .02 0 0];



for i = 1:length(msSpace)
    if modelId <=4;
        [~,gc]=simc(gp,msSpace(i));
        msTuning{modelId}(i)=ms(gp,gc);
        [gm, pm, wg, wp] = margin(gp*gc);
        msRes{modelId}(i,:)= [gm, pm, wg, wp];
    elseif modelId == 5;
        [~,gc]=simcImp(gp,msSpace(i));
        msTuning{modelId}(i)=ms(gp,gc);
        [gm, pm, wg, wp] = margin(gp*gc);
        msRes{modelId}(i,:)= [gm, pm, wg, wp];
    end
end
end


%%

figure(1);
clf

%markerSet={'-','*','--','-'};

for i = 1:length(modelName);

    h = plot(msSpace, (msRes{i}(:,2)/180)*pi./msRes{i}(:,4)); %
set(h,'color',colorSet(i,:),'linewidth',1.5) %'linestyle',markerSet{i};
hold on
end
hold off

%set(gcf,'Position',[1000 918 560 420])

%set(h(2),'color',colorSet(3,:))
%set(h(3),'color',colorSet(1,:))

% box=annotation('textbox',[.65 .85 .05 .05],'string','$g_p=\frac{1}{8s+1}$ exp$(-s)$','FitBoxToText','on','LineStyle','non','interpreter','latex','fontsize',14);


% msString={'$M_s=1.20$', '$M_s=1.59$','$M_s=2.00$'};
% msFigPos=[.22 .68 .05 .05; .3 .76 .05 .05; .46 .82 .05 .05];
% colorIndex=[5,3,1];
% for i = 1:length(msSpace);
% msTag=annotation('textbox',msFigPos(i,:),'string',msString{i},'FitBoxToText','on','LineStyle','non','interpreter','latex','fontsize',14,'color',colorSet(colorIndex(i),:));
% end


xlab=xlabel('Closed loop tuning constant, $\tau_c / \theta$');%,'interpreter','latex');

ylab=ylabel('Allowed time delay error, $\Delta\theta/\theta$');%,'interpreter','latex');
%ylab=ylabel('Gain margin, $GM$');%,'interpreter','latex');

set(xlab,'interpreter','latex','fontsize',14)
set(ylab,'interpreter','latex','fontsize',14)

grid on
axis([0, 3,0, 4])


xpos = 2.4;
ypos = [4.5,4,3.5,3,2.5,2,1.5,1,.0];              
annotationString={'','$\tau_1\in\{0,1\}$','$\tau_1=8$','$\tau_1=\infty$'};

               
for i = 1:length(annotationString)
    [figx figy] = dsxy2figxy(gca, xpos, .5*ypos(i));
    curve1 = annotation('textbox',[figx, figy, .07, .05],'string',annotationString{i},'interpreter','latex','fontsize',14,'color',colorSet(i,:),'FitBoxToText','on','LineStyle','non');    
%end

end


saveas(h , ['dmVsMs.eps'],'psc2')
