Update audio gui demo to stereo channels

// Scilab ( http://www.scilab.org/ ) - This file is part of Scilab
// Copyright (C) 2011-2014 - INRIA - Serge Steer
//
// Copyright (C) 2012 - 2016 - Scilab Enterprises
//
// This file is hereby licensed under the terms of the GNU GPL v2.0,
// pursuant to article 5.3.4 of the CeCILL v.2.1.
// This file was originally licensed under the terms of the CeCILL v2.1,
// and continues to be available under such terms.
// For more information, see the COPYING file which you should have received
// along with this program.
//
//
// Edited by Witczenko from MicroDAQ.org
// Real time signal processing with MicroDAQ
// Toolbox ver. 1.2, scan functions - DEMO

START = %F;
FILTER = [];
GAIN = [];
NO_FILTER = [];

function [ok,values_res,exprs]=wfir_gui_demo(exprs)
    global START;
    global FILTER;
    global GAIN;
    global NO_FILTER;

    START = %F;
    NO_FILTER = %T;
    FILTER = [];
    GAIN = 1.0;

    FT=["lp","hp","bp","sb", "nf"]
    WT=["re","tr","hn","hm","kr","ch","ch"]
    //  errcatch(-1,'continue')
    if argn(2)<1 then
        exprs=["""bp""";
        """hn"""
        "48";
        "44100";
        "300"
        "3000";
        "1000"]
    end
    ftype=exprs(1)
    wtype=exprs(2)
    if execstr("forder="+exprs(3)+";freq_ech="+exprs(4)+";low="+exprs(5)+";high="+exprs(6)+";fp="+exprs(7),"errcatch")<>0 then
        values_res=[]
        exprs=[]
        ok=%f
        return
    end
    global ret
    ret=0

    margin_x     = 5;      // Horizontal margin between each elements
    margin_y     = 5;      // Vertical margin between each elements
    button_w     = 70;
    button_h     = 30;
    frame_h     = 350;
    frame_w     = 440;
    label_h      = 20;
    list_h       = 120;
    list_w       = 100;
    list_incr    = list_w;
    axes_w       = 2*margin_x+frame_w;
    axes_h       = 2*margin_y+frame_h;// Frame height
    defaultfont  = "arial"; // Default Font

    fig_id = max(winsid())
    if isempty(fig_id)
        fig_id = 1;
    else
        fig_id = fig_id + 1;
    end

    fig = scf(fig_id)

    // Remove Scilab graphics menus & toolbar
    delmenu(fig.figure_id, gettext("&File"));
    delmenu(fig.figure_id, gettext("&Tools"));
    delmenu(fig.figure_id, gettext("&Edit"));
    delmenu(fig.figure_id, gettext("&?"));
    toolbar(fig.figure_id, "off");
    fig.axes_size       = [axes_w axes_h];

    fig.background      = addcolor([0.8 0.8 0.8]);
    fig.figure_name     = _("WFIR settings");
    ax=fig.children;
    ax.background= fig.background ;

    gui=uicontrol( ...
    "parent"              , fig,...
    "style"               , "frame",...
    "units"               , "pixels",...
    "position"            , [0 0 axes_w axes_h],...
    "background"          , [1 1 1]*0.8, ...
    "visible"             , "on");

    yo=axes_h-button_h;

    yft=frame_h-margin_y-label_h
    xft=margin_x;
    //Filter type selection -----------------------------------------------------------------
    listf_h       = 100;
    listf_w       = 150;
    label_w       = 75;
    uicontrol( ...
    "parent"              , gui,...
    "style"               , "text",...
    "string"              , _("Filter type"),...
    "units"               , "pixels",...
    "position"            , [xft yft label_w label_h], ...
    "fontname"            , defaultfont,...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "fontweight"          , "bold", ...
    "horizontalalignment" , "left", ...
    "background"          , [1 1 1]*0.8, ...
    "visible"             , "on");
    Ftv=uicontrol( ...
    "parent"              , gui,...
    "style"               , "edit",...
    "string"              , ftype,...
    "units"               , "pixels",...
    "position"            , [xft+label_w+margin_x yft listf_w-label_w-margin_x label_h], ...
    "fontname"            , defaultfont,...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "fontweight"          , "bold", ...
    "horizontalalignment" , "left", ...
    "background"          , [1 1 1]*0.8, ...
    "callback"            , "wfirSetFilterType()", ...
    "visible"             , "on");
    Filtertype=uicontrol( ...
    "parent"              , gui,...
    "style"               , "listbox",...
    "string"              , [_("Low pass");_("High pass");_("Band pass");_("Stop Band"); _("No filter")],...
    "value"               , find(FT==evstr(ftype)),...
    "units"               , "pixels",...
    "position"            , [xft,yft-listf_h,listf_w,listf_h],...
    "fontname"            , defaultfont,...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "horizontalalignment" , "left", ...
    "BackgroundColor"     , [1 1 1], ...
    "ForegroundColor"     , [1 1 1]*0, ...
    "visible"             , "on", ...
    "callback"            , "wfirSetFilterType()");
    set(Ftv,"userdata",list([],Filtertype))

    //Window type selection -----------------------------------------------------------------
    ywt=yft-listf_h-4*margin_y
    xwt=xft
    listw_h       = 140;
    listw_w       = listf_w;
    uicontrol( ...
    "parent"              , gui,...
    "style"               , "text",...
    "string"              , _("Window type"),...
    "units"               , "pixels",...
    "position"            , [xwt ywt label_w label_h],...
    "fontname"            , defaultfont,...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "fontweight"          , "bold", ...
    "horizontalalignment" , "left", ...
    "background"          , [1 1 1]*0.8, ...
    "visible"             , "on");
    Wtv=uicontrol( ...
    "parent"              , gui,...
    "style"               , "edit",...
    "string"              , wtype,...
    "units"               , "pixels",...
    "position"            , [xwt+label_w+margin_x ywt listw_w-label_w-margin_x label_h],...
    "fontname"            , defaultfont,...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "fontweight"          , "bold", ...
    "horizontalalignment" , "left", ...
    "background"          , [1 1 1]*0.8, ...
    "callback"            , "wfirSetWindowType()",...
    "visible"             , "on");

    W=[_("Rectangular");_("Triangular");_("Hanning");
    _("Hamming");_("Kaiser");_("Chebychev main lobe");_("Chebychev side lobe")];
    index=find(WT==evstr(wtype))
    if index==[] then index=1,end//for debug
    Windowtype=uicontrol( ...
    "parent"              , gui,...
    "style"               , "listbox",...
    "string"              , W,...
    "value"               , find(WT==evstr(wtype)),...
    "units"               , "pixels",...
    "position"            , [xwt,ywt-listw_h,listw_w,listw_h],...
    "fontname"            , defaultfont,...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "horizontalalignment" , "left", ...
    "BackgroundColor"     , [1 1 1], ...
    "ForegroundColor"     , [1 1 1]*0, ...
    "visible"             , "on", ...
    "callback"            , "wfirSetWindowType()");
    set(Wtv,"userdata",list([],Windowtype))

    //Sampling Frequency -----------------------------------------------------------------
    ysf=frame_h-margin_y-label_h
    xsf=xft+listf_w+2*margin_x
    labelsf_w=180
    editsf_w=80
    sfreq=1
    uicontrol( ...
    "parent"              , gui,...
    "style"               , "text",...
    "string"              ,  _("Sampling Frequency (Hz)"),...
    "units"               , "pixels",...
    "position"            , [xsf ysf labelsf_w label_h],...
    "fontname"            , defaultfont,...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "fontweight"          , "bold", ...
    "horizontalalignment" , "left", ...
    "background"          , [1 1 1]*0.8, ...
    "visible"             , "on");
    Sfreq =uicontrol( ...
    "parent"              , gui,...
    "style"               , "edit",...
    "string"               , exprs(4),...
    "units"               , "pixels",...
    "position"            , [xsf+margin_x+labelsf_w,ysf,editsf_w,label_h],...
    "fontname"            , defaultfont,...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "horizontalalignment" , "left", ...
    "BackgroundColor"     , [1 1 1], ...
    "ForegroundColor"     , [1 1 1]*0, ...
    "callback"            , "wfirSetSamplingFrequency()", ...
    "userdata"            ,sfreq,...
    "visible"             , "on", ...
    "enable"              , "off")
    //Filter order -----------------------------------------------------------------
    yfo=ysf-margin_y-label_h
    xfo=xsf
    labelfo_w=labelsf_w;
    editfo_w= editsf_w;
    scroll_w=160
    uicontrol( ...
    "parent"              , gui,...
    "style"               , "text",...
    "string"              ,  _("Filter Order"),...
    "units"               , "pixels",...
    "position"            , [xfo yfo labelfo_w label_h],...
    "fontname"            , defaultfont,...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "fontweight"          , "bold", ...
    "horizontalalignment" , "left", ...
    "background"          , [1 1 1]*0.8, ...
    "visible"             , "on");
    Forderv=uicontrol( ...
    "parent"              , gui,...
    "style"               , "edit",...
    "string"              , exprs(3),...
    "units"               , "pixels",...
    "position"            , [xfo,yfo-label_h-margin_y,editfo_w,label_h],...
    "fontname"            , defaultfont,...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "horizontalalignment" , "left", ...
    "BackgroundColor"     , [1 1 1], ...
    "ForegroundColor"     , [1 1 1]*0, ...
    "callback"            , "wfirValue2Sliderpos()", ...
    "visible"             , "on")

    Forders=uicontrol( ...
    "parent"              , gui,...
    "style"               , "slider",...
    "min"                 , 2,...
    "max"                 , 100,...
    "sliderstep"          , [1 10],...
    "value"               , forder,...
    "units"               , "pixels",...
    "position"            , [xfo+editfo_w+margin_x,yfo-label_h-margin_y,scroll_w,label_h],...
    "fontname"            , defaultfont,...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "horizontalalignment" , "left", ...
    "BackgroundColor"     , [1 1 1], ...
    "ForegroundColor"     , [1 1 1]*0, ...
    "userdata"            , list(Forderv,1), ...
    "callback"            , "wfirSliderpos2ValueI()",...
    "visible"             , "on")
    set(Forderv,"userdata",Forders);

    //Low cutoff frequency -----------------------------------------------------------------
    ylcf=yfo-2*(margin_y+label_h)
    xlcf=xsf
    labellcf_w=labelsf_w;
    editlcf_w= editsf_w;
    if ftype=="""hp""" then visible="off";else visible="on";end
    Lcfl=uicontrol( ...
    "parent"              , gui,...
    "style"               , "text",...
    "visible"             , visible,...
    "string"              ,  _("Low cutoff frequency (Hz)"),...
    "units"               , "pixels",...
    "position"            , [xlcf ylcf labellcf_w label_h],...
    "fontname"            , defaultfont,...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "fontweight"          , "bold", ...
    "horizontalalignment" , "left", ...
    "background"          , [1 1 1]*0.8);
    fact=1;
    Lcfv=uicontrol( ...
    "parent"              , gui,...
    "style"               , "edit",...
    "visible"             , visible,...
    "units"               , "pixels",...
    "string"              , exprs(5),...
    "position"            , [xlcf,ylcf-label_h-margin_y,editlcf_w,label_h],...
    "fontname"            , defaultfont,...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "horizontalalignment" , "left", ...
    "BackgroundColor"     , [1 1 1], ...
    "ForegroundColor"     , [1 1 1]*0, ...
    "callback"            , "wfirValue2Sliderpos()")
    Lcfs=uicontrol( ...
    "parent"              , gui,...
    "style"               , "slider",...
    "visible"             , visible,...
    "min"                 , 0,...
    "max"                 , 16000,...
    "sliderstep"          , [50 500],...
    "value"               , 300,...
    "units"               , "pixels",...
    "position"            , [xlcf+editlcf_w+margin_x,ylcf-label_h-margin_y,scroll_w,label_h],...
    "fontname"            , defaultfont,...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "horizontalalignment" , "left", ...
    "BackgroundColor"     , [1 1 1], ...
    "ForegroundColor"     , [1 1 1]*0, ...
    "userdata"            , list(Lcfv,fact), ...
    "callback"            , "wfirSliderpos2Value()")
    set(Lcfv,"userdata",Lcfs);

    //High cutoff frequency -----------------------------------------------------------------
    yhcf=ylcf-2*(margin_y+label_h)
    xhcf=xsf
    labelhcf_w=labelsf_w;
    edithcf_w= editsf_w;
    if ftype=="""lp""" then visible="off";else visible="on";end
    Hcfl=uicontrol( ...
    "parent"              , gui,...
    "style"               , "text",...
    "visible"             , visible,...
    "string"              ,  _("High cutoff frequency (Hz)"),...
    "units"               , "pixels",...
    "position"            , [xhcf yhcf labelhcf_w label_h],...
    "fontname"            , defaultfont,...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "fontweight"          , "bold", ...
    "horizontalalignment" , "left", ...
    "background"          , [1 1 1]*0.8);
    fact=1;
    Hcfv=uicontrol( ...
    "parent"              , gui,...
    "style"               , "edit",...
    "visible"             , visible,...
    "units"               , "pixels",...
    "string"              , exprs(6),...
    "position"            , [xhcf,yhcf-label_h-margin_y,edithcf_w,label_h],...
    "fontname"            , defaultfont,...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "horizontalalignment" , "left", ...
    "BackgroundColor"     , [1 1 1], ...
    "ForegroundColor"     , [1 1 1]*0, ...
    "callback"            , "wfirValue2Sliderpos()")
    Hcfs=uicontrol( ...
    "parent"              , gui,...
    "style"               , "slider",...
    "visible"             , visible,...
    "min"                 , 0,...
    "max"                 , 16000,...
    "sliderstep"          , [50 500],...
    "value"               , 3000,...
    "units"               , "pixels",...
    "position"            , [xhcf+edithcf_w+margin_x,yhcf-label_h-margin_y,scroll_w,label_h],...
    "fontname"            , defaultfont,...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "horizontalalignment" , "left", ...
    "BackgroundColor"     , [1 1 1], ...
    "ForegroundColor"     , [1 1 1]*0, ...
    "userdata"            , list(Hcfv,fact), ...
    "callback"            , "wfirSliderpos2Value()")
    set(Hcfv,"userdata",Hcfs);

    //Chebychev or Kaiser window parameter -----------------------------------------------------------------
    yfp=yhcf-2*(margin_y+label_h)
    xfp=xsf
    labelfp_w=labelsf_w;
    editfp_w= editsf_w;
    if and(wtype<>["""kr""" """ch"""]) then visible="off";else visible="on";end
    Fpl=uicontrol( ...
    "parent"              , gui,...
    "style"               , "text",...
    "visible"             , visible,...
    "string"              ,  _("Parameter"),...
    "units"               , "pixels",...
    "position"            , [xfp yfp labelfp_w label_h],...
    "fontname"            , defaultfont,...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "fontweight"          , "bold", ...
    "horizontalalignment" , "left", ...
    "background"          , [1 1 1]*0.8);
    fact=1000;

    Fpv=uicontrol( ...
    "parent"              , gui,...
    "style"               , "edit",...
    "visible"             , visible,...
    "units"               , "pixels",...
    "string"              , exprs(7),...
    "position"            , [xfp,yfp-label_h-margin_y,editfp_w,label_h],...
    "fontname"            , defaultfont,...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "horizontalalignment" , "left", ...
    "BackgroundColor"     , [1 1 1], ...
    "ForegroundColor"     , [1 1 1]*0, ...
    "callback"            , "wfirValue2Sliderpos()")
    Fps=uicontrol( ...
    "parent"              , gui,...
    "style"               , "slider",...
    "visible"             , visible,...
    "min"                 , 0,...
    "max"                 , 500,...
    "sliderstep"          , [1 10],...
    "value"               , fp*fact,...
    "units"               , "pixels",...
    "position"            , [xfp+editfp_w+margin_x,yfp-label_h-margin_y,scroll_w,label_h],...
    "fontname"            , defaultfont,...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "horizontalalignment" , "left", ...
    "BackgroundColor"     , [1 1 1], ...
    "ForegroundColor"     , [1 1 1]*0, ...
    "userdata"            , list(Fpv,fact), ...
    "callback"            , "wfirSliderpos2Value()")

    set(Fpv,"userdata",Fps);

    set(Filtertype,"userdata",list([Lcfl Lcfv Lcfs;Hcfl Hcfv Hcfs],Ftv))
    set(Windowtype,"userdata",list([Fpl Fpv Fps], Wtv))

