
//on older version of scilab, set the memory to the max
version_numbers = getversion('scilab');
if  version_numbers(1) < 6 then
    stacksize('max');
end
    

setlanguage("en_GB");

// ----------- A bit of physics  ----------- //

c =  299792458;// speed of light
h = 6.6207004e-34;// Planck's constant J.s.
k = 1.38064852E-23; // Boltzmann constant J/K

function T=Tm_dielectric_interface(n1,n2)
//p71 3.3.1
//dielectric interface n1/n2
//    n1    |    n2
//          |        
//    ----+ | +--->      
//    -r1 | | |  +r1    
//    <---+ | +---- 
//
// r1 is real positive for n2>n1 
//
// INPUTS:
//        n1:    complex refractive index of left dielectric
//        n2:    complex refractive index of right dielectric
// OUTPUTS:
//        T:     transfert matrix
    //just keep real part of indexes
    r1=(real(n2)-real(n1))/(real(n2)+real(n1));
    t=sqrt(1-r1*r1);
    T=1/t*[1 -r1; -r1, 1];
endfunction

function T=Tm_free_propagation(lambda, n, L)
//p72 3.3.21
// propagation in a medium of complex index n over a distance L
//
// INPUTS:
//        n:    complex refractive index of dielectric
//        L:    length of propagation
// OUTPUTS:
//        T:     transfert matrix
    //just keep real part of indexes
    
    ejbl=exp(%i*2*%pi./lambda*n*L);
    T=[ejbl, 0 ; 0, (1.0)./ejbl];
endfunction

function T=Tm_twolayers(lambda,n1,n2,l1,l2)
// propagation accross two dielectric layers:
//    1) free propag in n1
//    2) n1/n2 interface
//    3) free propag in n2
//    4) n2/n1 interface
// INPUTS:
//   lambda:    wavelength of incoming beam
//       n1:    complex refractive index of 1st dielectric half stack
//       n2:    complex refractive index of 2nd dielectric half stack
//       l1:    length of 1st dielectric half stack
//       l2:    length of 2nd dielectric half stack
// OUTPUTS:
//        T:     transfert matrix
    //just keep real part of indexes
    T4=Tm_dielectric_interface(n2,n1);
    T3=Tm_free_propagation(lambda, n2, l2);
    T2=Tm_dielectric_interface(n1,n2);
    T1=Tm_free_propagation(lambda, n1, l1);
    T=T1*T2*T3*T4;
    // T=T2*T3*T4*T1;
endfunction

function [r,t]=Tm2rtcoefs(T)
    r=T(2,1)./T(1,1);
    t=1/T(1,1);
endfunction

//amplitude reflection and transmission coefficient for a multistack:
//  n0  : coming from a medium of index n0 (n0=1 for air)
//  n1  : index in the ar layer 
//  ns  : index of the substrate
//  lam : wavelength at which we calculate the reflectivity and transmissivity
//  lam0: wavelength at which the multistack was designed
function [r,t]=ar(n0, n1 ,ns,lam,lam0)
    //recalculate best HR length at lam0
    l1=lam0./(4*real(n1));
    r=zeros(lam);
    t=r;
    for i=1:length(lam)
        T=Tm_dielectric_interface(n0,n1)......
        *Tm_free_propagation(lam(i), n1, l1)*Tm_dielectric_interface(n1,ns);
     
        [r(i),t(i)]=Tm2rtcoefs(T);
    end
endfunction


// Approximated values for Rmin
//  n0  : coming from a medium of index n0 (n0=1 for air)
//  n1  : smallest index in the layer pairs (ie of the 2nd layer in the pair)
//  ns  : index of the substrate
//  lam : wavelength at which we calculate the reflectivity and transmissivity
//  lam0: wavelength at which the multistack was designed
function [Rmin]=Rapprox(n0, n1 ,ns,lam,lam0)
    Rmin=((n0*ns-n1)/(n0*ns+n1))^2;
