% ------------------------------------------------------------- %
%                                                               %
%           -- Validation of Two Step Tuning Method --          %
%                                                               %
%                        written by: Chriss Grimholt  18/10-10  %
% ------------------------------------------------------------- %

global gp gc t y
% Main Simulink Paramaters

    simtime = 400;

    steptime = 1;
    disturbancetime = 1;

    res = [];    
% Overshoot simulation

for pmodel = 1 %[1:7,9:14,16:17,19:29];
    pmodel
    
    stepvalue = 1;
    disturbancevalue = 0;
    
    gfeedback = tf(1);

    [gp kc_s ti_s kc0] = model(pmodel);
    
    gc = controller(0,kc0);
    
    [kc0 fval]= fsolve(@(kc) fun(kc),kc0);

    gc = controller(0,kc0);

    

    sim('sys_model')
    
   

    [gp_om kp_om tp_om theta_om type] = omodel(kc0,y,r,t)

    [gc_o kc_o ti_o] = shams_tuning(kc0,y,r,t);

% Using SIMC Tuning 

    gc_s = controller(1,kc_s,ti_s);
    
    gfeedback = tf(1);

    ms_s = ms(gp, kc_s, ti_s);

    gc = gc_s;

        stepvalue = 1;
        disturbancevalue = 0;

        sim('sys_model')

        pf_sp_t = [iae(t,e) tv(u)];

        stepvalue = 0;
        disturbancevalue = 1;

        sim('sys_model')

        pf_d_t = [iae(t,e) tv(u)];

    pf_s = [ms_s, pf_sp_t, pf_d_t];


% Tuning from Two Step Model - SIMC Rules

    [gc_om kc_om ti_om]= simc_tuning(kp_om,tp_om,theta_om, type);


    ms_om = ms(gp, kc_om, ti_om);

    gc = gc_om;

        stepvalue = 1;
        disturbancevalue = 0;

        sim('sys_model')

        pf_sp_t = [iae(t,e) tv(u)];

        stepvalue = 0;
        disturbancevalue = 1;

        sim('sys_model')

        pf_d_t = [iae(t,e) tv(u)];

    pf_om = [ms_om, pf_sp_t, pf_d_t];

% Tuning from Direct Overshoot Tuning

    gc = gc_o;

    ms_o = ms(gp, kc_o, ti_o);

        stepvalue = 1;
        disturbancevalue = 0;

        sim('sys_model')

        pf_sp_t = [iae(t,e) tv(u)];

        stepvalue = 0;
        disturbancevalue = 1;

        sim('sys_model')

        pf_d_t = [iae(t,e) tv(u)];

    pf_o = [ms_o, pf_sp_t, pf_d_t];
    
% Recording the results    
    
    res_temp = [pmodel,type, kp_om,      kc_s,     ti_s,     pf_s
                pmodel,type, tp_om,      kc_om,  ti_om,  pf_om
                pmodel,type, theta_om,   kc_o,   ti_o,   pf_o];
            
    res = [res; res_temp];

end

disp(res)