//Gain -----------------------------------------------------------------
    yfp=yfp-2*(margin_y+label_h)
    xfp=xfp
    labelhcf_w=labelsf_w;
    edithcf_w= editsf_w;
    Gainlabel=uicontrol( ...
    "parent"              , gui,...
    "style"               , "text",...
    "visible"             , "on",...
    "string"              ,  _("Gain"),...
    "units"               , "pixels",...
    "position"            , [xfp yfp labelhcf_w label_h],...
    "fontname"            , defaultfont,...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "fontweight"          , "bold", ...
    "horizontalalignment" , "left", ...
    "background"          , [1 1 1]*0.8);
    fact=1;
    GainEdit=uicontrol( ...
    "parent"              , gui,...
    "style"               , "edit",...
    "visible"             , "on",...
    "units"               , "pixels",...
    "string"              , "1.0",...
    "position"            , [xfp,yfp-label_h-margin_y,edithcf_w,label_h],...
    "fontname"            , defaultfont,...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "horizontalalignment" , "left", ...
    "BackgroundColor"     , [1 1 1], ...
    "ForegroundColor"     , [1 1 1]*0, ...
    "callback"            , "gainEditCall()")
    GainSlider=uicontrol( ...
    "parent"              , gui,...
    "style"               , "slider",...
    "visible"             , "on",...
    "min"                 , 0,...
    "max"                 , 2.5,...
    "sliderstep"          , [0.05 0.4],...
    "value"               , 1.0,...
    "units"               , "pixels",...
    "position"            , [xfp+edithcf_w+margin_x,yfp-label_h-margin_y,scroll_w,label_h],...
    "fontname"            , defaultfont,...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "horizontalalignment" , "left", ...
    "BackgroundColor"     , [1 1 1], ...
    "ForegroundColor"     , [1 1 1]*0, ...
    "userdata"            , list(GainEdit), ...
    "callback"            , "gainSliderCall()")
    set(GainEdit,"userdata",GainSlider);
    //Display -----------------------------------------------------------------
    yd=yfp-2*(margin_y+label_h)
    xd=xsf
    labeld_w=40
    uicontrol( ...
    "parent"              , gui,...
    "style"               , "text",...
    "string"              ,  _("View"),...
    "units"               , "pixels",...
    "position"            , [xd yd labeld_w label_h],...
    "fontname"            , defaultfont,...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "fontweight"          , "bold", ...
    "horizontalalignment" , "left", ...
    "background"          , [1 1 1]*0.8, ...
    "visible"             , "on");
    Fview=uicontrol( ...
    "parent"              , gui,...
    "style"               , "checkbox",...
    "units"               , "pixels",...
    "min"                 , 0, ...
    "max"                 , 1, ...
    "value"               , 0, ...
    "position"            , [xd+margin_x+labeld_w yd label_h label_h],...
    "background"          , [1 1 1]*0.8, ...
    "callback"            , "wfirSetFilterView()",...
    "visible"             , "on");

    ybuttons=margin_y
    xbuttons=xhcf
    Start = uicontrol( ...
    "parent"              , gui,...
    "relief"              , "groove",...
    "style"               , "pushbutton",...
    "string"              , _("Start"),...
    "units"               , "pixels",...
    "position"            , [xbuttons,ybuttons,button_w button_h],..
    "fontname"            , "arial",...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "fontweight"          , "bold", ...
    "horizontalalignment" , "center", ...
    "visible"             , "on", ...
    "callback"            , "start()");
    xbuttons=xbuttons+margin_x+button_w
    Stop = uicontrol( ...
    "parent"              , gui,...
    "relief"              , "groove",...
    "style"               , "pushbutton",...
    "string"              , _("Stop"),...
    "units"               , "pixels",...
    "position"            , [xbuttons,ybuttons,button_w button_h],..
    "fontname"            , "arial",...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "fontweight"          , "bold", ...
    "horizontalalignment" , "center", ...
    "visible"             , "on", ...
    "callback"            , "stop()");
    xbuttons=xbuttons+margin_x+button_w

    set(gui,"userdata",[Fview,Filtertype,Windowtype,Forderv,Forders,Lcfv,Lcfs,Hcfv,Hcfs,Fpv,Fps,Sfreq,Ftv,Wtv])

    Rate = 44100;
    ChannelIN = [1 2];
    ChannelOUT = [1 2];
    aiRange = [-0.64 0.64]; // analog input range: ±5V
    aoRange = [-2.5 2.5]; // analog output range: ±2.5V
    IsContinuous = %T;
    IsDifferential = %F;
    ChunkSize = Rate/6;
    SampleOffset = 100;

    initialData = [zeros(ChunkSize,1) zeros(ChunkSize,1)];

    [ftype,forder,low,high,wtype,fpar,freq_ech]=wfirGetFilterParameters(gui.userdata);
    FILTER = wfir(ftype, 48,[low/Rate high/Rate],wtype,fpar);

    realtimeinit(0.1);
    t=0;

    mdaq_close();

    while ret==0&or(winsid()==fig_id) then
        if START == %T then
            // Init analog input/output scanning
            mdaq_ai_scan_init(ChannelIN, aiRange, IsDifferential, Rate, -1);
            mdaq_ao_scan_init(ChannelOUT, initialData, aoRange, IsContinuous, Rate, -1);

            audioData = mdaq_ai_scan(ChunkSize, %T);
            mdaq_ao_scan();
            mdaq_ao_scan_data(ChannelOUT, audioData, %T);

            mprintf("\nFiltering h as been started...\n");
            sample_count = 0;

            while START==%T then

                // Acquire data
                pastAudioData = audioData;
                audioData = mdaq_ai_scan(ChunkSize, %T);
                audioDataExt = [pastAudioData(ChunkSize-SampleOffset+1:ChunkSize, :); audioData];

                // FIR Filter
                //left channel
                filtAudioDataLeft = filter(FILTER, 1, audioDataExt(:, 1));
                filtAudioDataLeft = filtAudioDataLeft(SampleOffset+1:size(filtAudioDataLeft, '*'));

                //right channel
                filtAudioDataRight = filter(FILTER, 1, audioDataExt(:, 2));
                filtAudioDataRight = filtAudioDataRight(SampleOffset+1:size(filtAudioDataRight, '*'));

                // Analog Output
                if NO_FILTER == %F then
                    mdaq_ao_scan_data( ChannelOUT, [(filtAudioDataLeft*GAIN) (filtAudioDataRight*GAIN)], %T);
                else
                    mdaq_ao_scan_data(ChannelOUT, (audioData*GAIN), %T);
                end

                sample_count = sample_count + size(audioData, '*');
                mprintf("Filtered samples: %d\n", sample_count);
                realtime(t);
                t=t+1;
            end

            mdaq_ao_scan_stop();
            mdaq_ai_scan_stop();

            mprintf("Filtering has been stopped.\n");
        end

        realtime(t);
        t=t+1;
    end

    if ret==1&or(winsid()==fig_id) then
        ok=%t
        [ftype,forder,low,high,wtype,fpar,freq_ech]=wfirGetFilterParameters(gui.userdata)
        values_res=tlist(["wfir","ftype","forder","low","high","wtype","fpar","freq_ech"],ftype,forder,low,high,wtype,fpar,freq_ech)
        exprs= wfirGetFilterExprs(gui.userdata)
        delete(fig)
    else
        //user had canceled or closed the gui window
        ok=%f
        values_res=[]
        exprs=[]
    end
    clearglobal ret idle;

endfunction

function start()
    global START;
    START = %T;
endfunction

function stop()
    global START;
    START = %F;
endfunction

function gainEditCall(hv)
    global GAIN;
    if argn(2)<1 then hv=gcbo,end
    hs=hv.userdata;
    if execstr("v="+hv.string,"errcatch")==0 then
        hs.value=v
        if v > hs.max then
            GAIN = hs.max
        elseif v < hs.min then
            GAIN = hs.min
        else
            GAIN = v;
        end
    end
endfunction

function gainSliderCall(hs)
    global GAIN;
    xpause(200);
    if argn(2)<1 then hs=gcbo,end
    ud=hs.userdata;
    hv=ud(1);
    hv.string=string(hs.value)
    GAIN = hs.value;
endfunction

function wfirSliderpos2Value(hs)
    xpause(200);
    if argn(2)<1 then hs=gcbo,end
    hs.value=floor(hs.value)
    ud=hs.userdata
    hv=ud(1);//handle on edition zone
    fact=ud(2)// scale factor
    hv.string=string(hs.value)
    wfirUpdate(hs)
endfunction
function wfirSliderpos2ValueI(hs)
    xpause(200);
    if argn(2)<1 then hs=gcbo,end
    hs.value=round(hs.value)
    ud=hs.userdata
    hv=ud(1);//handle on edition zone
    fact=ud(2)// scale factor
    hv.string=string(hs.value/fact)
    wfirUpdate(hs)
endfunction

function wfirValue2Sliderpos(hv)
    // hv handle on edition zone
    if argn(2)<1 then hv=gcbo,end
    if execstr("v="+hv.string,"errcatch")==0 then
        hs=hv.userdata //handle on the slider
        ud=hs.userdata
        fact=ud(2)// scale factor
        hs.value=fact*v
        hv.ForegroundColor=[0 0 0];
        wfirUpdate(hv)
    else
        hv.ForegroundColor=[1 0 0];
    end
endfunction

function wfirSetFilterType()
    global NO_FILTER;
    FT=["lp","hp","bp","sb","nf"]
    ud=gcbo.userdata

    if gcbo.style=="edit" then
        he=gcbo //handle on the edit area
        hl=ud(2) //handle on the list area

        ok=execstr("k=find("+he.string+"==FT)","errcatch")==0
        if ~ok|k==[] then
            he.ForegroundColor=[1 0 0];
            return
        else
            he.ForegroundColor=[0 0 0];
            hl.value=k
        end
    else
        hl=gcbo //handle on the list area
        he=ud(2) //handle on the edit area
        he.string=sci2exp(FT(hl.value),0)
    end
    ud=hl.userdata
    Handles=ud(1)
    select hl.value
    case 1 then //low pass
        Handles(1,:).visible="on";
        Handles(2,:).visible="off";
    case 2 then //high pass
        Handles(1,:).visible="off";
        Handles(2,:).visible="on";
    case 3 then //band pass
        Handles(1,:).visible="on";
        Handles(2,:).visible="on";
    case 4 then //stop band
        Handles(1,:).visible="on";
        Handles(2,:).visible="on";
    case 5 then //stop band
        Handles(1,:).visible="off";
        Handles(2,:).visible="off";
    end

    if hl.value <> 5 then
        wfirUpdate(gcbo)
        NO_FILTER = %F;
    else
        NO_FILTER = %T;
    end