endfunction


// ----------- Done with physics  ----------- //


// ----------- Initial values  ----------- //

npts=10000;
npts= 1000;
npts= 100;

//index
n0=1.0;// we start in air
ns=1.51; //substrate is BK7 glass
n10=sqrt(ns*n0); //perfect AR layer

n1min=1;
n1max=1.7;

Rnoar=((ns-n0)/(ns+n0))^2;

 
//lambda for the spectrum plot
lam0=550;
lmax=900;
lmin=300;

lam=linspace(lmin, lmax, npts);

// ----------- Done with initial values  ----------- //


// ----------- Building up the GUI  ----------- //

function uicontrol_fp()
    demo_fp = figure( ...
    "dockable", "off", ...
    "infobar_visible", "off", ...
    "toolbar_visible", "off", ...
    "toolbar", "none", ...
    "menubar_visible", "on", ...
    "menubar", "none", ...
    "layout", "border", ...
    "visible", "off");

    fakeframe_height = 10;
    demo_fp.figure_id       = 100001;   
    demo_fp.background      = -2;
    demo_fp.figure_position = [0 0];
    demo_fp.figure_name     = gettext("AR single quarter wave layer");
    demo_fp.figure_size       = [800 600];

    // New menu
    h = uimenu(demo_fp, ...
    "label" , gettext("File"));

    uimenu(h, ...
    "label"     , gettext("Close"), ...
    "callback"  , "demo_fp=get_figure_handle(100001);delete(demo_fp);", ...
    "tag"       , "close_menu");

//    demo_viewCode("/home/amonmayr/ownCloud/laser_cours_INSA/simulations/ar_gui.sce");

    //LEFT PANE

    frame_left = uicontrol(demo_fp, ...
    "style", "frame", ...
    "constraints", createConstraints("border", "left", [250, 0]), ...
    "border", createBorder("titled", createBorder("line", "lightGray", 1), _("Control Panel"), "center", "below_top", createBorderFont("", 16, "normal"), "black"), ...
    "backgroundcolor", [1 1 1], ...
    "layout", "gridbag");

    //Index of AR layer
    frame_nar = uicontrol(frame_left, ...
    "style", "frame", ...
    "backgroundcolor", [1 1 1], ...
    "constraints", createConstraints("gridbag", [1, 1, 1, 1], [0, 0], "both", "center"), ...
    "border", createBorder("titled", createBorder("line", "lightGray", 1), _("Index of AR layer n1"), "center", "top", createBorderFont("", 11, "normal"), "black"), ...
    "layout", "border");
    uicontrol(frame_nar, ...
    "style", "slider", ...
    "tag", "slider_nar", ...
    "backgroundcolor", [1 1 1], ...
    "value", n10, ...
    "min", n1min, ...
    "max", n1max, ...
    "sliderstep", [0.01, 0.1], ...
    "constraints", createConstraints("border", "top"), ...
    "callback", "update_nar");



    uicontrol(frame_nar, ...
    "style", "text", ...
    "tag", "min_nar", ...
    "backgroundcolor", [1 1 1], ...
    "string", string(n1min), ...
    "constraints", createConstraints("border", "left"), ...
    "callback_type", -1);

    uicontrol(frame_nar, ...
    "style", "text", ...
    "tag", "val_nar", ...
    "backgroundcolor", [1 1 1], ...
    "HorizontalAlignment", "center", ...
    "string", string(n10), ...
    "constraints", createConstraints("border", "center"), ...
    "callback_type", -1);

    uicontrol(frame_nar, ...
    "style", "text", ...
    "tag", "max_nar", ...
    "backgroundcolor", [1 1 1], ...
    "string", string(n1max), ...
    "constraints", createConstraints("border", "right"), ...
    "callback_type", -1);