endfunction

function wfirSetWindowType()
    WT=["re","tr","hn","hm","kr","ch","ch"]
    ud=gcbo.userdata
    if gcbo.style=="edit" then
        he=gcbo //handle on the edit area
        hl=ud(2) //handle on the list area
        ok=execstr("k=find("+he.string+"==WT)","errcatch")==0

        if ~ok|k==[] then
            he.ForegroundColor=[1 0 0];
            return
        else
            he.ForegroundColor=[0 0 0];
            hl.value=k
        end
    else
        hl=gcbo //handle on the list area
        he=ud(2) //handle on the edit area
        he.string=sci2exp(WT(hl.value),0)
    end

    ud=hl.userdata
    Handles=ud(1)
    k=hl.value
    if and(k<>[5 6 7]) then
        Handles.visible="off"
    else
        label=Handles(1)
        value=Handles(2)
        scroll=Handles(3)

        if k==5 then //Kaiser
            label.string="Beta"
            label.visible="on";
            value.visible="on";

            init=2.5;fact=100;
            value.string=string(init)
            scroll.min=0
            scroll.max=10*fact
            scroll.value=init*fact
            d=scroll.userdata;d(2)=fact
            set(scroll,"userdata",d)
            scroll.visible="on";
        elseif k==6 then //Chebychev, main lobe constraint df in [0 0.5]
            label.string=_("Window main lobe width")
            label.visible="on";
            value.visible="on";
            init=0.2;fact=1000;
            value.string=string(init)
            scroll.min=1d-10*fact
            scroll.max=0.5*fact
            scroll.value=init*fact
            d=scroll.userdata;d(2)=fact
            set(scroll,"userdata",d)
            scroll.visible="on";

        elseif k==7 then //Chebychev, side lobe constraint dp>0
            label.string=_("maximum side-lobe height")
            label.visible="on";
            value.visible="on";
            init=0.001;fact=1000;
            value.string=string(init)
            scroll.min=1d-10*fact
            scroll.max=1*fact
            scroll.value=init*fact
            d=scroll.userdata;d(2)=fact
            set(scroll,"userdata",d)
            scroll.visible="on";
        end
    end
    wfirUpdate(gcbo)
endfunction

function wfirSetFilterView()
    h=gcbo //handle on the view check box
    if h.value==0 //disable
        fig=h.userdata
        execstr("delete(fig)","errcatch")
        h.userdata=[]
    else //enable
        nwin=size(winsid(),"*")
        if nwin==0 then win=1;else win=max(winsid())+1;end
        fig=scf(win)
        a=gca();
        a.x_label.text=_("frequency (Hz)")
        a.y_label.text=_("Magnitude (dB)")
        a.axes_visible="on"
        a.grid=ones(1,2)*color("gray");
        xpoly([],[])
        set(h,"userdata",fig)
        clearglobal idle
        wfirUpdate(gcbo)
    end
endfunction

function wfirSetSamplingFrequency()
    Sfreq=gcbo
    ok=execstr("newfreq="+Sfreq.string,"errcatch")==0
    ok=ok&newfreq>0

    if ok then
        Sfreq.ForegroundColor=[0 0 0];
        curfreq=Sfreq.userdata
        gui=gcbo.parent
        H=gui.userdata
        //H=[Fview,Filtertype,Windowtype,Forderv,Forders,Lcfv,Lcfs,Hcfv,Hcfs,Fpv,Fps,Sfreq,Ftv,Wtv]
        //update low and high cutoff frequencies
        r=newfreq/curfreq
        Lcfv=H(6),Lcfs=H(7),Hcfv=H(8),Hcfs=H(9)

        Lcfs.min=Lcfs.min*r
        Lcfs.max=Lcfs.max*r
        Lcfs.value=Lcfs.value*r
        Lcfv.string=string(evstr(Lcfv.string)*r)

        Hcfs.min=Hcfs.min*r
        Hcfs.max=Hcfs.max*r
        Hcfs.value=Hcfs.value*r
        Hcfv.string=string(evstr(Hcfv.string)*r)

        Sfreq.userdata=newfreq
        wfirUpdate(gcbo)
    else
        Sfreq.ForegroundColor=[1 0 0];
    end

endfunction

function [ftype,forder,low,high,wtype,fpar,freq_ech]=wfirGetFilterParameters(H)
    //  low,high,freq_ech are returned in Hz
    //H=[Fview,Filtertype,Windowtype,Forderv,Forders,Lcfv,Lcfs,Hcfv,Hcfs,Fpv,Fps,Sfreq,Ftv,Wtv]
    FT=["lp","hp","bp","sb"]
    WT=["re","tr","hn","hm","kr","ch","ch"]
    Filtertype=H(2);
    Windowtype=H(3);
    Forderv=H(4);
    Lcfv=H(6);
    Hcfv=H(8);
    Fpv=H(10);
    Sfreq=H(12)
    ftype=FT(Filtertype.value)
    wtype=WT(Windowtype.value)
    forder=evstr(Forderv.string)
    if or(ftype==["hp" "sb"]) then
        //force odd ordrer
        if 2*int(forder/2)==forder then forder=forder+1,end
    end
    freq_ech=evstr(Sfreq.string)
    if ftype=="lp" then
        low=evstr(Lcfv.string)
        high=0
    elseif ftype=="hp" then
        low=evstr(Hcfv.string)
        high=0
    else
        low=evstr(Lcfv.string)
        high=evstr(Hcfv.string)
    end
    if Windowtype.value==5 //Kaiser
        fpar=[evstr(Fpv.string) 0]
    elseif Windowtype.value==6 //Chebychev, main lobe constraint df in [0 0.5]
        fpar=[-1 evstr(Fpv.string)]
    elseif Windowtype.value==7  //Chebychev, side lobe constraint dp>0
        fpar=[evstr(Fpv.string) -1]
    else
        fpar=[-1 -1]
    end
endfunction

function  wfirUpdate(h)
    global FILTER;
    gui=h.parent
    H=gui.userdata
    [ftype,forder,low,high,wtype,fpar,freq_ech]= ...
    wfirGetFilterParameters(H)

    if ftype == 'bp' | ftype == 'sb' then
        if low >= high then
                low = high - 1;
        end
    end

    cfreq=[low,high]/freq_ech;
    FILTER =wfir(ftype,forder,cfreq,wtype,fpar);

    if H(1).value==1 then
        old=gcf()
        [ftype,forder,low,high,wtype,fpar,freq_ech]= ...
        wfirGetFilterParameters(H)

    if ftype == 'bp' | ftype == 'sb' then
        if low >= high then
                low = high - 1;
        end
    end

        cfreq=[low,high]/freq_ech;
        [filt,wfm,fr]=wfir(ftype,forder,cfreq,wtype,fpar);
        fig=H(1).userdata
        if ~is_handle_valid(fig) then
            //the window has been closed by user
            fig=scf(max(winsid())+1)
            a=gca();
            a.x_label.text=_("frequency (Hz)")
            a.y_label.text=_("Magnitude (dB)")
            a.axes_visible="on"
            a.grid=ones(1,2)*color("gray");
            xpoly([],[])
            set(H(1),"userdata",fig)
        end
        eps=1d-6;
        frq=linspace(eps,0.5-eps,10*size(FILTER,"*"))
        [frq,repf]=repfreq(syslin("d",poly(FILTER,"z","c"),1),frq)
        scf(fig);drawlater()
        a=gca();p=a.children
        frq=frq(:)*freq_ech
        m=20*log10(abs(repf(:)))
        a.data_bounds=[min(frq) min(m);max(frq) max(m)]
        p.data=[frq m];
        drawnow()
        scf(old)
    end
endfunction

function exprs= wfirGetFilterExprs(H)
    // H=[Fview,Filtertype,Windowtype,Forderv,Forders,Lcfv,Lcfs,Hcfv,Hcfs,Fpv,Fps,Sfreq,Ftv,Wtv]
    FT=["lp","hp","bp","sb"]
    WT=["re","tr","hn","hm","kr","ch","ch"]
    Filtertype=H(2);
    Windowtype=H(3);
    Forderv=H(4);
    Lcfv=H(6);
    Hcfv=H(8);
    Fpv=H(10);
    Sfreq=H(12)
    exprs=[Ftv.string;
    Wtv.string;
    Forderv.string;
    Sfreq.string;
    Lcfv.string
    Hcfv.string;
    Fpv.string]
endfunction

clc;
wfir_gui_demo();

// Scilab ( http://www.scilab.org/ ) - This file is part of Scilab
// Copyright (C) 2011-2014 - INRIA - Serge Steer
//
// Copyright (C) 2012 - 2016 - Scilab Enterprises
//
// This file is hereby licensed under the terms of the GNU GPL v2.0,
// pursuant to article 5.3.4 of the CeCILL v.2.1.
// This file was originally licensed under the terms of the CeCILL v2.1,
// and continues to be available under such terms.
// For more information, see the COPYING file which you should have received
// along with this program.
//
//
// Edited by Witczenko from MicroDAQ.org
// Real time signal processing with MicroDAQ
// Toolbox ver. 1.2, scan functions - DEMO

START = %F;
FILTER = [];
GAIN = [];
NO_FILTER = [];

function [ok,values_res,exprs]=wfir_gui_demo(exprs)
    global START;
    global FILTER;
    global GAIN;
    global NO_FILTER;

    START = %F;
    NO_FILTER = %T;
    FILTER = [];
    GAIN = 1.0;

    FT=["lp","hp","bp","sb", "nf"]
    WT=["re","tr","hn","hm","kr","ch","ch"]
    //  errcatch(-1,'continue')
    if argn(2)<1 then
        exprs=["""bp""";
        """hn"""
        "64";
        "44100";
        "300"
        "3000";
        "1000"]
    end
    ftype=exprs(1)
    wtype=exprs(2)
    if execstr("forder="+exprs(3)+";freq_ech="+exprs(4)+";low="+exprs(5)+";high="+exprs(6)+";fp="+exprs(7),"errcatch")<>0 then
        values_res=[]
        exprs=[]
        ok=%f
        return
    end
    global ret
    ret=0

    margin_x     = 5;      // Horizontal margin between each elements
    margin_y     = 5;      // Vertical margin between each elements
    button_w     = 70;
    button_h     = 30;
    frame_h     = 350;
    frame_w     = 440;
    label_h      = 20;
    list_h       = 120;
    list_w       = 100;
    list_incr    = list_w;
    axes_w       = 2*margin_x+frame_w;
    axes_h       = 2*margin_y+frame_h;// Frame height
    defaultfont  = "arial"; // Default Font

    fig_id = max(winsid())
    if isempty(fig_id)
        fig_id = 1;
    else
        fig_id = fig_id + 1;
    end

    fig = scf(fig_id)

    // Remove Scilab graphics menus & toolbar
    delmenu(fig.figure_id, gettext("&File"));
    delmenu(fig.figure_id, gettext("&Tools"));
    delmenu(fig.figure_id, gettext("&Edit"));
    delmenu(fig.figure_id, gettext("&?"));
    toolbar(fig.figure_id, "off");
    fig.axes_size       = [axes_w axes_h];

    fig.background      = addcolor([0.8 0.8 0.8]);
    fig.figure_name     = _("WFIR settings");
    ax=fig.children;
    ax.background= fig.background ;

    gui=uicontrol( ...
    "parent"              , fig,...
    "style"               , "frame",...
    "units"               , "pixels",...
    "position"            , [0 0 axes_w axes_h],...
    "background"          , [1 1 1]*0.8, ...
    "visible"             , "on");

    yo=axes_h-button_h;

    yft=frame_h-margin_y-label_h
    xft=margin_x;
    //Filter type selection -----------------------------------------------------------------
    listf_h       = 100;
    listf_w       = 150;
    label_w       = 75;
    uicontrol( ...
    "parent"              , gui,...
    "style"               , "text",...
    "string"              , _("Filter type"),...
    "units"               , "pixels",...
    "position"            , [xft yft label_w label_h], ...
    "fontname"            , defaultfont,...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "fontweight"          , "bold", ...
    "horizontalalignment" , "left", ...
    "background"          , [1 1 1]*0.8, ...
    "visible"             , "on");
    Ftv=uicontrol( ...
    "parent"              , gui,...
    "style"               , "edit",...
    "string"              , ftype,...
    "units"               , "pixels",...
    "position"            , [xft+label_w+margin_x yft listf_w-label_w-margin_x label_h], ...
    "fontname"            , defaultfont,...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "fontweight"          , "bold", ...
    "horizontalalignment" , "left", ...
    "background"          , [1 1 1]*0.8, ...
    "callback"            , "wfirSetFilterType()", ...
    "visible"             , "on");
    Filtertype=uicontrol( ...
    "parent"              , gui,...
    "style"               , "listbox",...
    "string"              , [_("Low pass");_("High pass");_("Band pass");_("Stop Band"); _("No filter")],...
    "value"               , find(FT==evstr(ftype)),...
    "units"               , "pixels",...
    "position"            , [xft,yft-listf_h,listf_w,listf_h],...
    "fontname"            , defaultfont,...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "horizontalalignment" , "left", ...
    "BackgroundColor"     , [1 1 1], ...
    "ForegroundColor"     , [1 1 1]*0, ...
    "visible"             , "on", ...
    "callback"            , "wfirSetFilterType()");
    set(Ftv,"userdata",list([],Filtertype))

    //Window type selection -----------------------------------------------------------------
    ywt=yft-listf_h-4*margin_y
    xwt=xft
    listw_h       = 140;
    listw_w       = listf_w;
    uicontrol( ...
    "parent"              , gui,...
    "style"               , "text",...
    "string"              , _("Window type"),...
    "units"               , "pixels",...
    "position"            , [xwt ywt label_w label_h],...
    "fontname"            , defaultfont,...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "fontweight"          , "bold", ...
    "horizontalalignment" , "left", ...
    "background"          , [1 1 1]*0.8, ...
    "visible"             , "on");
    Wtv=uicontrol( ...
    "parent"              , gui,...
    "style"               , "edit",...
    "string"              , wtype,...
    "units"               , "pixels",...
    "position"            , [xwt+label_w+margin_x ywt listw_w-label_w-margin_x label_h],...
    "fontname"            , defaultfont,...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "fontweight"          , "bold", ...
    "horizontalalignment" , "left", ...
    "background"          , [1 1 1]*0.8, ...
    "callback"            , "wfirSetWindowType()",...
    "visible"             , "on");

    W=[_("Rectangular");_("Triangular");_("Hanning");
    _("Hamming");_("Kaiser");_("Chebychev main lobe");_("Chebychev side lobe")];
    index=find(WT==evstr(wtype))
    if index==[] then index=1,end//for debug
    Windowtype=uicontrol( ...
    "parent"              , gui,...
    "style"               , "listbox",...
    "string"              , W,...
    "value"               , find(WT==evstr(wtype)),...
    "units"               , "pixels",...
    "position"            , [xwt,ywt-listw_h,listw_w,listw_h],...
    "fontname"            , defaultfont,...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "horizontalalignment" , "left", ...
    "BackgroundColor"     , [1 1 1], ...
    "ForegroundColor"     , [1 1 1]*0, ...
    "visible"             , "on", ...
    "callback"            , "wfirSetWindowType()");
    set(Wtv,"userdata",list([],Windowtype))

    //Sampling Frequency -----------------------------------------------------------------
    ysf=frame_h-margin_y-label_h
    xsf=xft+listf_w+2*margin_x
    labelsf_w=180
    editsf_w=80
    sfreq=1
    uicontrol( ...
    "parent"              , gui,...
    "style"               , "text",...
    "string"              ,  _("Sampling Frequency (Hz)"),...
    "units"               , "pixels",...
    "position"            , [xsf ysf labelsf_w label_h],...
    "fontname"            , defaultfont,...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "fontweight"          , "bold", ...
    "horizontalalignment" , "left", ...
    "background"          , [1 1 1]*0.8, ...
    "visible"             , "on");
    Sfreq =uicontrol( ...
    "parent"              , gui,...
    "style"               , "edit",...
    "string"               , exprs(4),...
    "units"               , "pixels",...
    "position"            , [xsf+margin_x+labelsf_w,ysf,editsf_w,label_h],...
    "fontname"            , defaultfont,...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "horizontalalignment" , "left", ...
    "BackgroundColor"     , [1 1 1], ...
    "ForegroundColor"     , [1 1 1]*0, ...
    "callback"            , "wfirSetSamplingFrequency()", ...
    "userdata"            ,sfreq,...
    "visible"             , "on", ...
    "enable"              , "off")
    //Filter order -----------------------------------------------------------------
    yfo=ysf-margin_y-label_h
    xfo=xsf
    labelfo_w=labelsf_w;
    editfo_w= editsf_w;
    scroll_w=160
    uicontrol( ...
    "parent"              , gui,...
    "style"               , "text",...
    "string"              ,  _("Filter Order"),...
    "units"               , "pixels",...
    "position"            , [xfo yfo labelfo_w label_h],...
    "fontname"            , defaultfont,...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "fontweight"          , "bold", ...
    "horizontalalignment" , "left", ...
    "background"          , [1 1 1]*0.8, ...
    "visible"             , "on");
    Forderv=uicontrol( ...
    "parent"              , gui,...
    "style"               , "edit",...
    "string"              , exprs(3),...
    "units"               , "pixels",...
    "position"            , [xfo,yfo-label_h-margin_y,editfo_w,label_h],...
    "fontname"            , defaultfont,...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "horizontalalignment" , "left", ...
    "BackgroundColor"     , [1 1 1], ...
    "ForegroundColor"     , [1 1 1]*0, ...
    "callback"            , "wfirValue2Sliderpos()", ...
    "visible"             , "on")

    Forders=uicontrol( ...
    "parent"              , gui,...
    "style"               , "slider",...
    "min"                 , 2,...
    "max"                 , 100,...
    "sliderstep"          , [1 10],...
    "value"               , forder,...
    "units"               , "pixels",...
    "position"            , [xfo+editfo_w+margin_x,yfo-label_h-margin_y,scroll_w,label_h],...
    "fontname"            , defaultfont,...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "horizontalalignment" , "left", ...
    "BackgroundColor"     , [1 1 1], ...
    "ForegroundColor"     , [1 1 1]*0, ...
    "userdata"            , list(Forderv,1), ...
    "callback"            , "wfirSliderpos2ValueI()",...
    "visible"             , "on")
    set(Forderv,"userdata",Forders);

    //Low cutoff frequency -----------------------------------------------------------------
    ylcf=yfo-2*(margin_y+label_h)
    xlcf=xsf
    labellcf_w=labelsf_w;
    editlcf_w= editsf_w;
    if ftype=="""hp""" then visible="off";else visible="on";end
    Lcfl=uicontrol( ...
    "parent"              , gui,...
    "style"               , "text",...
    "visible"             , visible,...
    "string"              ,  _("Low cutoff frequency (Hz)"),...
    "units"               , "pixels",...
    "position"            , [xlcf ylcf labellcf_w label_h],...
    "fontname"            , defaultfont,...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "fontweight"          , "bold", ...
    "horizontalalignment" , "left", ...
    "background"          , [1 1 1]*0.8);
    fact=1;
    Lcfv=uicontrol( ...
    "parent"              , gui,...
    "style"               , "edit",...
    "visible"             , visible,...
    "units"               , "pixels",...
    "string"              , exprs(5),...
    "position"            , [xlcf,ylcf-label_h-margin_y,editlcf_w,label_h],...
    "fontname"            , defaultfont,...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "horizontalalignment" , "left", ...
    "BackgroundColor"     , [1 1 1], ...
    "ForegroundColor"     , [1 1 1]*0, ...
    "callback"            , "wfirValue2Sliderpos()")
    Lcfs=uicontrol( ...
    "parent"              , gui,...
    "style"               , "slider",...
    "visible"             , visible,...
    "min"                 , 0,...
    "max"                 , 16000,...
    "sliderstep"          , [50 500],...
    "value"               , 300,...
    "units"               , "pixels",...
    "position"            , [xlcf+editlcf_w+margin_x,ylcf-label_h-margin_y,scroll_w,label_h],...
    "fontname"            , defaultfont,...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "horizontalalignment" , "left", ...
    "BackgroundColor"     , [1 1 1], ...
    "ForegroundColor"     , [1 1 1]*0, ...
    "userdata"            , list(Lcfv,fact), ...
    "callback"            , "wfirSliderpos2Value()")
    set(Lcfv,"userdata",Lcfs);

    //High cutoff frequency -----------------------------------------------------------------
    yhcf=ylcf-2*(margin_y+label_h)
    xhcf=xsf
    labelhcf_w=labelsf_w;
    edithcf_w= editsf_w;
    if ftype=="""lp""" then visible="off";else visible="on";end
    Hcfl=uicontrol( ...
    "parent"              , gui,...
    "style"               , "text",...
    "visible"             , visible,...
    "string"              ,  _("High cutoff frequency (Hz)"),...
    "units"               , "pixels",...
    "position"            , [xhcf yhcf labelhcf_w label_h],...
    "fontname"            , defaultfont,...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "fontweight"          , "bold", ...
    "horizontalalignment" , "left", ...
    "background"          , [1 1 1]*0.8);
    fact=1;
    Hcfv=uicontrol( ...
    "parent"              , gui,...
    "style"               , "edit",...
    "visible"             , visible,...
    "units"               , "pixels",...
    "string"              , exprs(6),...
    "position"            , [xhcf,yhcf-label_h-margin_y,edithcf_w,label_h],...
    "fontname"            , defaultfont,...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "horizontalalignment" , "left", ...
    "BackgroundColor"     , [1 1 1], ...
    "ForegroundColor"     , [1 1 1]*0, ...
    "callback"            , "wfirValue2Sliderpos()")
    Hcfs=uicontrol( ...
    "parent"              , gui,...
    "style"               , "slider",...
    "visible"             , visible,...
    "min"                 , 0,...
    "max"                 , 16000,...
    "sliderstep"          , [50 500],...
    "value"               , 3000,...
    "units"               , "pixels",...
    "position"            , [xhcf+edithcf_w+margin_x,yhcf-label_h-margin_y,scroll_w,label_h],...
    "fontname"            , defaultfont,...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "horizontalalignment" , "left", ...
    "BackgroundColor"     , [1 1 1], ...
    "ForegroundColor"     , [1 1 1]*0, ...
    "userdata"            , list(Hcfv,fact), ...
    "callback"            , "wfirSliderpos2Value()")
    set(Hcfv,"userdata",Hcfs);

    //Chebychev or Kaiser window parameter -----------------------------------------------------------------
    yfp=yhcf-2*(margin_y+label_h)
    xfp=xsf
    labelfp_w=labelsf_w;
    editfp_w= editsf_w;
    if and(wtype<>["""kr""" """ch"""]) then visible="off";else visible="on";end
    Fpl=uicontrol( ...
    "parent"              , gui,...
    "style"               , "text",...
    "visible"             , visible,...
    "string"              ,  _("Parameter"),...
    "units"               , "pixels",...
    "position"            , [xfp yfp labelfp_w label_h],...
    "fontname"            , defaultfont,...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "fontweight"          , "bold", ...
    "horizontalalignment" , "left", ...
    "background"          , [1 1 1]*0.8);
    fact=1000;

    Fpv=uicontrol( ...
    "parent"              , gui,...
    "style"               , "edit",...
    "visible"             , visible,...
    "units"               , "pixels",...
    "string"              , exprs(7),...
    "position"            , [xfp,yfp-label_h-margin_y,editfp_w,label_h],...
    "fontname"            , defaultfont,...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "horizontalalignment" , "left", ...
    "BackgroundColor"     , [1 1 1], ...
    "ForegroundColor"     , [1 1 1]*0, ...
    "callback"            , "wfirValue2Sliderpos()")
    Fps=uicontrol( ...
    "parent"              , gui,...
    "style"               , "slider",...
    "visible"             , visible,...
    "min"                 , 0,...
    "max"                 , 500,...
    "sliderstep"          , [1 10],...
    "value"               , fp*fact,...
    "units"               , "pixels",...
    "position"            , [xfp+editfp_w+margin_x,yfp-label_h-margin_y,scroll_w,label_h],...
    "fontname"            , defaultfont,...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "horizontalalignment" , "left", ...
    "BackgroundColor"     , [1 1 1], ...
    "ForegroundColor"     , [1 1 1]*0, ...
    "userdata"            , list(Fpv,fact), ...
    "callback"            , "wfirSliderpos2Value()")

    set(Fpv,"userdata",Fps);

    set(Filtertype,"userdata",list([Lcfl Lcfv Lcfs;Hcfl Hcfv Hcfs],Ftv))
    set(Windowtype,"userdata",list([Fpl Fpv Fps], Wtv))