// replot button
   frame_replot = uicontrol(frame_left, ...
   "style", "frame", ...
   "backgroundcolor", [1 1 1], ...
   "constraints", createConstraints("gridbag", [1, 3, 1, 1], [0, 0], "both", "center"), ...
   "border", createBorder("titled", createBorder("line", "lightGray", 1), _("Optimum "), "center", "top", createBorderFont("", 11, "normal"), "black"), ...
   "layout", "border");
   
   uicontrol(frame_replot, ...
   "style", "pushbutton", ...
   "tag", "replot_button", ...
    "String", gettext("Reset n1"),...
    "FontSize", 11,...
   "callback", "reset_n1");

    frame_empty = uicontrol(frame_left, ...
    "style", "frame", ...
    "backgroundcolor", [1 1 1], ...
    "constraints", createConstraints("gridbag", [1, 4, 1, 1], [1, 1], "both", "center"));

    //Plot
    frame_right = uicontrol(demo_fp, ...
    "style", "frame", ...
    "layout", "border", ...
    "constraints", createConstraints("border", "center"));


    a=newaxes(frame_right);
    sca(a);

    h1=findobj("tag","slider_nar");
    n1=h1.Value;
//    h2=findobj("tag","slider_npairs");
//    np=h2.Value;

    [r,t]=ar(n0, n1 ,ns,lam,lam0)
       
//    [Rmin]=Rapprox(n0, n1 ,ns,lam,lam0);
////    pause
//    xfrect(lmin,Rmin*100,lmax-lmin, Rmin*100);
//    erect=gce();
//    erect.tag="rect_approx";
//    erect.background=color("gainsboro");
    plot(lam,Rnoar*ones(lam)*100, 'r--');
    et=gce();
    et.children.thickness=4;
    et.children.tag="plot_noar";
    plot(lam,abs(r).^2*100, 'r');
    er=gce();
    er.children.thickness=4;
    er.children.tag="plot_r";



   a = gca();
   a.font_size=4;
   a.tag                   = "plotAR";
   a.title.text            = "Single Layer AR";
   a.title.font_size       = 5;
   a.x_label.text          = "$\lambda\ [nm]$";
   a.x_label.font_size       = 5;
   a.y_label.text          = "R [%]";
   a.y_label.font_size       = 5;
   a.margins=[0.20,0.05,0.15,0.15];
   a.axes_bounds=[0,0,1,1]
   a.tight_limits="on";
   a.ticks_format(2)="%.1f";
   a.data_bounds=[lmin, 0; lmax, Rnoar*100];
   a.grid=[1,1]*color('grey');
   a.box="on";
   
   demo_fp.immediate_drawing     = "on";

   demo_fp.visible     = "on";
endfunction

// ----------- Done building up the GUI  ----------- //


// ----------- Callback  ----------- //

function update_nar()
    //temporarily deactivate the callback (don't want callback calls to stack up while processing the current one)
    set(gcbo,"callback_type",-1);
//    h1=findobj("tag","slider_nar"); // useless, I can rely on gcbo
//    dn=h1.Value;
    n1=get(gcbo,"value");
    
    //update numeric display
    h3=findobj("tag","val_nar");
    h3.String=string(n1);
    //reactivate callback
    set(gcbo,"callback_type",0);

replot_sim()

endfunction

function reset_n1()
   n1=sqrt(n0*ns);
   h1=findobj("tag","slider_nar");
   h1.Value=n1;
   h3=findobj("tag","val_nar");
   h3.String=string(n1);
   replot_sim();
endfunction




function replot_sim()
   h1=findobj("tag","slider_nar");
   n1=h1.Value;
   [r,t]=ar(n0, n1 ,ns,lam,lam0);
   R=100*(abs(r).^2);
   er=findobj("tag","plot_r");
   er.data=[lam.',R.'];
   
   a=findobj("tag", "plotAR");
   a.data_bounds=[lmin, 0; lmax, max([Rnoar*100,R])];
   
endfunction

// -----------Done with callback  ----------- //


xdel(winsid());

uicontrol_fp();// launch the GUI