//Gain -----------------------------------------------------------------
    yfp=yfp-2*(margin_y+label_h)
    xfp=xfp
    labelhcf_w=labelsf_w;
    edithcf_w= editsf_w;
    Gainlabel=uicontrol( ...
    "parent"              , gui,...
    "style"               , "text",...
    "visible"             , "on",...
    "string"              ,  _("Gain"),...
    "units"               , "pixels",...
    "position"            , [xfp yfp labelhcf_w label_h],...
    "fontname"            , defaultfont,...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "fontweight"          , "bold", ...
    "horizontalalignment" , "left", ...
    "background"          , [1 1 1]*0.8);
    fact=1;
    GainEdit=uicontrol( ...
    "parent"              , gui,...
    "style"               , "edit",...
    "visible"             , "on",...
    "units"               , "pixels",...
    "string"              , "1.0",...
    "position"            , [xfp,yfp-label_h-margin_y,edithcf_w,label_h],...
    "fontname"            , defaultfont,...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "horizontalalignment" , "left", ...
    "BackgroundColor"     , [1 1 1], ...
    "ForegroundColor"     , [1 1 1]*0, ...
    "callback"            , "gainEditCall()")
    GainSlider=uicontrol( ...
    "parent"              , gui,...
    "style"               , "slider",...
    "visible"             , "on",...
    "min"                 , 0,...
    "max"                 , 2.5,...
    "sliderstep"          , [0.05 0.4],...
    "value"               , 1.0,...
    "units"               , "pixels",...
    "position"            , [xfp+edithcf_w+margin_x,yfp-label_h-margin_y,scroll_w,label_h],...
    "fontname"            , defaultfont,...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "horizontalalignment" , "left", ...
    "BackgroundColor"     , [1 1 1], ...
    "ForegroundColor"     , [1 1 1]*0, ...
    "userdata"            , list(GainEdit), ...
    "callback"            , "gainSliderCall()")
    set(GainEdit,"userdata",GainSlider);
    //Display -----------------------------------------------------------------
    yd=yfp-2*(margin_y+label_h)
    xd=xsf
    labeld_w=40
    uicontrol( ...
    "parent"              , gui,...
    "style"               , "text",...
    "string"              ,  _("View"),...
    "units"               , "pixels",...
    "position"            , [xd yd labeld_w label_h],...
    "fontname"            , defaultfont,...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "fontweight"          , "bold", ...
    "horizontalalignment" , "left", ...
    "background"          , [1 1 1]*0.8, ...
    "visible"             , "on");
    Fview=uicontrol( ...
    "parent"              , gui,...
    "style"               , "checkbox",...
    "units"               , "pixels",...
    "min"                 , 0, ...
    "max"                 , 1, ...
    "value"               , 0, ...
    "position"            , [xd+margin_x+labeld_w yd label_h label_h],...
    "background"          , [1 1 1]*0.8, ...
    "callback"            , "wfirSetFilterView()",...
    "visible"             , "on");

    ybuttons=margin_y
    xbuttons=xhcf
    Start = uicontrol( ...
    "parent"              , gui,...
    "relief"              , "groove",...
    "style"               , "pushbutton",...
    "string"              , _("Start"),...
    "units"               , "pixels",...
    "position"            , [xbuttons,ybuttons,button_w button_h],..
    "fontname"            , "arial",...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "fontweight"          , "bold", ...
    "horizontalalignment" , "center", ...
    "visible"             , "on", ...
    "callback"            , "start()");
    xbuttons=xbuttons+margin_x+button_w
    Stop = uicontrol( ...
    "parent"              , gui,...
    "relief"              , "groove",...
    "style"               , "pushbutton",...
    "string"              , _("Stop"),...
    "units"               , "pixels",...
    "position"            , [xbuttons,ybuttons,button_w button_h],..
    "fontname"            , "arial",...
    "fontunits"           , "points",...
    "fontsize"            , 12,...
    "fontweight"          , "bold", ...
    "horizontalalignment" , "center", ...
    "visible"             , "on", ...
    "callback"            , "stop()");
    xbuttons=xbuttons+margin_x+button_w

    set(gui,"userdata",[Fview,Filtertype,Windowtype,Forderv,Forders,Lcfv,Lcfs,Hcfv,Hcfs,Fpv,Fps,Sfreq,Ftv,Wtv])

    Rate = 44100;
    Channel = 1;
    aiRange = 2; // analog input range: ±5V
    aoRange = 3; // analog output range: ±2.5V
    aoTrigger = 0;
    IsContinuous = %T;
    IsDifferential = %F;
    ChunkSize = Rate/6;
    SampleOffset = 100;

    [ftype,forder,low,high,wtype,fpar,freq_ech]=wfirGetFilterParameters(gui.userdata);
    FILTER = wfir(ftype, 64,[low/Rate high/Rate],wtype,fpar);

    realtimeinit(0.01);
    t=0;

    while ret==0&or(winsid()==fig_id) then
        if START == %T then
            // Init analog input/output scanning
            mdaq_ai_scan_init(Channel, aiRange, IsDifferential, Rate, -1);
            mdaq_ao_scan_init(Channel, aoRange, IsContinuous, aoTrigger, Rate, -1);

            audioData = mdaq_ai_scan(ChunkSize, %T);
            mdaq_ao_data_queue(zeros(ChunkSize, 1), %T);

            mdaq_ao_scan();

            mprintf("\nFiltering h as been started...\n");
            sample_count = 0;

            while START==%T then

                // Acquire data
                pastAudioData = audioData;
                audioData = mdaq_ai_scan(ChunkSize, %T);
                audioDataExt = [pastAudioData(ChunkSize-SampleOffset+1:ChunkSize); audioData];

                // FIR Filter
                filtAudioData = filter(FILTER, 1, audioDataExt);
                filtAudioData = filtAudioData(SampleOffset+1:size(filtAudioData, '*'));

                // Analog Output
                if NO_FILTER == %F then
                    mdaq_ao_data_queue((filtAudioData*GAIN), %T);
                else
                    mdaq_ao_data_queue((audioData*GAIN), %T);
                end

                sample_count = sample_count + size(audioData, '*');
                mprintf("Filtered samples: %d\n", sample_count);
                realtime(t);
                t=t+1;
            end

            mdaq_ao_scan_stop();
            mdaq_ai_scan_stop();

            mprintf("Filtering has been stopped.\n");
        end

        realtime(t);
        t=t+1;
    end

    if ret==1&or(winsid()==fig_id) then
        ok=%t
        [ftype,forder,low,high,wtype,fpar,freq_ech]=wfirGetFilterParameters(gui.userdata)
        values_res=tlist(["wfir","ftype","forder","low","high","wtype","fpar","freq_ech"],ftype,forder,low,high,wtype,fpar,freq_ech)
        exprs= wfirGetFilterExprs(gui.userdata)
        delete(fig)
    else
        //user had canceled or closed the gui window
        ok=%f
        values_res=[]
        exprs=[]
    end
    clearglobal ret idle;

endfunction

function start()
    global START;
    START = %T;
endfunction

function stop()
    global START;
    START = %F;
endfunction

function gainEditCall(hv)
    global GAIN;
    if argn(2)<1 then hv=gcbo,end
    hs=hv.userdata;
    if execstr("v="+hv.string,"errcatch")==0 then
        hs.value=v
        if v > hs.max then
            GAIN = hs.max
        elseif v < hs.min then
            GAIN = hs.min
        else
            GAIN = v;
        end
    end
endfunction

function gainSliderCall(hs)
    global GAIN;
    xpause(200);
    if argn(2)<1 then hs=gcbo,end
    ud=hs.userdata;
    hv=ud(1);
    hv.string=string(hs.value)
    GAIN = hs.value;
endfunction

function wfirSliderpos2Value(hs)

    if argn(2)<1 then hs=gcbo,end
    hs.value=floor(hs.value)
    ud=hs.userdata
    hv=ud(1);//handle on edition zone
    fact=ud(2)// scale factor
    hv.string=string(hs.value)
    wfirUpdate(hs)
endfunction
function wfirSliderpos2ValueI(hs)
    xpause(200);
    if argn(2)<1 then hs=gcbo,end
    hs.value=round(hs.value)
    ud=hs.userdata
    hv=ud(1);//handle on edition zone
    fact=ud(2)// scale factor
    hv.string=string(hs.value/fact)
    wfirUpdate(hs)
endfunction

function wfirValue2Sliderpos(hv)
    // hv handle on edition zone
    if argn(2)<1 then hv=gcbo,end
    if execstr("v="+hv.string,"errcatch")==0 then
        hs=hv.userdata //handle on the slider
        ud=hs.userdata
        fact=ud(2)// scale factor
        hs.value=fact*v
        hv.ForegroundColor=[0 0 0];
        wfirUpdate(hv)
    else
        hv.ForegroundColor=[1 0 0];
    end
endfunction

function wfirSetFilterType()
    global NO_FILTER;
    FT=["lp","hp","bp","sb","nf"]
    ud=gcbo.userdata

    if gcbo.style=="edit" then
        he=gcbo //handle on the edit area
        hl=ud(2) //handle on the list area

        ok=execstr("k=find("+he.string+"==FT)","errcatch")==0
        if ~ok|k==[] then
            he.ForegroundColor=[1 0 0];
            return
        else
            he.ForegroundColor=[0 0 0];
            hl.value=k
        end
    else
        hl=gcbo //handle on the list area
        he=ud(2) //handle on the edit area
        he.string=sci2exp(FT(hl.value),0)
    end
    ud=hl.userdata
    Handles=ud(1)
    select hl.value
    case 1 then //low pass
        Handles(1,:).visible="on";
        Handles(2,:).visible="off";
    case 2 then //high pass
        Handles(1,:).visible="off";
        Handles(2,:).visible="on";
    case 3 then //band pass
        Handles(1,:).visible="on";
        Handles(2,:).visible="on";
    case 4 then //stop band
        Handles(1,:).visible="on";
        Handles(2,:).visible="on";
    case 5 then //stop band
        Handles(1,:).visible="off";
        Handles(2,:).visible="off";
    end

    if hl.value <> 5 then
        wfirUpdate(gcbo)
        NO_FILTER = %F;
    else
        NO_FILTER = %T;
    end

endfunction

function wfirSetWindowType()
    WT=["re","tr","hn","hm","kr","ch","ch"]
    ud=gcbo.userdata
    if gcbo.style=="edit" then
        he=gcbo //handle on the edit area
        hl=ud(2) //handle on the list area
        ok=execstr("k=find("+he.string+"==WT)","errcatch")==0

        if ~ok|k==[] then
            he.ForegroundColor=[1 0 0];
            return
        else
            he.ForegroundColor=[0 0 0];
            hl.value=k
        end
    else
        hl=gcbo //handle on the list area
        he=ud(2) //handle on the edit area
        he.string=sci2exp(WT(hl.value),0)
    end

    ud=hl.userdata
    Handles=ud(1)
    k=hl.value
    if and(k<>[5 6 7]) then
        Handles.visible="off"
    else
        label=Handles(1)
        value=Handles(2)
        scroll=Handles(3)

        if k==5 then //Kaiser
            label.string="Beta"
            label.visible="on";
            value.visible="on";

            init=2.5;fact=100;
            value.string=string(init)
            scroll.min=0
            scroll.max=10*fact
            scroll.value=init*fact
            d=scroll.userdata;d(2)=fact
            set(scroll,"userdata",d)
            scroll.visible="on";
        elseif k==6 then //Chebychev, main lobe constraint df in [0 0.5]
            label.string=_("Window main lobe width")
            label.visible="on";
            value.visible="on";
            init=0.2;fact=1000;
            value.string=string(init)
            scroll.min=1d-10*fact
            scroll.max=0.5*fact
            scroll.value=init*fact
            d=scroll.userdata;d(2)=fact
            set(scroll,"userdata",d)
            scroll.visible="on";

        elseif k==7 then //Chebychev, side lobe constraint dp>0
            label.string=_("maximum side-lobe height")
            label.visible="on";
            value.visible="on";
            init=0.001;fact=1000;
            value.string=string(init)
            scroll.min=1d-10*fact
            scroll.max=1*fact
            scroll.value=init*fact
            d=scroll.userdata;d(2)=fact
            set(scroll,"userdata",d)
            scroll.visible="on";
        end
    end
    wfirUpdate(gcbo)
endfunction

function wfirSetFilterView()
    h=gcbo //handle on the view check box
    if h.value==0 //disable
        fig=h.userdata
        execstr("delete(fig)","errcatch")
        h.userdata=[]
    else //enable
        nwin=size(winsid(),"*")
        if nwin==0 then win=1;else win=max(winsid())+1;end
        fig=scf(win)
        a=gca();
        a.x_label.text=_("frequency (Hz)")
        a.y_label.text=_("Magnitude (dB)")
        a.axes_visible="on"
        a.grid=ones(1,2)*color("gray");
        xpoly([],[])
        set(h,"userdata",fig)
        clearglobal idle
        wfirUpdate(gcbo)
    end
endfunction

function wfirSetSamplingFrequency()
    Sfreq=gcbo
    ok=execstr("newfreq="+Sfreq.string,"errcatch")==0
    ok=ok&newfreq>0

    if ok then
        Sfreq.ForegroundColor=[0 0 0];
        curfreq=Sfreq.userdata
        gui=gcbo.parent
        H=gui.userdata
        //H=[Fview,Filtertype,Windowtype,Forderv,Forders,Lcfv,Lcfs,Hcfv,Hcfs,Fpv,Fps,Sfreq,Ftv,Wtv]
        //update low and high cutoff frequencies
        r=newfreq/curfreq
        Lcfv=H(6),Lcfs=H(7),Hcfv=H(8),Hcfs=H(9)

        Lcfs.min=Lcfs.min*r
        Lcfs.max=Lcfs.max*r
        Lcfs.value=Lcfs.value*r
        Lcfv.string=string(evstr(Lcfv.string)*r)

        Hcfs.min=Hcfs.min*r
        Hcfs.max=Hcfs.max*r
        Hcfs.value=Hcfs.value*r
        Hcfv.string=string(evstr(Hcfv.string)*r)

        Sfreq.userdata=newfreq
        wfirUpdate(gcbo)
    else
        Sfreq.ForegroundColor=[1 0 0];
    end

endfunction

function [ftype,forder,low,high,wtype,fpar,freq_ech]=wfirGetFilterParameters(H)
    //  low,high,freq_ech are returned in Hz
    //H=[Fview,Filtertype,Windowtype,Forderv,Forders,Lcfv,Lcfs,Hcfv,Hcfs,Fpv,Fps,Sfreq,Ftv,Wtv]
    FT=["lp","hp","bp","sb"]
    WT=["re","tr","hn","hm","kr","ch","ch"]
    Filtertype=H(2);
    Windowtype=H(3);
    Forderv=H(4);
    Lcfv=H(6);
    Hcfv=H(8);
    Fpv=H(10);
    Sfreq=H(12)
    ftype=FT(Filtertype.value)
    wtype=WT(Windowtype.value)
    forder=evstr(Forderv.string)
    if or(ftype==["hp" "sb"]) then
        //force odd ordrer
        if 2*int(forder/2)==forder then forder=forder+1,end
    end
    freq_ech=evstr(Sfreq.string)
    if ftype=="lp" then
        low=evstr(Lcfv.string)
        high=0
    elseif ftype=="hp" then
        low=evstr(Hcfv.string)
        high=0
    else
        low=evstr(Lcfv.string)
        high=evstr(Hcfv.string)
    end
    if Windowtype.value==5 //Kaiser
        fpar=[evstr(Fpv.string) 0]
    elseif Windowtype.value==6 //Chebychev, main lobe constraint df in [0 0.5]
        fpar=[-1 evstr(Fpv.string)]
    elseif Windowtype.value==7  //Chebychev, side lobe constraint dp>0
        fpar=[evstr(Fpv.string) -1]
    else
        fpar=[-1 -1]
    end
endfunction

function  wfirUpdate(h)
    global FILTER;
    gui=h.parent
    H=gui.userdata
    [ftype,forder,low,high,wtype,fpar,freq_ech]= ...
    wfirGetFilterParameters(H)

    if ftype == 'bp' | ftype == 'sb' then
        if low >= high then
                low = high - 1;
        end
    end

    cfreq=[low,high]/freq_ech;
    FILTER =wfir(ftype,forder,cfreq,wtype,fpar);

    if H(1).value==1 then
        old=gcf()
        [ftype,forder,low,high,wtype,fpar,freq_ech]= ...
        wfirGetFilterParameters(H)

    if ftype == 'bp' | ftype == 'sb' then
        if low >= high then
                low = high - 1;
        end
    end

        cfreq=[low,high]/freq_ech;
        [filt,wfm,fr]=wfir(ftype,forder,cfreq,wtype,fpar);
        fig=H(1).userdata
        if ~is_handle_valid(fig) then
            //the window has been closed by user
            fig=scf(max(winsid())+1)
            a=gca();
            a.x_label.text=_("frequency (Hz)")
            a.y_label.text=_("Magnitude (dB)")
            a.axes_visible="on"
            a.grid=ones(1,2)*color("gray");
            xpoly([],[])
            set(H(1),"userdata",fig)
        end
        eps=1d-6;
        frq=linspace(eps,0.5-eps,10*size(FILTER,"*"))
        [frq,repf]=repfreq(syslin("d",poly(FILTER,"z","c"),1),frq)
        scf(fig);drawlater()
        a=gca();p=a.children
        frq=frq(:)*freq_ech
        m=20*log10(abs(repf(:)))
        a.data_bounds=[min(frq) min(m);max(frq) max(m)]
        p.data=[frq m];
        drawnow()
        scf(old)
    end
endfunction

function exprs= wfirGetFilterExprs(H)
    // H=[Fview,Filtertype,Windowtype,Forderv,Forders,Lcfv,Lcfs,Hcfv,Hcfs,Fpv,Fps,Sfreq,Ftv,Wtv]
    FT=["lp","hp","bp","sb"]
    WT=["re","tr","hn","hm","kr","ch","ch"]
    Filtertype=H(2);
    Windowtype=H(3);
    Forderv=H(4);
    Lcfv=H(6);
    Hcfv=H(8);
    Fpv=H(10);
    Sfreq=H(12)
    exprs=[Ftv.string;
    Wtv.string;
    Forderv.string;
    Sfreq.string;
    Lcfv.string
    Hcfv.string;
    Fpv.string]
endfunction

clc;
wfir_gui_demo();


Update Cramer.sce

Update Cramer.sce

A = input("Introduce la matriz A: ")
b = input("Introduce el vector b: ")

d = det(A)

if size(A,1)==size(b,1) then
    for i=1:size(A,2)
        Ai = A
        Ai(:,i) = b
        X(i) = det(Ai)/d
    end
    disp(X)
else
    disp("Dimensiones no compatibles")
end

function [ X ] = cramer(A, B)

    [s u] = size(A);

    if s~= u
      error('A debe ser una matriz cuadratica');
    elseif s ~= size(B)(1)
      error('A y B no concuerdan en size');
    end

    detS = det(A);
    X = zeros(s(1), 1);
    for i = 1 : s(1)
        t = A(:, i);
        A(:, i) = B;
        R(i) = det(A) / detS;
        A(:, i) = t;
    end
endfunction

A = [3., -0.1, -0.2; 0.1, 7., -0.3; 0.3, -0.2, 10.]
B = [7.85; -19.3; 71.4]

X = cramer(A, B)


INTEGRATION: CWS tbe12 (1.2.248); FILE MERGED 2004/08/09 13:35:26 sw 1.2.248.1: #i24857#

-o svtools.AccessibleBrowseBox
-o svtools.AccessibleBrowseBoxHeaderBar
-o svtools.AccessibleBrowseBoxHeaderCell
-o svtools.AccessibleBrowseBoxTable
-o svtools.AccessibleBrowseBoxTableCell
-o svtools.AccessibleIconChoiceCtrl
-o svtools.AccessibleIconChoiceCtrlEntry
-o svtools.AccessibleTabBar
#-o svtools.AccessibleTabBarPage
#-o svtools.AccessibleTabBarPageList
-o svtools.AccessibleTreeListBox
-o svtools.AccessibleTreeListBoxEntry

-o svtools.AccessibleBrowseBox
-o svtools.AccessibleBrowseBoxHeaderBar
-o svtools.AccessibleBrowseBoxHeaderCell
-o svtools.AccessibleBrowseBoxTable
-o svtools.AccessibleBrowseBoxTableCell
-o svtools.AccessibleIconChoiceCtrl
-o svtools.AccessibleIconChoiceCtrlEntry
-o svtools.AccessibleTabBar
-o svtools.AccessibleTabBarPage
-o svtools.AccessibleTabBarPageList
-o svtools.AccessibleTreeListBox
-o svtools.AccessibleTreeListBoxEntry


Working copy of scilab MOTP metrics calculation

// clear all
xdel(winsid());
clear;
//mclose('all');

//opens file
fd_gt=mopen('/home/andreu/dataSets/people_tracking/reem/ground_truth/20140925_twoPeople.txt','r');
fd_res=mopen('/home/andreu/dataSets/people_tracking/reem/tracker_results/20140925_twoPeople_1_tree_all.txt','r');

//GROUND TRUTH PARSING
gt = list();
while (1) do
    gt_row = [];
    str_line = mgetl(fd_gt,1);
    if length(str_line) < 2 then
        break;
    else
        tkns = tokens(str_line,' ');
        for i=1:size(tkns,1)
            gt_row = [gt_row strtod(tkns(i))];
        end
        gt($+1) = gt_row;
    end
end

//TRACKER OPUTPUT PARSING
res = list();
while (1) do
    res_row=[];
    str_line = mgetl(fd_res,1);
    if length(str_line) < 2 then
        break;
    else
        tkns = tokens(str_line,' ');
        for i=1:size(tkns,1)
            res_row = [res_row strtod(tkns(i))];
        end
        res($+1) = res_row;
    end
end

//delete res rows out of ground truth time interval
while ( res(1)(1) < gt(1)(1) )
    res(1) = null();
end
while ( res($)(1) > gt($)(1) )
    res($) = null();
end

//interpolate ground truth at result time stamp point
ii = 1;
gt_intp = list();
for jj=1:size(res)
    ts = res(jj)(1);//get time stamp
    gt_intp_row = ts;
    while ( ts > gt(ii)(1) ) do
        ii = ii + 1;
    end
    ts_gt_1 = gt(ii-1)(1);//ts just before
    ts_gt_2 = gt(ii)(1);//ts just after
    alpha = (ts - ts_gt_1) / (ts_gt_2 - ts_gt_1);
    Nt_gt = ( min( size(gt(ii),2),size(gt(ii-1),2) ) -1 ) / 3; //number of targets
    if Nt_gt > 0 then
        for kk=1:Nt_gt
            //check "out of horizon"
            if ( gt(ii-1)(kk*3) < 0 ) | ( gt(ii-1)(kk*3) < 0 ) then
                gt_x = -1; //label as "out of horizon"
                gt_y = -1; //label as "out of horizon"
            else //compute linear interpolation
                gt_x = alpha*gt(ii)(kk*3) + (1-alpha)*gt(ii-1)(kk*3);
                gt_y = alpha*gt(ii)(kk*3+1) + (1-alpha)*gt(ii-1)(kk*3+1);
            end
            gt_intp_row = [gt_intp_row gt(ii-1)(kk*3-1) gt_x gt_y];
        end
    end
    gt_intp($+1) = gt_intp_row;
end

//plot ground truth and results
plot_flag = 1;
if plot_flag then
    fig1 = figure(0);
    fig1.background = 8;
    ah = gca();
    ah.isoview = "on";
    ah.x_label.text = "$y [m] (lateral)$";
    ah.x_label.font_size = 4;
    ah.y_label.text = "$x [m] (fwd)$";
    ah.y_label.font_size = 4;
    ah.grid = [1,1,1];
    ah.grid_position = "background";
    ah.auto_clear = "off";
    ah.auto_scale = "off";
    ah.data_bounds = [-3 0; 3 5];
    gt_colors = ["r+";"g+";"b+";"k+";"y+"];
    res_colors = ["r.";"g.";"b.";"k.";"y."];
    for jj=1:size(res)
        Nt_gt = (size(gt_intp(jj),2)-1) / 3; //number of targets
        if Nt_gt > 0 then
            for kk=1:Nt_gt
                plot(-gt_intp(jj)(kk*3+1),gt_intp(jj)(kk*3),gt_colors(pmodulo(gt_intp(jj)(kk*3-1)-1,5)+1));
            end
        end
        Nt_res = (size(res(jj),2)-1) / 4; //number of targets
        if Nt_res > 0 then
            for kk=1:Nt_res
                if res(jj)(kk*4-1) > 15 then
                    plot(-res(jj)(kk*4+1),res(jj)(kk*4),res_colors(pmodulo(res(jj)(kk*4-2)-1,5)+1));
                end
            end
        end
    end
end

//ESTABLISH BEST MAPPING between tracker output and ground truth, based on nearest neighbor

//COMPUTE DISTANCES -> MOTP

//CHECK MAPPING SWITCHES -> sw

//COUNT FALSE POSITIVES -> fp

//COUNT MISSINGS -> m

//COMPUTE MOTA = (sw,fp,m)

//close file
mclose(fd_gt);
mclose(fd_res);

// clear all
xdel(winsid());
clear;

//opens file
fd_gt=mopen('/home/andreu/dataSets/people_tracking/reem/ground_truth/20140925_twoPeople.txt','r');
fd_res=mopen('/home/andreu/dataSets/people_tracking/reem/tracker_results/20140925_twoPeople_1_tree_all.txt','r');

//GROUND TRUTH PARSING
gt = list();
while (1) do
    gt_row = [];
    str_line = mgetl(fd_gt,1);
    if length(str_line) < 2 then
        break;
    else
        tkns = tokens(str_line,' ');
        for i=1:size(tkns,1)
            gt_row = [gt_row strtod(tkns(i))];
        end
        gt($+1) = gt_row;
    end
end

//TRACKER OPUTPUT PARSING
res = list();
while (1) do
    res_row=[];
    str_line = mgetl(fd_res,1);
    if length(str_line) < 2 then
        break;
    else
        tkns = tokens(str_line,' ');
        for i=1:size(tkns,1)
            res_row = [res_row strtod(tkns(i))];
        end
        res($+1) = res_row;
    end
end

//delete res rows out of ground truth time interval
while ( res(1)(1) < gt(1)(1) )
    res(1) = null();
end
while ( res($)(1) > gt($)(1) )
    res($) = null();
end

//interpolate ground truth at result time stamp point
ii = 1;
gt_intp = list();
for jj=1:size(res)
    ts = res(jj)(1);//get time stamp
    gt_intp_row = ts;
    while ( ts > gt(ii)(1) ) do
        ii = ii + 1;
    end
    ts_gt_1 = gt(ii-1)(1);//ts just before
    ts_gt_2 = gt(ii)(1);//ts just after
    alpha = (ts - ts_gt_1) / (ts_gt_2 - ts_gt_1);
    Nt_gt = ( min( size(gt(ii)),size(gt(ii-1)) ) -1 ) / 3; //number of targets
    for kk=1:Nt_gt
        //check "out of horizon"
        if ( gt(ii-1)(ii*3) < 0 ) | ( gt(ii-1)(ii*3) < 0 ) then
            gt_x = -1; //label as "out of horizon"
        end
        else //compute linear interpolation
            gt_x = alpha*gt(ii-1)(kk*3) + (1-alpha)*gt(ii)(kk*3);
            gt_y = alpha*gt(ii-1)(kk*3+1) + (1-alpha)*gt(ii)(kk*3+1);
            gt_intp_row = [gt_intp_row gt(ii-1)(kk*3-1) gt_x gt_y];
        end
        gt_intp($+1)
    end
end

//Compute performance indexes

//ESTABLISH BEST MAPPING

//COMPUTE DISTANCES -> MOTP

//CHECK MAPPING SWITCHES -> sw

//COUNT FALSE POSITIVES -> fp

//COUNT MISSINGS -> m

//COMPUTE MOTA = (sw,fp,m)

end

//close file
mclose(fd_gt);
mclose(fd_res);


sb120: #i111278# disabled failing tests for now

#i98339 -o svx.AccessibleControlShape
#i111278 -o svx.AccessibleEditableTextPara
#i111252 -o svx.AccessibleGraphicShape
#i46736 -o svx.AccessibleImageBullet
#i111252 -o svx.AccessibleOLEShape
#i111252 -o svx.AccessiblePageShape
#i111216 -o svx.AccessiblePresentationGraphicShape
#i111216 -o svx.AccessiblePresentationOLEShape
#i85539 -o svx.AccessiblePresentationShape
-o svx.AccessibleShape
#i90294 -o svx.GraphicExporter
-o svx.SvxDrawPage
#i85501 -o svx.SvxGraphCtrlAccessibleContext
#i87746 -o svx.SvxGraphicObject
#i85263 -o svx.SvxShape
#i87746 -o svx.SvxShapeCircle
-o svx.SvxShapeCollection
#i85263 -o svx.SvxShapeConnector
#i87746 -o svx.SvxShapeControl
#i87746 -o svx.SvxShapeDimensioning
#i87746 -o svx.SvxShapeGroup
#i87746 -o svx.SvxShapePolyPolygon
#i87746 -o svx.SvxShapePolyPolygonBezier
-o svx.SvxUnoNumberingRules
-o svx.SvxUnoText
-o svx.SvxUnoTextContent
-o svx.SvxUnoTextContentEnum
-o svx.SvxUnoTextCursor
-o svx.SvxUnoTextField
-o svx.SvxUnoTextRange
-o svx.SvxUnoTextRangeEnumeration

#i98339 -o svx.AccessibleControlShape
-o svx.AccessibleEditableTextPara
#i111252 -o svx.AccessibleGraphicShape
#i46736 -o svx.AccessibleImageBullet
#i111252 -o svx.AccessibleOLEShape
#i111252 -o svx.AccessiblePageShape
#i111216 -o svx.AccessiblePresentationGraphicShape
#i111216 -o svx.AccessiblePresentationOLEShape
#i85539 -o svx.AccessiblePresentationShape
-o svx.AccessibleShape
#i90294 -o svx.GraphicExporter
-o svx.SvxDrawPage
#i85501 -o svx.SvxGraphCtrlAccessibleContext
#i87746 -o svx.SvxGraphicObject
#i85263 -o svx.SvxShape
#i87746 -o svx.SvxShapeCircle
-o svx.SvxShapeCollection
#i85263 -o svx.SvxShapeConnector
#i87746 -o svx.SvxShapeControl
#i87746 -o svx.SvxShapeDimensioning
#i87746 -o svx.SvxShapeGroup
#i87746 -o svx.SvxShapePolyPolygon
#i87746 -o svx.SvxShapePolyPolygonBezier
-o svx.SvxUnoNumberingRules
-o svx.SvxUnoText
-o svx.SvxUnoTextContent
-o svx.SvxUnoTextContentEnum
-o svx.SvxUnoTextCursor
-o svx.SvxUnoTextField
-o svx.SvxUnoTextRange
-o svx.SvxUnoTextRangeEnumeration


INTEGRATION: CWS impress34 (1.4.88); FILE MERGED 2005/02/17 12:58:46 sw 1.4.88.1: #i26264#

-o sd.SdXImpressDocument
-o sd.SdXCustomPresentationAccess
-o sd.SdUnoOutlineView
-o sd.SdUnoPresView
#i35935#-o sd.AccessibleDrawDocumentView
-o sd.AccessibleOutlineView
#i35935#-o sd.AccessibleSlideView
-o sd.SdDocLinkTargets
-o sd.SdDrawPage
-o sd.SdGenericDrawPage
-o sd.SdLayer
-o sd.SdLayerManager
-o sd.SdMasterPage
-o sd.SdMasterPagesAccess
-o sd.SdPageLinkTargets
-o sd.SdXCustomPresentation
-o sd.SdXPresentation
-o sd.SdXShape
-o sd.SdUnoDrawView
-o sd.SdDrawPagesAccess

-o sd.SdXImpressDocument
-o sd.SdXCustomPresentationAccess
-o sd.SdUnoOutlineView
-o sd.SdUnoPresView
-o sd.AccessibleDrawDocumentView
-o sd.AccessibleOutlineView
#i35935#-o sd.AccessibleSlideView
-o sd.SdDocLinkTargets
-o sd.SdDrawPage
-o sd.SdGenericDrawPage
-o sd.SdLayer
-o sd.SdLayerManager
-o sd.SdMasterPage
-o sd.SdMasterPagesAccess
-o sd.SdPageLinkTargets
-o sd.SdXCustomPresentation
-o sd.SdXPresentation
-o sd.SdXShape
-o sd.SdUnoDrawView
-o sd.SdDrawPagesAccess


INTEGRATION: CWS unoapi3 (1.6.116); FILE MERGED 2008/01/24 19:48:15 cn 1.6.116.2: #i84995# update lists with issues 2008/01/24 09:42:19 cn 1.6.116.1: #i84995# update ists with issues

-o svx.AccessibleControlShape
-o svx.AccessibleEditableTextPara
-o svx.AccessibleGraphicShape
#i46736 -o svx.AccessibleImageBullet
-o svx.AccessibleOLEShape
-o svx.AccessiblePageShape
-o svx.AccessiblePresentationGraphicShape
-o svx.AccessiblePresentationOLEShape
#i85539 -o svx.AccessiblePresentationShape
-o svx.AccessibleShape
-o svx.GraphicExporter
-o svx.SvxDrawPage
#i85501 -o svx.SvxGraphCtrlAccessibleContext
-o svx.SvxGraphicObject
#i85263 -o svx.SvxShape
-o svx.SvxShapeCircle
-o svx.SvxShapeCollection
#i85263 -o svx.SvxShapeConnector
-o svx.SvxShapeControl
-o svx.SvxShapeDimensioning
-o svx.SvxShapeGroup
-o svx.SvxShapePolyPolygon
-o svx.SvxShapePolyPolygonBezier
-o svx.SvxUnoNumberingRules
-o svx.SvxUnoText
-o svx.SvxUnoTextContent
-o svx.SvxUnoTextContentEnum
-o svx.SvxUnoTextCursor
-o svx.SvxUnoTextField
-o svx.SvxUnoTextRange
-o svx.SvxUnoTextRangeEnumeration

-o svx.SvxShapeDimensioning
#-o svx.SvxShapeControl
-o svx.SvxGraphicObject
-o svx.AccessibleGraphicShape
-o svx.AccessibleOLEShape
#-o svx.AccessiblePageShape
-o svx.AccessiblePresentationGraphicShape
-o svx.AccessiblePresentationOLEShape
#-o svx.AccessibleShape
#-o svx.GraphicExporter
-o svx.SvxDrawPage
#-o svx.SvxShape
-o svx.SvxShapeCircle
-o svx.SvxShapeCollection
#-o svx.SvxShapeConnector
-o svx.SvxShapeGroup
#-o svx.SvxShapePolyPolygon
#-o svx.SvxShapePolyPolygonBezier
-o svx.SvxUnoNumberingRules
-o svx.SvxUnoText
#-o svx.SvxUnoTextContent
-o svx.SvxUnoTextContentEnum
#-o svx.SvxUnoTextCursor
-o svx.SvxUnoTextField
#-o svx.SvxUnoTextRange
-o svx.SvxUnoTextRangeEnumeration
-o svx.AccessibleShape
-o svx.SvxGraphCtrlAccessibleContext
-o svx.AccessibleControlShape
### i58062 ###
-o svx.AccessibleEditableTextPara
### i57892 ###
#-o svx.AccessiblePresentationShape


fix for SCHEDULING-1393

fix for SCHEDULING-1393

git-svn-id: 27916816d6cfa57849e9a885196bf7392b80e1ac@20855 28e8926c-6b08-0410-baaa-805c5e19b8d6

function [] = PAinit()

    global ('PA_initialized', 'PA_scheduler_dir')

    jautoUnwrap(%t);

    version = ver();
    if strtod(part(version(1,2),1)) < 5
        error('This toolkit cannot be run on a version of Scilab anterior to version 5');
    end
    if ~exists('PA_scheduler_dir')
        error('The environment variable SCHEDULER_HOME must be defined, use setenv to define it in Scilab');
    end
    // disp(PA_scheduler_dir)
    if ~isdir(PA_scheduler_dir)
        error(strcat(['The path "',schedulerdir,'" doesn''t exist or is not a directory']));
    end
    plugins_dir = fullfile(PA_scheduler_dir,'plugins');
    if isdir(plugins_dir) then
        release_dir = listfiles(fullfile(PA_scheduler_dir,'plugins','org.ow2.proactive.scheduler.lib_*'));
        dist_lib_dir = fullfile(release_dir,'lib')
    else
        dist_lib_dir = fullfile(PA_scheduler_dir,'dist','lib');
    end
    schedjar=fullfile(dist_lib_dir,'ProActive.jar');
    if length(fileinfo(schedjar)) == 0
        error(strcat(['Can''t locate the scheduler jar at ""';schedjar;'"" , please make sure that SCHEDULER_HOME refers to the correct directory.']));
    end
    opt=PAoptions();

    jimport java.io.File;

    // Log4J file
    log4jFile = File.new(strcat([PA_scheduler_dir, filesep(), 'config', filesep(), 'log4j', filesep(), 'log4j-client']));
    log4jFileUri = jinvoke(log4jFile,'toURI');
    urlLog4jFile = jinvoke(log4jFileUri,'toURL');
    finalstring = jinvoke(urlLog4jFile,'toExternalForm');
    system_setproperty('log4j.configuration',finalstring);
    system_setproperty('proactive.configuration', opt.ProActiveConfiguration);

    // Policy
    system_setproperty('java.security.policy',strcat([PA_scheduler_dir, filesep(), 'config', filesep(), 'security.java.policy-client']));
    jremove(log4jFile);

    sep=pathsep();

    // Add ProActive Scheduler to the scilab classpath
    initcp = javaclasspath();
    if strcmp(getos(),'Windows') == 0
        for i=1:size(initcp,1)
            initcp(i)=getlongpathname(strsubst(initcp(1),'%20',' '))
        end
    end

    listjars = opt.ProActiveJars;

    cp = initcp;

    for i=1:size(listjars,1)
        cp = [cp; fullfile(dist_lib_dir,listjars(i).entries)];
    end

    javaclasspath(cp);

    // Call the native JNI connection to the Scheduler classes
    //initEmbedded();

    PA_initialized = 1;

endfunction

function [] = PAinit()

    global ('PA_initialized', 'PA_scheduler_dir')

    jautoUnwrap(%t);

    version = ver();
    if strtod(part(version(1,2),1)) < 5
        error('This toolkit cannot be run on a version of Scilab anterior to version 5');
    end
    if ~exists('PA_scheduler_dir')
        error('The environment variable SCHEDULER_HOME must be defined, use setenv to define it in Scilab');
    end
    // disp(PA_scheduler_dir)
    if ~isdir(PA_scheduler_dir)
        error(strcat(['The path "',schedulerdir,'" doesn''t exist or is not a directory']));
    end
    plugins_dir = fullfile(PA_scheduler_dir,'plugins');
    if isdir(plugins_dir) then
        release_dir = listfiles(fullfile(PA_scheduler_dir,'plugins','org.ow2.proactive.scheduler.lib_*'));
        dist_lib_dir = fullfile(release_dir,'lib')
    else
        dist_lib_dir = fullfile(PA_scheduler_dir,'dist','lib');
    end
    schedjar=fullfile(dist_lib_dir,'ProActive.jar');
    if length(fileinfo(schedjar)) == 0
        error(strcat(['Can''t locate the scheduler jar at ""';schedjar;'"" , please make sure that SCHEDULER_HOME refers to the correct directory.']));
    end
    opt=PAoptions();

    jimport java.io.File;

    // Log4J file
    log4jFile = File.new(strcat([PA_scheduler_dir, filesep(), 'config', filesep(), 'log4j', filesep(), 'log4j-client']));
    log4jFileUri = jinvoke(log4jFile,'toURI');
    urlLog4jFile = jinvoke(log4jFileUri,'toURL');
    finalstring = jinvoke(urlLog4jFile,'toExternalForm');
    system_setproperty('log4j.configuration',finalstring);
    system_setproperty('proactive.configuration', opt.ProActiveConfiguration);

    // Policy
    system_setproperty('java.security.policy',strcat([PA_scheduler_dir, filesep(), 'config', filesep(), 'security.java.policy-client']));
    jremove(log4jFile);

    sep=pathsep();

    // Add ProActive Scheduler to the scilab classpath
    initcp = javaclasspath();
    if strcmp(getos(),'Windows') == 0
        for i=1:size(initcp,1)
            initcp(i)=getlongpathname(strsubst(initcp(1),'%20',' '))
        end
    end

    listjars = opt.ProActiveJars;

    cp = initcp;

    for i=1:size(listjars,1)
        cp = [cp; fullfile(dist_lib_dir,listjars(i).entries)];
    end

    javaclasspath(cp);

    // Call the native JNI connection to the Scheduler classes
    //initEmbedded();

    PA_initialized = 1;
    predef(1);

endfunction


git-svn-id: svn+ssh://scm.gforge.inria.fr/svn/proactive/trunk@3628 28e8926c-6b08-0410-baaa-805c5e19b8d6

//need to initialize variable n
for i=1:n,
  for j=1:n,
    if i==j then
      x(i,j)=2;
    else x(i,j)=4;
    end;
  end;
end;

y=tril(x);


More accurate firmware checking

More accurate firmware checking

function [fw_ver,fw_ver_str, res] = mdaq_fw_version_url()
    res = mdaq_system_ping();
    fw_ver = [];
    fw_ver_str =[];

    if res then
        [logfile mlinkLog] = getURL(mdaq_get_ip()+"/log/mlink-server.log", TMPDIR);
        fw_ver_str = part(mlinkLog,strindex(mlinkLog, ' ver: ')+5:strindex(mlinkLog, 'build:')-1);
        fw_ver = strtod(strsplit(fw_ver_str, '.'));
    end
endfunction

function [fw_ver,fw_ver_str, res] = mdaq_fw_version_url()
    res = mdaq_system_ping();
    fw_ver = [];
    fw_ver_str =[];

    if res then
        [logfile mlinkLog] = getURL(mdaq_get_ip()+"/log/mlink-server.log", TMPDIR);
        fw_ver_str = part(mlinkLog,strindex(mlinkLog, 'ver: ')+5:strindex(mlinkLog, 'build:')-1);
        fw_ver = strtod(strsplit(fw_ver_str, '.'));
    end
endfunction


Rename mdaq_ip_set to mdaqSetIP in mdaqPing printf

function result = mdaqPing()
    [mdaq_ip_addr, res] = mdaq_get_ip();
    if res < 0 then
        disp("Unable to get MicroDAQ IP address - run microdaq_setup!");
        result = %F;
    else
        mprintf('Connecting to MicroDAQ@%s...',mdaq_ip_addr);
        connection_id = mdaqOpen();
        if connection_id < 0 then
            mprintf(' ERROR!\nUnable to connect to MicroDAQ device, check your configuration!\n');
            mprintf('Scilab is configured with following settings:\n');
            mprintf('IP address: %s, port %d\n', mdaq_ip_addr, 4343);
            mprintf('If MicroDAQ has different IP address use mdaqSetIP function to set correct IP address.\n\n');
            result = %F;
        else
            mprintf('OK!\n');
            mdaq_disconnect(connection_id);
            result = %T;
        end
    end
endfunction

function result = mdaqPing()
    [mdaq_ip_addr, res] = mdaq_get_ip();
    if res < 0 then
        disp("Unable to get MicroDAQ IP address - run microdaq_setup!");
        result = %F;
    else
        mprintf('Connecting to MicroDAQ@%s...',mdaq_ip_addr);
        connection_id = mdaqOpen();
        if connection_id < 0 then
            mprintf(' ERROR!\nUnable to connect to MicroDAQ device, check your configuration!\n');
            mprintf('Scilab is configured with following settings:\n');
            mprintf('IP address: %s, port %d\n', mdaq_ip_addr, 4343);
            mprintf('If MicroDAQ has different IP address use mdaq_ip_set to set correct IP address.\n\n');
            result = %F;
        else
            mprintf('OK!\n');
            mdaq_disconnect(connection_id);
            result = %T;
        end
    end
endfunction


Don't change directory when buiilding block code

function mdaq_block_build(debug_build)
    if  check_mdaq_compiler() == %F then
        disp("ERROR: Compiler not found - run microdaq_setup! ");
        return;
    end

    p_dir = pwd();
    mprintf(" ### Building user block macros...\n")
    macros_path = mdaq_toolbox_path() + "macros" + filesep() + "user_blocks" + filesep();
    tbx_build_macros("microdaq", macros_path);

    blocks = [];
    cd(macros_path);
    macros = ls("*_sim.sci")
    for i=1:size(macros,'*')
        blocks(i) = part(macros(i), 1:length(macros(i)) - 8);
    end

    cd(mdaq_toolbox_path());
    tbx_build_blocks(mdaq_toolbox_path(), blocks, "macros" + filesep() + "user_blocks");
// TODO: load newly created block upon creation - avoid Scilab restart
//    root_tlbx = mdaq_toolbox_path();
//    if isfile(root_tlbx + filesep() + "macros" + filesep() + "user_blocks" + filesep() + "names")  == %T then
//        errcatch(999,"continue");
//        xcosPalDelete("MicroDAQ User");
//        pal = xcosPal("MicroDAQ User");
//        microdaq_blocks = mgetl( root_tlbx + filesep() + "macros" + filesep() + "user_blocks" + filesep() + "names");
//        microdaq_blocks = microdaq_blocks';
//
//        blocks = [];
//        for i=1:size(microdaq_blocks, "*")
//            if strstr(microdaq_blocks(i), "_sim") == ""
//                blocks = [blocks, microdaq_blocks(i)];
//            end
//        end
//
//        for i=1:size(blocks, "*")
//            h5  = ls(root_tlbx + "/images/h5/"  + blocks(i) + "." + ["sod" "h5"]);
//            gif = ls(root_tlbx + "/images/gif/" + blocks(i) + "." + ["png" "jpg" "gif"]);
//            svg = ls(root_tlbx + "/images/svg/" + blocks(i) + "." + ["png" "jpg" "gif" "svg"]);
//            pal = xcosPalAddBlock(pal, h5(1), gif(1), svg(1));
//        end
//
//        if ~xcosPalAdd(pal,"MicroDAQ User") then
//            error(msprintf(gettext("%s: Unable to export %s.\n"), "microdaq.start", "pal"));
//        end
//    end

    root_path = mdaq_toolbox_path();
    userlib_src_path = root_path + filesep() + "src" + filesep() + "c"+ filesep() + "userlib" + filesep();
    userlib_path = root_path + filesep() + "etc" + filesep() + "userlib" + filesep() + "lib" + filesep();

    chdir(userlib_src_path);
    GMAKE = root_path + "\etc\bin\gmake.exe";
    mprintf(" ### Building userlib...\n")
    if getenv('WIN32','NO')=='OK' then
        if argn(2) > 0 & argn(2) < 2 then
            if debug_build then
                unix_w(GMAKE + ' -f Makefile' + ' OPT_FLAG=-g');
            else
                unix_w(GMAKE + ' -f Makefile' );
            end

        else
            unix_w(GMAKE + ' -f Makefile' );
        end

    else
        if argn(2) > 0 & argn(2) < 2 then
            if debug_build then
                unix_w('make' + ' OPT_FLAG=-g')
            else
                unix_w('make')
            end
        else
            unix_w('make')
        end

    end

    if isfile("userlib.lib") then
        copyfile("userlib.lib", userlib_path);
    end
    chdir(p_dir);
endfunction

function mdaq_block_build(debug_build)
    if  check_mdaq_compiler() == %F then
        disp("ERROR: Compiler not found - run microdaq_setup! ");
        return;
    end

    mprintf(" ### Building user block macros...\n")
    macros_path = mdaq_toolbox_path() + "macros" + filesep() + "user_blocks" + filesep();
    tbx_build_macros("microdaq", macros_path);

    blocks = [];
    cd(macros_path);
    macros = ls("*_sim.sci")
    for i=1:size(macros,'*')
        blocks(i) = part(macros(i), 1:length(macros(i)) - 8);
    end

    p_dir = pwd();
    cd(mdaq_toolbox_path());
    tbx_build_blocks(mdaq_toolbox_path(), blocks, "macros" + filesep() + "user_blocks");

//    root_tlbx = mdaq_toolbox_path();
//    if isfile(root_tlbx + filesep() + "macros" + filesep() + "user_blocks" + filesep() + "names")  == %T then
//        errcatch(999,"continue");
//        xcosPalDelete("MicroDAQ User");
//        pal = xcosPal("MicroDAQ User");
//        microdaq_blocks = mgetl( root_tlbx + filesep() + "macros" + filesep() + "user_blocks" + filesep() + "names");
//        microdaq_blocks = microdaq_blocks';
//
//        blocks = [];
//        for i=1:size(microdaq_blocks, "*")
//            if strstr(microdaq_blocks(i), "_sim") == ""
//                blocks = [blocks, microdaq_blocks(i)];
//            end
//        end
//
//        for i=1:size(blocks, "*")
//            h5  = ls(root_tlbx + "/images/h5/"  + blocks(i) + "." + ["sod" "h5"]);
//            gif = ls(root_tlbx + "/images/gif/" + blocks(i) + "." + ["png" "jpg" "gif"]);
//            svg = ls(root_tlbx + "/images/svg/" + blocks(i) + "." + ["png" "jpg" "gif" "svg"]);
//            pal = xcosPalAddBlock(pal, h5(1), gif(1), svg(1));
//        end
//
//        if ~xcosPalAdd(pal,"MicroDAQ User") then
//            error(msprintf(gettext("%s: Unable to export %s.\n"), "microdaq.start", "pal"));
//        end
//    end

    root_path = mdaq_toolbox_path();
    userlib_src_path = root_path + filesep() + "src" + filesep() + "c"+ filesep() + "userlib" + filesep();
    userlib_path = root_path + filesep() + "etc" + filesep() + "userlib" + filesep() + "lib" + filesep();

    wd = pwd();
    chdir(userlib_src_path);
    GMAKE = root_path + "\etc\bin\gmake.exe";
    mprintf(" ### Building userlib...\n")
    if getenv('WIN32','NO')=='OK' then
        if argn(2) > 0 & argn(2) < 2 then
            if debug_build then
                unix_w(GMAKE + ' -f Makefile' + ' OPT_FLAG=-g');
            else
                unix_w(GMAKE + ' -f Makefile' );
            end

        else
            unix_w(GMAKE + ' -f Makefile' );
        end

    else
        if argn(2) > 0 & argn(2) < 2 then
            if debug_build then
                unix_w('make' + ' OPT_FLAG=-g')
            else
                unix_w('make')
            end
        else
            unix_w('make')
        end

    end

    if isfile("userlib.lib") then
        copyfile("userlib.lib", userlib_path);
    end
    chdir(p_dir);
endfunction


normaal tempo

normaal tempo

Fss = 16000; //the bitrate of the song
Speed = 1; //how fast the song will be played

[testsign,Fs,bits]=wavread("SCI/modules/sound/demos/filterTest2(anja).wav"); //reading the wav (music) file in a matrix
 //[testsign,Fs,bits]=wavread("SCI/modules/sound/demos/filterTest1(H-style).wav");

testsign = testsign(1,:); //when reading in the wav file it creates 2 channels (stereo) and we only need one (mono)
t = [1:1:length(testsign)]*1/Fs; //We do this to plot the testsign in function of the sample frequetion of the wav file

//filterontwerp BP met een orde van 100 die filterd van 800hz tot 2000hz
[BD_coeff, amplitude, frequentie] = wfir('bp',100,[800/Fss, 2000/Fss],'hm',[0 0]);
//bepalen van transfertfunctie van de filter
//maken van polynoom (veelterm)
BD_polynoom = poly(BD_coeff, 'z', 'coeff');
//omvormen van z-coeff naar 1/z coeff
BD_functie = horner(BD_polynoom, 1/%z);
//aangeven werken met discrete waarden
BD_lineair_system = syslin('d', BD_functie);
//filteren via scilab
BD_output = flts(testsign, BD_lineair_system);

//plot oorspronkelijk signaal
plot(t, testsign)
//plot gefilterd signaal
plot(t, BD_output, 'r');

//muziek afspelen afhankelijk van de speed
playsnd(BD_output,Speed*Fss);
//schrijven van muziek afhankelijk van speed
wavwrite(BD_output, Speed*Fss ,'SCI/modules/sound/demos/'+'yolo.wav');

Fss = 16000; //the bitrate of the song
Speed = 1.3; //how fast the song will be played

[testsign,Fs,bits]=wavread("SCI/modules/sound/demos/filterTest2(anja).wav"); //reading the wav (music) file in a matrix
 //[testsign,Fs,bits]=wavread("SCI/modules/sound/demos/filterTest1(H-style).wav");

testsign = testsign(1,:); //when reading in the wav file it creates 2 channels (stereo) and we only need one (mono)
t = [1:1:length(testsign)]*1/Fs; //We do this to plot the testsign in function of the sample frequetion of the wav file

//filterontwerp BP met een orde van 100 die filterd van 800hz tot 2000hz
[BD_coeff, amplitude, frequentie] = wfir('bp',100,[800/Fss, 2000/Fss],'hm',[0 0]);
//bepalen van transfertfunctie van de filter
//maken van polynoom (veelterm)
BD_polynoom = poly(BD_coeff, 'z', 'coeff');
//omvormen van z-coeff naar 1/z coeff
BD_functie = horner(BD_polynoom, 1/%z);
//aangeven werken met discrete waarden
BD_lineair_system = syslin('d', BD_functie);
//filteren via scilab
BD_output = flts(testsign, BD_lineair_system);

//plot oorspronkelijk signaal
plot(t, testsign)
//plot gefilterd signaal
plot(t, BD_output, 'r');

//muziek afspelen afhankelijk van de speed
playsnd(BD_output,Speed*Fss);
//schrijven van muziek afhankelijk van speed
wavwrite(BD_output, Speed*Fss ,'SCI/modules/sound/demos/'+'yolo.wav');