Fixed error with ADC, DAC block counter after load

function continueSimulation=pre_xcos_simulate(scs_m, needcompile)
    global %microdaq;
    %microdaq.private.has_mdaq_block = %F;
    continueSimulation = %T;
    look_for_mdaq_blocks = %T;

    //reset mdaq_adc, mdaq_dac block counters
    %microdaq.private.mdaq_dac_idx = 0;
    %microdaq.private.mdaq_adc_idx = 0;

    for i = 1:size(scs_m.objs)
        curObj= scs_m.objs(i);
        if (typeof(curObj) == "Block" & curObj.gui == "mdaq_setup")

            if scs_m.objs(i).model.rpar(1) == (-1) then
                scs_m.props.tf= 1.000D+12;
            else
                scs_m.props.tf=scs_m.objs(i).model.rpar(1);
            end

            // if model has microdaq block set real-time scaling to 1
            tmp = scs_m;
            scan_mdaq_blocks(tmp);
            if %microdaq.private.has_mdaq_block then
                scs_m.props.tol(5) = 1;
            end

            if %microdaq.dsp_loaded == %T then
                look_for_mdaq_blocks = %F;
                // if dsp is loaded set real-time scaling to 1
                scs_m.props.tol(5) = 1;

                [mdaq_ip_addr, result] = mdaq_get_ip();
                if result < 0 then
                    disp("Unable to get MicroDAQ IP address - run microdaq_setup!");
                    continueSimulation = %F;
                    %microdaq.dsp_loaded = %F;
                    break;
                end

                result = client_connect(mdaq_ip_addr, 4344);
                if result < 0 then
                    con = mdaq_open();
                    result = mlink_set_obj(con, "ext_mode", 1);
                    mdaq_close(con);
                    if result == -25 then
                        message("ERROR: Unable to connect - your are running model in Standalone mode!");
                    else
                        message("ERROR: Unable to connect to MicroDAQ - reboot device!")
                        %microdaq.dsp_loaded = %F;
                    end
                    continueSimulation = %F;
                    break;
                end
                disp('### Starting model in Ext mode...');

                //adc, dac quantity restriction (1), prevent error
                %microdaq.private.mdaq_dac_idx = 0;
                %microdaq.private.mdaq_adc_idx = 0;

                scan_mdaq_blocks(tmp);
                if %microdaq.private.has_mdaq_param_sim then
                    result = mdaq_open();
                    if result > -1 then
                        %microdaq.private.connection_id = result;
                    else
                        message("ERROR: Unable to connect to MicroDAQ device!");
                        continueSimulation = %F;
                        %microdaq.private.connection_id = -1;
                    end
                end
            end
        end
    end

    if look_for_mdaq_blocks then
        tmp = scs_m;
        scan_mdaq_blocks(tmp);
        if %microdaq.private.has_mdaq_block then
            disp("### Running model in simulation mode... ")
            result = mdaq_open();
            if result > -1 then
                %microdaq.private.connection_id = result;
            else
                message("ERROR: Unable to connect to MicroDAQ device!");
                continueSimulation = %F;
                %microdaq.private.connection_id = -1;
            end
        end
        %microdaq.private.mem_write_idx = 0;
        %microdaq.private.mem_read_idx = 0;
        %microdaq.private.to_file_idx = 0;

        %microdaq.private.mdaq_signal_id = 0;

    end

    scs_m=resume(scs_m)
endfunction

function continueSimulation=pre_xcos_simulate(scs_m, needcompile)
    global %microdaq;
    %microdaq.private.has_mdaq_block = %F;
    continueSimulation = %T;
    look_for_mdaq_blocks = %T;

    for i = 1:size(scs_m.objs)
        curObj= scs_m.objs(i);
        if (typeof(curObj) == "Block" & curObj.gui == "mdaq_setup")

            if scs_m.objs(i).model.rpar(1) == (-1) then
                scs_m.props.tf= 1.000D+12;
            else
                scs_m.props.tf=scs_m.objs(i).model.rpar(1);
            end

            // if model has microdaq block set real-time scaling to 1
            tmp = scs_m;
            scan_mdaq_blocks(tmp);
            if %microdaq.private.has_mdaq_block then
                scs_m.props.tol(5) = 1;
            end

            if %microdaq.dsp_loaded == %T then
                look_for_mdaq_blocks = %F;
                // if dsp is loaded set real-time scaling to 1
                scs_m.props.tol(5) = 1;

                [mdaq_ip_addr, result] = mdaq_get_ip();
                if result < 0 then
                    disp("Unable to get MicroDAQ IP address - run microdaq_setup!");
                    continueSimulation = %F;
                    %microdaq.dsp_loaded = %F;
                    break;
                end

                result = client_connect(mdaq_ip_addr, 4344);
                if result < 0 then
                    con = mdaq_open();
                    result = mlink_set_obj(con, "ext_mode", 1);
                    mdaq_close(con);
                    if result == -25 then
                        message("ERROR: Unable to connect - your are running model in Standalone mode!");
                    else
                        message("ERROR: Unable to connect to MicroDAQ - reboot device!")
                        %microdaq.dsp_loaded = %F;
                    end
                    continueSimulation = %F;
                    break;
                end
                disp('### Starting model in Ext mode...');

                //adc, dac quantity restriction (1), prevent error
                %microdaq.private.mdaq_dac_idx = 0;
                %microdaq.private.mdaq_adc_idx = 0;

                scan_mdaq_blocks(tmp);
                if %microdaq.private.has_mdaq_param_sim then
                    result = mdaq_open();
                    if result > -1 then
                        %microdaq.private.connection_id = result;
                    else
                        message("ERROR: Unable to connect to MicroDAQ device!");
                        continueSimulation = %F;
                        %microdaq.private.connection_id = -1;
                    end
                end
            end
        end
    end

    if look_for_mdaq_blocks then
        tmp = scs_m;
        scan_mdaq_blocks(tmp);
        if %microdaq.private.has_mdaq_block then
            disp("### Running model in simulation mode... ")
            result = mdaq_open();
            if result > -1 then
                %microdaq.private.connection_id = result;
            else
                message("ERROR: Unable to connect to MicroDAQ device!");
                continueSimulation = %F;
                %microdaq.private.connection_id = -1;
            end
        end
        %microdaq.private.mem_write_idx = 0;
        %microdaq.private.mem_read_idx = 0;
        %microdaq.private.to_file_idx = 0;
        %microdaq.private.mdaq_dac_idx = 0;
        %microdaq.private.mdaq_adc_idx = 0;

        %microdaq.private.mdaq_signal_id = 0;

    end

    scs_m=resume(scs_m)
endfunction


sb120: #i109939# disabled failing tests for now

-o forms.OButtonControl
-o forms.OButtonModel
-o forms.OCheckBoxControl
-o forms.OCheckBoxModel
-o forms.OComboBoxControl
-o forms.OComboBoxModel
-o forms.OCurrencyControl
-o forms.OCurrencyModel
#-o forms.ODatabaseForm
-o forms.ODateControl
-o forms.ODateModel
-o forms.OEditControl
-o forms.OEditModel
#i109939 -o forms.OFileControlModel
-o forms.OFixedTextModel
-o forms.OFormattedControl
-o forms.OFormattedFieldWrapper
# LSST EIN DOKUMENT OFFEN -o forms.OFormsCollection
-o forms.OGridControlModel
-o forms.OGroupBoxControl
-o forms.OGroupBoxModel
-o forms.OHiddenModel
-o forms.OImageButtonControl
-o forms.OImageButtonModel
-o forms.OImageControlControl
-o forms.OImageControlModel
-o forms.OListBoxControl
-o forms.OListBoxModel
-o forms.ONavigationBarControl
-o forms.ONavigationBarModel
-o forms.ONumericControl
-o forms.ONumericModel
-o forms.OPatternControl
-o forms.OPatternModel
-o forms.ORadioButtonControl
-o forms.ORadioButtonModel
-o forms.OScrollBarModel
-o forms.OSpinButtonModel
-o forms.OTimeControl
-o forms.OTimeModel

-o forms.OButtonControl
-o forms.OButtonModel
-o forms.OCheckBoxControl
-o forms.OCheckBoxModel
-o forms.OComboBoxControl
-o forms.OComboBoxModel
-o forms.OCurrencyControl
-o forms.OCurrencyModel
#-o forms.ODatabaseForm
-o forms.ODateControl
-o forms.ODateModel
-o forms.OEditControl
-o forms.OEditModel
-o forms.OFileControlModel
-o forms.OFixedTextModel
-o forms.OFormattedControl
-o forms.OFormattedFieldWrapper
# LSST EIN DOKUMENT OFFEN -o forms.OFormsCollection
-o forms.OGridControlModel
-o forms.OGroupBoxControl
-o forms.OGroupBoxModel
-o forms.OHiddenModel
-o forms.OImageButtonControl
-o forms.OImageButtonModel
-o forms.OImageControlControl
-o forms.OImageControlModel
-o forms.OListBoxControl
-o forms.OListBoxModel
-o forms.ONavigationBarControl
-o forms.ONavigationBarModel
-o forms.ONumericControl
-o forms.ONumericModel
-o forms.OPatternControl
-o forms.OPatternModel
-o forms.ORadioButtonControl
-o forms.ORadioButtonModel
-o forms.OScrollBarModel
-o forms.OSpinButtonModel
-o forms.OTimeControl
-o forms.OTimeModel


update

update

// CLEAR PATH
clear();
clearglobal();

// LOAD Functions
getd('./');

// get path to the offset measurement file:
// driftfile = uigetfile();
// /home/asander/Projekte/losCorredors/data/Waage/Kraftmessungen_Loko_WS16

driftfile = '../data/Waage/Kalibrierung/Waagendrift_clean.txt';
offsetDataRaw = fscanfMat(driftfile);

// xCalFile = uigetfile();
xCalFile = '../data/Waage/Kalibrierung/XKali_clean.txt';
xCalRaw = fscanfMat(xCalFile);

// yCalFile = uigetfile();
yCalFile = '../data/Waage/Kalibrierung/YKali_clean.txt';
yCalRaw = fscanfMat(yCalFile);

zCalFile = '../data/Waage/Kalibrierung/ZKali_clean.txt';
zCalRaw = fscanfMat(zCalFile);

langsamFile = '../data/Waage/Kraftmessungen_Loko_WS16/Aljoscha/langsam.txt';
langsamRaw = fscanfMat(langsamFile);

normalFile = '../data/Waage/Kraftmessungen_Loko_WS16/Aljoscha/angenehm.txt';
normalRaw = fscanfMat(normalFile);

schnellFile = '../data/Waage/Kraftmessungen_Loko_WS16/Aljoscha/schnell.txt';
schnellRaw = fscanfMat(schnellFile);

// FORMATTING OF THE FILE RAW FILE:
//Channel
//1 time
//2 x1+x2
//3 x3+x4
//4 y1+y4
//5 y2+y3
//6:89 z1:z4

// INDEXING OFF THE DATA STRUCTURES
// 2 -> X
// 3 -> Y
// 4 -> Z -> main axis, hence four channels

// OFFSET AND DRIFT
// combine the channels into a global data structure
offsetData(:,1) = offsetDataRaw(:,1);
offsetData(:,2) = offsetDataRaw(:,2) + offsetDataRaw(:,3);
offsetData(:,3) = offsetDataRaw(:,4) + offsetDataRaw(:,5);
offsetData(:,4) = offsetDataRaw(:,6) + offsetDataRaw(:,7) + offsetDataRaw(:,8) + offsetDataRaw(:,9);

// X AXIS CALIBRATION
// combine the channels into a global data structure
xCal(:,1) = xCalRaw(:,1);
xCal(:,2) = xCalRaw(:,2) + xCalRaw(:,3);
xCal(:,3) = xCalRaw(:,4) + xCalRaw(:,5);
xCal(:,4) = xCalRaw(:,6) + xCalRaw(:,7) + xCalRaw(:,8) + xCalRaw(:,9);

// Y AXIS CALIBRATION
// combine the channels into a global data structure
yCal(:,1) = yCalRaw(:,1);
yCal(:,2) = yCalRaw(:,2) + yCalRaw(:,3);
yCal(:,3) = yCalRaw(:,4) + yCalRaw(:,5);
yCal(:,4) = yCalRaw(:,6) + yCalRaw(:,7) + yCalRaw(:,8) + yCalRaw(:,9);

// Z AXIS CALIBRATION
// combine the channels into a global data structure
zCal(:,1) = zCalRaw(:,1);
zCal(:,2) = zCalRaw(:,2) + zCalRaw(:,3);
zCal(:,3) = zCalRaw(:,4) + zCalRaw(:,5);
zCal(:,4) = zCalRaw(:,6) + zCalRaw(:,7) + zCalRaw(:,8) + zCalRaw(:,9);

langsam(:,1) = langsamRaw(:,1);
langsam(:,2) = langsamRaw(:,2) + langsamRaw(:,3);
langsam(:,3) = langsamRaw(:,4) + langsamRaw(:,5);
langsam(:,4) = langsamRaw(:,6) + langsamRaw(:,7) + langsamRaw(:,8) + langsamRaw(:,9);

normal(:,1) = normalRaw(:,1);
normal(:,2) = normalRaw(:,2) + normalRaw(:,3);
normal(:,3) = normalRaw(:,4) + normalRaw(:,5);
normal(:,4) = normalRaw(:,6) + normalRaw(:,7) + normalRaw(:,8) + normalRaw(:,9);

schnell(:,1) = schnellRaw(:,1);
schnell(:,2) = schnellRaw(:,2) + schnellRaw(:,3);
schnell(:,3) = schnellRaw(:,4) + schnellRaw(:,5);
schnell(:,4) = schnellRaw(:,6) + schnellRaw(:,7) + schnellRaw(:,8) + schnellRaw(:,9);

// calculate linear regression of the scale
[ scaleOffsetXSLOPE, scaleOffsetXOFFSET, scaleOffsetXSIGMA ]= reglin( offsetData(:,1)', offsetData(:,2)' );
[ scaleOffsetYSLOPE, scaleOffsetYOFFSET, scaleOffsetYSIGMA ]= reglin( offsetData(:,1)', offsetData(:,3)' );
[ scaleOffsetZSLOPE, scaleOffsetZOFFSET, scaleOffsetZSIGMA ]= reglin( offsetData(:,1)', offsetData(:,4)' );

// add labels n stuff to the plot and save it!
// plot(offsetData(:,1),[offsetData(:,2) scaleOffsetSLOPE * offsetData(:,1) + scaleOffsetYOFFSET])
// plot( offsetData(:,1), [offsetData(:,2) - scaleOffsetSLOPE * offsetData(:,1) - scaleOffsetYOFFSET] )

// messwerte (in VOLT) welche mit den gewichten korreliert werden müssen
meanVoltageX = [ mean(xCal(5000:6000, 2)), mean(xCal(10000:11000, 2)), mean(xCal(15000:16000, 2)), mean(xCal(20000:21000, 2)) ];
meanVoltageY = [ mean(yCal(5000:6000, 3)), mean(yCal(10000:11000, 3)), mean(yCal(15000:16000, 3)), mean(yCal(20000:21000, 3)) ];
meanVoltageZ = [ mean(zCal(5000:6000, 4)), mean(zCal(10000:11000, 4)), mean(zCal(20000:21000, 4)), mean(zCal(30000:31000, 4)) ];

kg = [0, 1, 3.6, 7.75]; // kalibrationsgewichte

[ scaleVoltageXSLOPE, scaleVoltageXOFFSET, scaleVoltageXSIGMA ] = reglin( meanVoltageX, kg );
[ scaleVoltageYSLOPE, scaleVoltageYOFFSET, scaleVoltageYSIGMA ] = reglin( meanVoltageY, kg );
[ scaleVoltageZSLOPE, scaleVoltageZOFFSET, scaleVoltageZSIGMA ] = reglin( meanVoltageZ, kg );

// plot(xCal(:,2))
// plot( (xCal(:,2) - (xCal(:,1)*scaleOffsetXSLOPE + scaleOffsetXOFFSET)) * scaleVoltageXSLOPE);
// plot( (yCal(:,3) - (yCal(:,1)*scaleOffsetYSLOPE + scaleOffsetYOFFSET)) * scaleVoltageYSLOPE);
// plot( (zCal(:,4) - (zCal(:,1)*scaleOffsetZSLOPE + scaleOffsetZOFFSET)) * scaleVoltageZSLOPE);
// plot(xCal(:,1), xCal(:,2))
// plot(xCal(:,1)

langsamSmooth.t = langsam(:,1)
langsamSmooth.x = WeightedMovingMean4(((langsam(:,2) - (langsam(:,1) * scaleOffsetXSLOPE + scaleOffsetZOFFSET  )) * scaleVoltageZSLOPE), 0.25, 0.5, 0.75, 0.5, 0.25)
langsamSmooth.y = WeightedMovingMean4(((langsam(:,3) - (langsam(:,1) * scaleOffsetXSLOPE + scaleOffsetZOFFSET  )) * scaleVoltageZSLOPE), 0.25, 0.5, 0.75, 0.5, 0.25)
langsamSmooth.z = WeightedMovingMean4(((langsam(:,4) - (langsam(:,1) * scaleOffsetXSLOPE + scaleOffsetZOFFSET  )) * scaleVoltageZSLOPE), 0.25, 0.5, 0.75, 0.5, 0.25)

normalSmooth.t = normal(:,1)
normalSmooth.x = WeightedMovingMean4(((normal(:,2) - (normal(:,1) * scaleOffsetXSLOPE + scaleOffsetZOFFSET  )) * scaleVoltageZSLOPE), 0.25, 0.5, 0.75, 0.5, 0.25)
normalSmooth.y = WeightedMovingMean4(((normal(:,3) - (normal(:,1) * scaleOffsetXSLOPE + scaleOffsetZOFFSET  )) * scaleVoltageZSLOPE), 0.25, 0.5, 0.75, 0.5, 0.25)
normalSmooth.z = WeightedMovingMean4(((normal(:,4) - (normal(:,1) * scaleOffsetXSLOPE + scaleOffsetZOFFSET  )) * scaleVoltageZSLOPE), 0.25, 0.5, 0.75, 0.5, 0.25)

schnellSmooth.t = schnell(:,1)
schnellSmooth.x = WeightedMovingMean4(((schnell(:,2) - (schnell(:,1) * scaleOffsetXSLOPE + scaleOffsetZOFFSET  )) * scaleVoltageZSLOPE), 0.25, 0.5, 0.75, 0.5, 0.25)
schnellSmooth.y = WeightedMovingMean4(((schnell(:,3) - (schnell(:,1) * scaleOffsetXSLOPE + scaleOffsetZOFFSET  )) * scaleVoltageZSLOPE), 0.25, 0.5, 0.75, 0.5, 0.25)
schnellSmooth.z = WeightedMovingMean4(((schnell(:,4) - (schnell(:,1) * scaleOffsetXSLOPE + scaleOffsetZOFFSET  )) * scaleVoltageZSLOPE), 0.25, 0.5, 0.75, 0.5, 0.25)

//plot( time, (langsam(:,4) - (langsam(:,1) * scaleOffsetXSLOPE + scaleOffsetZOFFSET  )) * scaleVoltageZSLOPE, 'r' )
//plot( time, Z_clean, 'g' )
//plot( time, Z_clean2, 'b')
//plot( time, Z_clean4, 'y')

plot(langsamSmooth.t, langsamSmooth.x, 'r')
plot(langsamSmooth.t, ((langsam(:,2) - (langsam(:,1) * scaleOffsetXSLOPE + scaleOffsetZOFFSET  )) * scaleVoltageZSLOPE), 'r')
plot(langsamSmooth.t, langsamSmooth.y, 'g')
plot(langsamSmooth.t, ((langsam(:,3) - (langsam(:,1) * scaleOffsetXSLOPE + scaleOffsetZOFFSET  )) * scaleVoltageZSLOPE), 'g')
plot(langsamSmooth.t, langsamSmooth.z, 'b')
plot(langsamSmooth.t, ((langsam(:,4) - (langsam(:,1) * scaleOffsetXSLOPE + scaleOffsetZOFFSET  )) * scaleVoltageZSLOPE), 'b')

// CLEAR PATH
clear();
clearglobal();

// LOAD Functions
getd('./');

// get path to the offset measurement file:
// driftfile = uigetfile();
// /home/asander/Projekte/losCorredors/data/Waage/Kraftmessungen_Loko_WS16

driftfile = '../data/Waage/Kalibrierung/Waagendrift_clean.txt';
offsetDataRaw = fscanfMat(driftfile);

// xCalFile = uigetfile();
xCalFile = '../data/Waage/Kalibrierung/XKali_clean.txt';
xCalRaw = fscanfMat(xCalFile);

// yCalFile = uigetfile();
yCalFile = '../data/Waage/Kalibrierung/YKali_clean.txt';
yCalRaw = fscanfMat(yCalFile);

zCalFile = '../data/Waage/Kalibrierung/ZKali_clean.txt';
zCalRaw = fscanfMat(zCalFile);

langsamFile = '../data/Waage/Kraftmessungen_Loko_WS16/Aljoscha/langsam.txt';
langsamRaw = fscanfMat(langsamFile);

normalFile = '../data/Waage/Kraftmessungen_Loko_WS16/Aljoscha/angenehm.txt';
normalRaw = fscanfMat(normalFile);

schnellFile = '../data/Waage/Kraftmessungen_Loko_WS16/Aljoscha/schnell.txt';
schnellRaw = fscanfMat(schnellFile);

// FORMATTING OF THE FILE RAW FILE:
//Channel
//1 time
//2 x1+x2
//3 x3+x4
//4 y1+y4
//5 y2+y3
//6:89 z1:z4

// INDEXING OFF THE DATA STRUCTURES
// 2 -> X
// 3 -> Y
// 4 -> Z -> main axis, hence four channels

// OFFSET AND DRIFT
// combine the channels into a global data structure
offsetData(:,1) = offsetDataRaw(:,1);
offsetData(:,2) = offsetDataRaw(:,2) + offsetDataRaw(:,3);
offsetData(:,3) = offsetDataRaw(:,4) + offsetDataRaw(:,5);
offsetData(:,4) = offsetDataRaw(:,6) + offsetDataRaw(:,7) + offsetDataRaw(:,8) + offsetDataRaw(:,9);

// X AXIS CALIBRATION
// combine the channels into a global data structure
xCal(:,1) = xCalRaw(:,1);
xCal(:,2) = xCalRaw(:,2) + xCalRaw(:,3);
xCal(:,3) = xCalRaw(:,4) + xCalRaw(:,5);
xCal(:,4) = xCalRaw(:,6) + xCalRaw(:,7) + xCalRaw(:,8) + xCalRaw(:,9);

// Y AXIS CALIBRATION
// combine the channels into a global data structure
yCal(:,1) = yCalRaw(:,1);
yCal(:,2) = yCalRaw(:,2) + yCalRaw(:,3);
yCal(:,3) = yCalRaw(:,4) + yCalRaw(:,5);
yCal(:,4) = yCalRaw(:,6) + yCalRaw(:,7) + yCalRaw(:,8) + yCalRaw(:,9);

// Z AXIS CALIBRATION
// combine the channels into a global data structure
zCal(:,1) = zCalRaw(:,1);
zCal(:,2) = zCalRaw(:,2) + zCalRaw(:,3);
zCal(:,3) = zCalRaw(:,4) + zCalRaw(:,5);
zCal(:,4) = zCalRaw(:,6) + zCalRaw(:,7) + zCalRaw(:,8) + zCalRaw(:,9);

langsam(:,1) = langsamRaw(:,1);
langsam(:,2) = langsamRaw(:,2) + langsamRaw(:,3);
langsam(:,3) = langsamRaw(:,4) + langsamRaw(:,5);
langsam(:,4) = langsamRaw(:,6) + langsamRaw(:,7) + langsamRaw(:,8) + langsamRaw(:,9);

normal(:,1) = normalRaw(:,1);
normal(:,2) = normalRaw(:,2) + normalRaw(:,3);
normal(:,3) = normalRaw(:,4) + normalRaw(:,5);
normal(:,4) = normalRaw(:,6) + normalRaw(:,7) + normalRaw(:,8) + normalRaw(:,9);

schnell(:,1) = schnellRaw(:,1);
schnell(:,2) = schnellRaw(:,2) + schnellRaw(:,3);
schnell(:,3) = schnellRaw(:,4) + schnellRaw(:,5);
schnell(:,4) = schnellRaw(:,6) + schnellRaw(:,7) + schnellRaw(:,8) + schnellRaw(:,9);

// calculate linear regression of the scale
[ scaleOffsetXSLOPE, scaleOffsetXOFFSET, scaleOffsetXSIGMA ]= reglin( offsetData(:,1)', offsetData(:,2)' );
[ scaleOffsetYSLOPE, scaleOffsetYOFFSET, scaleOffsetYSIGMA ]= reglin( offsetData(:,1)', offsetData(:,3)' );
[ scaleOffsetZSLOPE, scaleOffsetZOFFSET, scaleOffsetZSIGMA ]= reglin( offsetData(:,1)', offsetData(:,4)' );

// add labels n stuff to the plot and save it!
// plot(offsetData(:,1),[offsetData(:,2) scaleOffsetSLOPE * offsetData(:,1) + scaleOffsetYOFFSET])
// plot( offsetData(:,1), [offsetData(:,2) - scaleOffsetSLOPE * offsetData(:,1) - scaleOffsetYOFFSET] )

// messwerte (in VOLT) welche mit den gewichten korreliert werden müssen
meanVoltageX = [ mean(xCal(5000:6000, 2)), mean(xCal(10000:11000, 2)), mean(xCal(15000:16000, 2)), mean(xCal(20000:21000, 2)) ];
meanVoltageY = [ mean(yCal(5000:6000, 3)), mean(yCal(10000:11000, 3)), mean(yCal(15000:16000, 3)), mean(yCal(20000:21000, 3)) ];
meanVoltageZ = [ mean(zCal(5000:6000, 4)), mean(zCal(10000:11000, 4)), mean(zCal(20000:21000, 4)), mean(zCal(30000:31000, 4)) ];

kg = [0, 1, 3.6, 7.75]; // kalibrationsgewichte

[ scaleVoltageXSLOPE, scaleVoltageXOFFSET, scaleVoltageXSIGMA ] = reglin( meanVoltageX, kg );
[ scaleVoltageYSLOPE, scaleVoltageYOFFSET, scaleVoltageYSIGMA ] = reglin( meanVoltageY, kg );
[ scaleVoltageZSLOPE, scaleVoltageZOFFSET, scaleVoltageZSIGMA ] = reglin( meanVoltageZ, kg );

// plot(xCal(:,2))
// plot( (xCal(:,2) - (xCal(:,1)*scaleOffsetXSLOPE + scaleOffsetXOFFSET)) * scaleVoltageXSLOPE);
// plot( (yCal(:,3) - (yCal(:,1)*scaleOffsetYSLOPE + scaleOffsetYOFFSET)) * scaleVoltageYSLOPE);
// plot( (zCal(:,4) - (zCal(:,1)*scaleOffsetZSLOPE + scaleOffsetZOFFSET)) * scaleVoltageZSLOPE);
// plot(xCal(:,1), xCal(:,2))
// plot(xCal(:,1)

time = langsam(:,1)
Z_clean = WeightedMovingMean2(((langsam(:,4) - (langsam(:,1) * scaleOffsetXSLOPE + scaleOffsetZOFFSET  )) * scaleVoltageZSLOPE), 0.5, 0.75, 0.5)
Z_clean2 = WeightedMovingMean2(((langsam(:,4) - (langsam(:,1) * scaleOffsetXSLOPE + scaleOffsetZOFFSET  )) * scaleVoltageZSLOPE), 1, 1, 1)
Z_clean4 = WeightedMovingMean4(((langsam(:,4) - (langsam(:,1) * scaleOffsetXSLOPE + scaleOffsetZOFFSET  )) * scaleVoltageZSLOPE), 0.25, 0.5, 0.75, 0.5, 0.25)

plot( time, (langsam(:,4) - (langsam(:,1) * scaleOffsetXSLOPE + scaleOffsetZOFFSET  )) * scaleVoltageZSLOPE, 'r' )
plot( time, Z_clean, 'g' )
plot( time, Z_clean2, 'b')
plot( time, Z_clean4, 'y')


Check is compiler exists in path provided by user

function [] = microdaq_setup(arg1, arg2)

    if argn(2) <> 2 then
        mprintf("Description:\n");
        mprintf("\tConfigures MicroDAQ toolbox\n");
        mprintf("Usage:\n");
        mprintf("\tmicrodaq_setup(compilerPath, ipAddress)\n")
        mprintf("\tcompilerPath - the C6000 compiler installation path e.g ""c:\\ti\\c6000_7.4.21\\""\n");
        mprintf("\tipAddress - MicroDAQ IP address e.g ""10.10.1.1""\n");
        return
    end

    // check provided compiler install path
    if getos() == "Windows" then
        compilerFile = "cl6x.exe"
    else
        compilerFile = "cl6x"
    end
    if isfile(pathconvert(arg1 + "\bin\") + compilerFile) then
        CompilerRoot = getshortpathname(pathconvert(arg1, %F));
        ipAddress = arg2;
    else
        error("Unable to locate compiler (" + compilerFile + ") in " + arg1);
    end

    // set MicroDAQ IP address
    try
        mdaqSetIP(ipAddress)
    catch
        error("Unable to set MicroDAQ IP address");
    end

    // checking firmware
    [firmVer rawFrimVer res] = mdaq_fw_version_url();
    if res == %F then
        disp('Unable to verify MicroDAQ firmware - make sure you have latest MicroDAQ firmware installed!');
    elseif firmVer(1) < 2 then
        disp('Firmware version '+rawFrimVer+' is not supported.Please upgrade MicroDAQ firmware!');
    else
        result = mdaqOpen();
        if result < 0  then
            disp('Unable to connect to MicroDAQ device!');
        else
            global %microdaq;
            disp(%microdaq.model + ' connected, firmware version: '+rawFrimVer);
            mdaqClose(result);
        end
    end

    dir_temp = pwd();

    targetRoot = pathconvert(fileparts(get_function_path('microdaq_setup'))+"..\etc", %F);
    targetPathsFile = pathconvert(fileparts(get_function_path('microdaq_setup'))+"\..\rt_templates\target_paths.mk", %F);
    cpu0LinkerFile = pathconvert(targetRoot + '\sysbios\cpu0\configPkg\linker.cmd', %F);
    mkdir(pathconvert(targetRoot + '\sysbios\cpu0\configPkg', %F));
    cpu1LinkerFile = pathconvert(targetRoot + '\sysbios\cpu1\configPkg\linker.cmd', %F);
    mkdir(pathconvert(targetRoot + '\sysbios\cpu1\configPkg', %F));
    linkerTemplateFile = pathconvert(targetRoot + '\sysbios\linker.template', %F);

    [cpu0Linker, res1] = mopen(cpu0LinkerFile, 'w')
    [cpu1Linker, res2] = mopen(cpu1LinkerFile, 'w')
    if res1 < 0 | res2 < 0 then
        error("Unable to create linker file")
    end

    [linkerTemplate, res1] = mopen(linkerTemplateFile, 'r')
    if res1 < 0 then
        error("Unable to open linker template file")
    end
    linker = mgetl(linkerTemplate);
    mclose(linkerTemplate);

    [targetPaths, res1] = mopen(targetPathsFile, 'w');
    if res1 < 0 then
        error('Building failed. Cannot create file ''target_path.mk''');
    end

    mputl('-l""' + pathconvert(targetRoot + '\sysbios\boot.ae674', %F) + '""', cpu0Linker);
    mputl('-l""' + pathconvert(targetRoot + '\sysbios\ti.targets.rts6000.ae674', %F) + '""', cpu0Linker);
    mputl('-l""' + pathconvert(targetRoot + '\sysbios\cpu0\libs\sysbios_pe674.oe674', %F) + '""', cpu0Linker);
    mputl('-l""' + pathconvert(targetRoot + '\sysbios\cpu0\libs\sysbios.ae674', %F) + '""', cpu0Linker);
    mputl(linker, cpu0Linker);
    mclose(cpu0Linker)

    mputl('-l""' + pathconvert(targetRoot + '\sysbios\boot.ae674', %F) + '""', cpu1Linker);
    mputl('-l""' + pathconvert(targetRoot + '\sysbios\ti.targets.rts6000.ae674', %F) + '""', cpu1Linker);
    mputl('-l""' + pathconvert(targetRoot + '\sysbios\cpu1\libs\sysbios_pe674.oe674', %F) + '""', cpu1Linker);
    mputl('-l""' + pathconvert(targetRoot + '\sysbios\cpu1\libs\sysbios.ae674', %F) + '""', cpu1Linker);
    mputl(linker, cpu1Linker);
    mclose(cpu1Linker)

    mputl('# MicroDAQ paths', targetPaths)
    mputl('',targetPaths)
    mputl('CompilerRoot  = ' + CompilerRoot, targetPaths)
    mputl('TargetRoot    = '+ targetRoot, targetPaths)
    mclose(targetPaths)

    messagebox("MicroDAQ toolbox is configured and ready to use!", "Toolbox configuration", "info");
endfunction

function [] = microdaq_setup(arg1, arg2)
    sciVer = getversion('scilab');
    if sciVer(1) == 5 & argn(2) <> 2 then
        mprintf("Description:\n");
        mprintf("\tConfigures MicroDAQ toolbox\n");
        mprintf("Usage:\n");
        mprintf("\tmicrodaq_setup(compilerPath, ipAddress)\n")
        mprintf("\tcompilerPath - the C6000 compiler installation path e.g ""c:\\ti\\c6000_7.4.21\\""\n");
        mprintf("\tipAddress - MicroDAQ IP address e.g ""10.10.1.1""\n");
        return
    elseif sciVer(1) == 6 & argn(2) <> 1 then
        mprintf("Description:\n");
        mprintf("\tConfigures MicroDAQ toolbox\n");
        mprintf("Usage:\n");
        mprintf("\tmicrodaq_setup(ipAddress)\n")
        mprintf("\tipAddress - MicroDAQ IP address e.g ""10.10.1.1""\n");
        return
    end

    if sciVer(1) == 5 then
        if isfile(pathconvert(arg1 + "\bin\") + "cl6x.exe") | isfile(pathconvert(arg1 + "/bin/") + "cl6x") then
            CompilerRoot = getshortpathname(pathconvert(arg1, %F));
            ipAddress = arg2;
        else
            error("Unable to locate compiler in " + arg1);
        end
    elseif sciVer(1) == 6 then
        ipAddress = arg1;
        try
            mdaqSetIP(ipAddress)
        catch
            error("Unable to set MicroDAQ IP address");
        end
        disp('Setup complete - toolbox is ready to use!');
        return
    else
        error("Unsupported Scilab version");
    end

    // set MicroDAQ IP address
    try
        mdaqSetIP(ipAddress)
    catch
        error("Unable to set MicroDAQ IP address");
    end

    // checking firmware
    [firmVer rawFrimVer res] = mdaq_fw_version_url();
    if res == %F then
        disp('Unable to verify MicroDAQ firmware - make sure you have latest MicroDAQ firmware installed!');
    elseif firmVer(1) < 2 then
        disp('Firmware version '+rawFrimVer+' is not supported.Please upgrade MicroDAQ firmware!');
    else
        result = mdaqOpen();
        if result < 0  then
            disp('Unable to connect to MicroDAQ device!');
        else
            global %microdaq;
            disp(%microdaq.model + ' connected, firmware version: '+rawFrimVer);
            mdaqClose(result);
        end
    end

    dir_temp = pwd();

    targetRoot = pathconvert(fileparts(get_function_path('microdaq_setup'))+"..\etc", %F);
    targetPathsFile = pathconvert(fileparts(get_function_path('microdaq_setup'))+"\..\rt_templates\target_paths.mk", %F);
    cpu0LinkerFile = pathconvert(targetRoot + '\sysbios\cpu0\configPkg\linker.cmd', %F);
    mkdir(pathconvert(targetRoot + '\sysbios\cpu0\configPkg', %F));
    cpu1LinkerFile = pathconvert(targetRoot + '\sysbios\cpu1\configPkg\linker.cmd', %F);
    mkdir(pathconvert(targetRoot + '\sysbios\cpu1\configPkg', %F));
    linkerTemplateFile = pathconvert(targetRoot + '\sysbios\linker.template', %F);

    [cpu0Linker, res1] = mopen(cpu0LinkerFile, 'w')
    [cpu1Linker, res2] = mopen(cpu1LinkerFile, 'w')
    if res1 < 0 | res2 < 0 then
        error("Unable to create linker file")
    end

    [linkerTemplate, res1] = mopen(linkerTemplateFile, 'r')
    if res1 < 0 then
        error("Unable to open linker template file")
    end
    linker = mgetl(linkerTemplate);
    mclose(linkerTemplate);

    [targetPaths, res1] = mopen(targetPathsFile, 'w');
    if res1 < 0 then
        error('Building failed. Cannot create file ''target_path.mk''');
    end

    mputl('-l""' + pathconvert(targetRoot + '\sysbios\boot.ae674', %F) + '""', cpu0Linker);
    mputl('-l""' + pathconvert(targetRoot + '\sysbios\ti.targets.rts6000.ae674', %F) + '""', cpu0Linker);
    mputl('-l""' + pathconvert(targetRoot + '\sysbios\cpu0\libs\sysbios_pe674.oe674', %F) + '""', cpu0Linker);
    mputl('-l""' + pathconvert(targetRoot + '\sysbios\cpu0\libs\sysbios.ae674', %F) + '""', cpu0Linker);
    mputl(linker, cpu0Linker);
    mclose(cpu0Linker)

    mputl('-l""' + pathconvert(targetRoot + '\sysbios\boot.ae674', %F) + '""', cpu1Linker);
    mputl('-l""' + pathconvert(targetRoot + '\sysbios\ti.targets.rts6000.ae674', %F) + '""', cpu1Linker);
    mputl('-l""' + pathconvert(targetRoot + '\sysbios\cpu1\libs\sysbios_pe674.oe674', %F) + '""', cpu1Linker);
    mputl('-l""' + pathconvert(targetRoot + '\sysbios\cpu1\libs\sysbios.ae674', %F) + '""', cpu1Linker);
    mputl(linker, cpu1Linker);
    mclose(cpu1Linker)

    mputl('# MicroDAQ paths', targetPaths)
    mputl('',targetPaths)
    mputl('CompilerRoot  = ' + CompilerRoot, targetPaths)
    mputl('TargetRoot    = '+ targetRoot, targetPaths)
    mclose(targetPaths)

    disp('Setup complete - toolbox is ready to use!');
endfunction


Fix for blocking paramter

Fix for blocking paramter

function mdaq_ao_data_queue(arg1, arg2, arg3)
    global %microdaq;
    link_id = -1;

    if argn(2) == 2 then
        data = arg1;
        blocking = arg2;
    end

    if argn(2) == 3 then
        link_id = arg1;
        data = arg2;
        blocking = arg3;

        if link_id < 0 then
            error("ERROR: Invalid link ID!")
            return;
        end
    end

    if argn(2) > 3 | argn(2) < 2 then
        mprintf("Description:\n");
        mprintf("\tQueues AO channel data in scanning continuous mode.\n");
        mprintf("Usage:\n");
        mprintf("\tmdaq_ao_data_queue(link_id, data, blocking);\n")
        mprintf("\tlink_id - connection id returned by mdaq_open() (OPTIONAL)\n");
        mprintf("\tdata - AO scan data\n");
        mprintf("\tblocking - blocking mode (%T-enable, %F-disable)\n");
        return;
    end

    if argn(2) == 2 then
        link_id = mdaq_open();
        if link_id < 0 then
            error("ERROR: Unable to connect to MicroDAQ device!");
            return;
        end
    end

//    if size(data, "c") > 1 & size(data, "r") > 1 then
//        error("ERROR: Wrong AO scan data size");
//        return
//    end
    if blocking == %T then
            blocking = 1;
    elseif blocking == %F then
            blocking = 0;
    elseif blocking > 0 then
            blocking = 1;
    else
            blocking = 0;
    end

    data_size = size(data, "*");
    ch_count = %microdaq.private.ao_scan_ch_count;
    if ch_count <> size(data, "c") then
        if link_id > -1 then
            mdaq_close(link_id);
        end
        error("ERROR: Wrong AO scan data size or function is called before mdaq_ao_scan_init");
        return
    end

//MDAQ_API void sci_mlink_ao_data_queue(
//		IO		int 		*link_fd,
//		IN		double      *data,
//		IN		int			*data_size,
//		IN		int			*blocking,
//		OUT		int			*result)
//    mprintf("link_fd: %d\n", link_id)
//    disp(data);

    result = [];
    result = call("sci_mlink_ao_data_queue",..
                link_id, 1, "i",..
                data, 2, "d",..
                data_size, 3, "i",..
                blocking, 4, "i",..
                "out",..
                [1, 1], 5, "i");

    if result < 0  then
        if argn(2) == 2 then
            mdaq_close(link_id);
        end
        mdaq_error(result);
    end

    if argn(2) == 2 then
        mdaq_close(link_id);
    end
endfunction

function mdaq_ao_data_queue(arg1, arg2, arg3)
    global %microdaq;
    link_id = -1;

    if argn(2) == 2 then
        data = arg1;
        blocking = arg2;
    end

    if argn(2) == 3 then
        link_id = arg1;
        data = arg2;
        blocking = arg3;

        if link_id < 0 then
            error("ERROR: Invalid link ID!")
            return;
        end
    end

    if argn(2) > 3 | argn(2) < 2 then
        mprintf("Description:\n");
        mprintf("\tQueues AO channel data in scanning continuous mode.\n");
        mprintf("Usage:\n");
        mprintf("\tmdaq_ao_data_queue(link_id, data, blocking);\n")
        mprintf("\tlink_id - connection id returned by mdaq_open() (OPTIONAL)\n");
        mprintf("\tdata - AO scan data\n");
        mprintf("\tblocking - blocking mode (1-enable, 0-disable)\n");
        return;
    end

    if argn(2) == 2 then
        link_id = mdaq_open();
        if link_id < 0 then
            error("ERROR: Unable to connect to MicroDAQ device!");
            return;
        end
    end

//    if size(data, "c") > 1 & size(data, "r") > 1 then
//        error("ERROR: Wrong AO scan data size");
//        return
//    end
    if blocking == %T then
        blocking = 1;
    else
        blocking = 0;
    end

    data_size = size(data, "*");
    ch_count = %microdaq.private.ao_scan_ch_count;
    if ch_count <> size(data, "c") then
        if link_id > -1 then
            mdaq_close(link_id);
        end
        error("ERROR: Wrong AO scan data size or function is called before mdaq_ao_scan_init");
        return
    end

//MDAQ_API void sci_mlink_ao_data_queue(
//		IO		int 		*link_fd,
//		IN		double      *data,
//		IN		int			*data_size,
//		IN		int			*blocking,
//		OUT		int			*result)
//    mprintf("link_fd: %d\n", link_id)
//    disp(data);

    result = [];
    result = call("sci_mlink_ao_data_queue",..
                link_id, 1, "i",..
                data, 2, "d",..
                data_size, 3, "i",..
                blocking, 4, "i",..
                "out",..
                [1, 1], 5, "i");

    if result < 0  then
        if argn(2) == 2 then
            mdaq_close(link_id);
        end
        mdaq_error(result);
    end

    if argn(2) == 2 then
        mdaq_close(link_id);
    end
endfunction


Minor bugfix

Minor bugfix

//********************************************
//              DATA-IMPORT
//********************************************

// Öffnendialog starten

function [toes, ankle, knee, hip, shoulder, elbow, hand, neck] = readFromMDF(path)

// Einlesen der Daten
delimiter = " ";                                // Ist klar
regex_ignore = '/(Track).*$/';                  // Löschen aller mit "Track" beginnenden Zeilen
header = 5;                                     // Anzahl an Zeilen im Kopf
data = csvRead(path, delimiter, [], [], [], regex_ignore, [], header);

// Meta-Daten der Bilder
numberOfTracks = size(data,1) / max(data(:, 2))           // Number of Tracks
numberOfImages = max(data(:, 2))                          // Number of Images per Track
DELTA_T = 0.02;                                 // 50 FPS
CALIBRATION = 227; // 300;                              // Pix per m is correct, get the cal ratio from user via dialog box
Y_RESOLUTION = 479; //576 / 300;                             // Höhe in Pixeln  576!!! 479 bei FElix

// Kalibrieren
data = data / CALIBRATION;
Y_OFFSET = Y_RESOLUTION / CALIBRATION

// Eingelesenen Datensatz gemäß der Logik beim Tracken in 8 Datensätze unterteilen
// Jeder Datensatz wird logisch in x und y Werte unterteilt
// Gelenk.x und Gelenk.y enthalten jeweils eine 1 spaltige Matrix mit Koordinatenwerten
// Multiplikation mit -1 der y-Werte um "natürliches Koordinatensystem" zu erhalten
for i = 1 : numberOfTracks
    if i == 1 then
        toes.x = data(numberOfImages*(i - 1) + 1:i*numberOfImages , 3);
        toes.y = data(numberOfImages*(i - 1) + 1:i*numberOfImages , 4) * (-1) + Y_OFFSET;
    elseif i == 2 then
        ankle.x = data(numberOfImages*(i - 1) + 1:i*numberOfImages , 3);
        ankle.y = data(numberOfImages*(i - 1) + 1:i*numberOfImages , 4) * (-1) + Y_OFFSET;
    elseif i == 3 then
        knee.x = data(numberOfImages*(i - 1) + 1:i*numberOfImages , 3);
        knee.y = data(numberOfImages*(i - 1) + 1:i*numberOfImages , 4) * (-1) + Y_OFFSET;
    elseif i == 4 then
        hip.x = data(numberOfImages*(i - 1) + 1:i*numberOfImages , 3);
        hip.y = data(numberOfImages*(i - 1) + 1:i*numberOfImages , 4) * (-1) + Y_OFFSET;
    elseif i == 5 then
        shoulder.x = data(numberOfImages*(i - 1) + 1:i*numberOfImages , 3);
        shoulder.y = data(numberOfImages*(i - 1) + 1:i*numberOfImages , 4) * (-1) + Y_OFFSET;
    elseif i == 6 then
        elbow.x = data(numberOfImages*(i - 1) + 1:i*numberOfImages , 3);
        elbow.y = data(numberOfImages*(i - 1) + 1:i*numberOfImages , 4) * (-1) + Y_OFFSET;
    elseif i == 7 then
        hand.x = data(numberOfImages*(i - 1) + 1:i*numberOfImages , 3);
        hand.y = data(numberOfImages*(i - 1) + 1:i*numberOfImages , 4) * (-1) + Y_OFFSET;
    elseif i == 8 then
        neck.x = data(numberOfImages*(i - 1) + 1:i*numberOfImages , 3);
        neck.y = data(numberOfImages*(i - 1) + 1:i*numberOfImages , 4) * (-1) + Y_OFFSET;
    end
end

endfunction

function  [foot, leg, thigh, leg_total, upperarm, forearm, arm_total, trunk] = createLimbs(toes, ankle, knee, hip, shoulder, elbow, hand, neck)
    // Create Limbs

    foot = CalcCoM(ankle, toes, 0.5)
    leg = CalcCoM(knee, ankle, 0.433)
    thigh = CalcCoM(hip, knee, 0.433)
    leg_total = CalcCoM(hip, ankle, 0.447)
    upperarm = CalcCoM(shoulder, elbow, 0.436)
    forearm = CalcCoM(elbow, hand, 0.430)
    arm_total = CalcCoM(shoulder, hand, 0.5) // Nicht ganz richtig, da anthro Daten zwischen Ellenbogen und Finger anliegen
    trunk = CalcCoM(shoulder, hip, 0.5)

    // Add names

    foot.name = "foot"
    leg.name = "leg"
    thigh.name = "thigh"
    leg_total.name = "total leg"
    upperarm.name = "upper arm"
    forearm.name = "forearm"
    arm_total.name = "total arm"
    trunk.name = "trunk"

    // Add colors

    foot.color = color("red")
    leg.color = color("green")
    thigh.color = color("blue")
    leg_total.color = color("purple")
    upperarm.color = color("orange")
    forearm.color = color("darkgreen")
    arm_total.color = color("brown")
    trunk.color = color("yellow")

    // Add masses

    foot.mass = 0.0145 * proband_mass
    leg.mass = 0.0465 * proband_mass
    thigh.mass = 0.100 * proband_mass
    leg_total.mass = 0.161 * proband_mass
    upperarm.mass = 0.027 * proband_mass
    forearm.mass = 0.016 * proband_mass
    arm_total.mass = 0.050 * proband_mass
    trunk.mass = 0.497 * proband_mass

    // Add limb lengths

    foot.length = mean(GetLimbLength(ankle, toes))
    leg.length = mean(GetLimbLength(knee, ankle))
    thigh.length = mean(GetLimbLength(hip, knee))
    leg_total.length = mean(GetLimbLength(hip, ankle))
    upperarm.length = mean(GetLimbLength(shoulder, elbow))
    forearm.length = mean(GetLimbLength(elbow, hand))
    arm_total.length = mean(GetLimbLength(shoulder, hand))
    trunk.length = mean(GetLimbLength(shoulder, hip))

    // Add radii of gyration

    foot.RoG = foot.length * 0.475
    leg.RoG = leg.length * 0.302
    thigh.RoG = thigh.length * 0.323
    leg_total.RoG = leg_total.length * 0.326
    upperarm.RoG = upperarm.length * 0.322
    forearm.RoG = forearm.length * 0.302
    arm_total.RoG = arm_total.length * 0.368

    // Add moments of inertia

    foot.MoI = foot.mass * foot.RoG^2
    leg.MoI = leg.mass * leg.RoG^2
    thigh.MoI = thigh.mass * thigh.RoG^2
    leg_total.MoI = leg_total.mass * leg_total.RoG^2
    upperarm.MoI = upperarm.mass * upperarm.RoG^2
    forearm.MoI = forearm.mass * forearm.RoG^2
    arm_total.MoI = arm_total.mass * arm_total.RoG^2

endfunction

function [forcesRaw] = readScaleFile (filepath)
    data = fscanfMat(filepath);
    index = 1
    while data(index,1) < 3.20
        index = index + 1
    end
    forcesRaw = data( index:length(data(:,1)),: ) // -> no wonder no one likes matlab/scilab! wtf is this shit
endfunction

function [forces] = combineChannels (data, a, b, CoB)
    forces(:,1) = data(:,1);
    forces(:,2) = data(:,2) + data(:,3);
    forces(:,3) = data(:,4) + data(:,5);
    forces(:,4) = data(:,6) + data(:,7) + data(:,8) + data(:,9);
endfunction
function [forces] = combineChannels (data)
    forces(:,5) = (( data(:,6) + data(:,7) ) / ( data(:,6) + data(:,7) + data(:,8) + data(:,9) ))*2*b - b + CoB
endfunction


Add spaces for legibility purposes

Add spaces for legibility purposes

//  Author: Ali Ghahraei Figueroa
//
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.

//  Function to interpolate
//
//  Arguments:
//  n -> used to get the size of the matrix
//  leftTop -> A(beginning,beginning)
//  rightTop -> A(beginning,end)
//  leftBottom -> A(end,beginning)
//  rightBottom -> A(end,end)

function [heightField] = interpolation(n, leftTop, rightTop, leftBottom, rightBottom)
    MATRIX_LENGTH = (2 ** n) + 1

    heightField(1, 1) = leftTop
    heightField(1, MATRIX_LENGTH) = rightTop
    heightField(MATRIX_LENGTH, 1) = leftBottom
    heightField(MATRIX_LENGTH, MATRIX_LENGTH) = rightBottom

    increment = MATRIX_LENGTH - 1

    interpolationStart = ceil(MATRIX_LENGTH/2)

    i = interpolationStart
    while i >= 2
        for j = interpolationStart:increment:MATRIX_LENGTH
            distanceToEdge = i-1
            for k = i:increment:MATRIX_LENGTH
                heightField(k+distanceToEdge, j) = mean([heightField(k+distanceToEdge, j+distanceToEdge),heightField(k+distanceToEdge, j-distanceToEdge)])

                heightField(k-distanceToEdge, j) = mean([heightField(k-distanceToEdge, j+distanceToEdge),heightField(k-distanceToEdge, j-distanceToEdge)])

                heightField(k, j+distanceToEdge) = mean([heightField(k+distanceToEdge, j+distanceToEdge),heightField(k-distanceToEdge, j+distanceToEdge)])

                heightField(k, j-distanceToEdge) = mean([heightField(k+distanceToEdge, j-distanceToEdge),heightField(k-distanceToEdge, j-distanceToEdge)])

                heightField(k, j) = mean([heightField(k+distanceToEdge, j), heightField(k-distanceToEdge, j), heightField(k, j+distanceToEdge), heightField(k, j-distanceToEdge)])
            end
        end

        interpolationStart = ceil(interpolationStart/2)
        increment = increment/2
        i = i - floor(i/2)
    end
endfunction

//  Graph the provided example

function graphExample()
    n = 3
    [z] = interpolation(n, 1, 20, 5, 200)
    x = [1:1:2**n+1]
    plot3d(x,x,z)
endfunction


ADC oversampling - initial support

ADC oversampling - initial support

ADC with oversampling allows to get better accuracy

function [x,y,typ] = mdaq_adc(job,arg1,arg2)
    adc_desc = ["This block reads MicroDAQ analog inputs (AI).";
    "Select ADC type according to your hardware setup.";
    "";
    "output(1) - 16bit raw ADC value";
    "output(2) - measured value in volts";
    "";
    "Converter:";
    "   ADC01 - 8 channel,  166ksps, 12/16-bit, ±10V range";
    "   ADC02 - 8 channel,  600ksps, 12-bit, ±10V range";
    "   ADC03 - 16 channel, 600ksps, 12-bit, ±10V range";
    "   ADC04 - 8 channel,  500ksps, 16-bit, ±10V range";
    "   ADC05 - 16 channel, 500ksps, 16-bit, ±10V range";
    "";
    "Range: 5, 10";
    "";
    "Polarity:";
    "   1 - Unipolar";
    "   2 - Bipolar";
    "";
    "Mode:";
    "   0 - Single-ended";
    "   1 - Differential";
    "";
    "Set block parameters:"];

    adc_ch_lookup_table = [8,8,16,8,16];

    x=[];y=[];typ=[];
    select job
    case 'set' then
        x=arg1
        model=arg1.model;
        graphics=arg1.graphics;
        exprs=graphics.exprs;
        while %t do
            try
                getversion('scilab');
                [ok,adc_converter_str,adc_channels, adc_range,adc_polarity,adc_mode,oversamp_count,exprs]=..
                scicos_getvalue(adc_desc,..
                            ['Converter:';
                            'Channels:';
                            'Range:';
                            'Polarity:';
                            'Mode:';
                            'Oversampling:'],..
                            list('str',1,'vec',-1,'vec',1,'vec',1,'vec',1,'vec',1),exprs)
            catch
                [ok,adc_converter_str,adc_channels, adc_range,adc_polarity,adc_mode,oversamp_count,exprs]=..
                scicos_getvalue(adc_desc,..
                            ['Converter:';
                            'Channels:';
                            'Range:';
                            'Polarity:';
                            'Mode:';
                            'Oversampling:'],..
                            list('str',1,'vec',-1,'vec',1,'vec',1,'vec',1,'vec',1),exprs)
            end

            if ~ok then
                break
            end

            adc_converter_str = convstr(adc_converter_str, 'l');
            adc_converter = strtod(part(adc_converter_str, 4:5));
            if isnan(adc_converter) == %t | part(adc_converter_str, 1:3) <> "adc" then
                ok = %f;
                message("Wrong converter selected!");
            end

            if adc_converter > 5 | adc_converter < 1 then
                ok = %f;
                message("Wrong ADC converter selected!");
            end

            global %microdaq;
            if adc_converter <> %microdaq.private.mdaq_hwid(2) & %microdaq.private.mdaq_hwid(3) > 0 then
                message("Selected ADC converter is different than detected - run mdaq_hwinfo() for more details!");
            end

            n_channels = size(adc_channels);
            if n_channels(2) > adc_ch_lookup_table(adc_converter) then
                ok = %f;
                error_msg = 'Too many channels selected for ADC0' + string(adc_converter) + '!';
                message(error_msg);
            end

            if max(adc_channels) > adc_ch_lookup_table(adc_converter) then
                ok = %f;
                error_msg = 'Wrong channel number selected for ADC0' + string(adc_converter) + '!';
                message(error_msg);
            end

            if min(adc_channels) < 1 then
                ok = %f;
                error_msg = 'Wrong channel number selected for ADC0' + string(adc_converter) + '!';
                message(error_msg);
            end

            if adc_range <> 5 & adc_range <> 10 then
                ok = %f;
                message("Wrong ADC range selected - use 5 or 10!");
            end

            if adc_polarity < 1 | adc_polarity > 2 then
                ok = %f;
                message("Wrong polarity selected - use 1 or 2!");
            else
                if adc_converter > 1 & adc_polarity == 1 then
                    ok = %f;
                    message("This converter doesn''t support unipolar mode!");
                end
            end

            if adc_mode <> 0 & adc_mode <> 1 then
                ok = %f;
                message("Wrong ADC mode selected - use 0 or 1 to set single-ended or differential mode!");
            end

            if adc_mode == 1 & adc_converter <> 1 then
                message("This converter dones''t support differential mode!")
                of=%f;
            end

            if oversamp_count < 1 | oversamp_count > 16 then
                message("Wrong oversampling sample count - use 1-16 value!")
                of=%f;
            end

            if ok then
                [model,graphics,ok] = check_io(model,graphics, [], [n_channels(2),n_channels(2)], 1, []);
                graphics.exprs = exprs;
                model.rpar = [];
                model.ipar = [adc_converter;adc_range;adc_polarity;adc_mode;oversamp_count;n_channels(2);adc_channels'];
                model.dstate = [];
                x.graphics = graphics;
                x.model = model;
                break;
            end
        end
    case 'define' then
        adc_converter_str = [];
        adc_converter = 1;
        adc_channels = 1;
        n_channels = 1;
        adc_range = 10;
        adc_polarity = 2;
        adc_mode = 0;
        oversamp_count=1;
        model=scicos_model()
        model.sim=list('mdaq_adc_sim',5)
        model.in =[]
        model.out=[1;1]
        model.out2=[7;1]
        model.outtyp=[1;1]
        model.evtin=1
        model.rpar=[]
        model.ipar=[adc_converter;adc_range;adc_polarity;adc_mode;oversamp_count;1;adc_channels]
        model.dstate=[];
        model.blocktype='d'
        model.dep_ut=[%t %f]
        exprs=["ADC01";sci2exp(adc_channels);sci2exp(adc_range);sci2exp(adc_polarity); sci2exp(adc_mode);sci2exp(oversamp_count) ]
        gr_i=['xstringb(orig(1),orig(2),[''CH: '' ; string(adc_channels)],sz(1),sz(2),''fill'');']
        x=standard_define([4 3],model,exprs,gr_i)
        x.graphics.in_implicit=[];
        x.graphics.exprs=exprs;
        x.graphics.style=["blockWithLabel;verticalLabelPosition=center;displayedLabel=CH:%2$s;fontColor=#5f5f5f"]
    end
endfunction

function [x,y,typ] = mdaq_adc(job,arg1,arg2)
    adc_desc = ["This block reads MicroDAQ analog inputs (AI).";
    "Select ADC type according to your hardware setup.";
    "";
    "output(1) - 16bit raw ADC value";
    "output(2) - measured value in volts";
    "";
    "Converter:";
    "   ADC01 - 8 channel,  166ksps, 12/16-bit, ±10V range";
    "   ADC02 - 8 channel,  600ksps, 12-bit, ±10V range";
    "   ADC03 - 16 channel, 600ksps, 12-bit, ±10V range";
    "   ADC04 - 8 channel,  500ksps, 16-bit, ±10V range";
    "   ADC05 - 16 channel, 500ksps, 16-bit, ±10V range";
    "";
    "Range: 5, 10";
    "";
    "Polarity:";
    "   1 - Unipolar";
    "   2 - Bipolar";
    "";
    "Mode:";
    "   0 - Single-ended";
    "   1 - Differential";
    "";
    "Set block parameters:"];

    adc_ch_lookup_table = [8,8,16,8,16];

    x=[];y=[];typ=[];
    select job
    case 'set' then
        x=arg1
        model=arg1.model;
        graphics=arg1.graphics;
        exprs=graphics.exprs;
        while %t do
            try
                getversion('scilab');
                [ok,adc_converter_str,adc_channels, adc_range,adc_polarity,adc_mode,exprs]=..
                scicos_getvalue(adc_desc,..
                ['Converter:';
                'Channels:';
                'Range:';
                'Polarity:';
                'Mode:'],..
                list('str',1,'vec',-1,'vec',1,'vec',1,'vec',1),exprs)
            catch
                [ok,adc_converter_str,adc_channels, adc_range,adc_polarity,adc_mode,exprs]=..
                scicos_getvalue(adc_desc,..
                ['Converter:';
                'Channels:';
                'Range:';
                'Polarity:';
                'Mode:'],..
                list('str',1,'vec',-1,'vec',1,'vec',1,'vec',1),exprs)
            end

            if ~ok then
                break
            end

            adc_converter_str = convstr(adc_converter_str, 'l');
            adc_converter = strtod(part(adc_converter_str, 4:5));
            if isnan(adc_converter) == %t | part(adc_converter_str, 1:3) <> "adc" then
                ok = %f;
                message("Wrong converter selected!");
            end

            if adc_converter > 5 | adc_converter < 1 then
                ok = %f;
                message("Wrong ADC converter selected!");
            end

            global %microdaq;
            if adc_converter <> %microdaq.private.mdaq_hwid(2) & %microdaq.private.mdaq_hwid(3) > 0 then
                message("Selected ADC converter is different than detected - run mdaq_hwinfo() for more details!");
            end

            n_channels = size(adc_channels);
            if n_channels(2) > adc_ch_lookup_table(adc_converter) then
                ok = %f;
                error_msg = 'Too many channels selected for ADC0' + string(adc_converter) + '!';
                message(error_msg);
            end

            if max(adc_channels) > adc_ch_lookup_table(adc_converter) then
                ok = %f;
                error_msg = 'Wrong channel number selected for ADC0' + string(adc_converter) + '!';
                message(error_msg);
            end

            if min(adc_channels) < 1 then
                ok = %f;
                error_msg = 'Wrong channel number selected for ADC0' + string(adc_converter) + '!';
                message(error_msg);
            end

            if adc_range <> 5 & adc_range <> 10 then
                ok = %f;
                message("Wrong ADC range selected - use 5 or 10!");
            end

            if adc_polarity < 1 | adc_polarity > 2 then
                ok = %f;
                message("Wrong polarity selected - use 1 or 2!");
            else
                if adc_converter > 1 & adc_polarity == 1 then
                    ok = %f;
                    message("This converter doesn''t support unipolar mode!");
                end
            end

            if adc_mode <> 0 & adc_mode <> 1 then
                ok = %f;
                message("Wrong ADC mode selected - use 0 or 1 to set single-ended or differential mode!");
            end

            if adc_mode == 1 & adc_converter <> 1 then
                message("This converter dones''t support differential mode!")
                of=%f;
            end

            if ok then
                [model,graphics,ok] = check_io(model,graphics, [], [n_channels(2),n_channels(2)], 1, []);
                graphics.exprs = exprs;
                model.rpar = [];
                model.ipar = [adc_converter;adc_range;adc_polarity;adc_mode;n_channels(2);adc_channels'];
                model.dstate = [];
                x.graphics = graphics;
                x.model = model;
                break;
            end
        end
    case 'define' then
        adc_converter_str = [];
        adc_converter = 1;
        adc_channels = 1;
        n_channels = 1;
        adc_range = 10;
        adc_polarity = 2;
        adc_mode = 0;
        model=scicos_model()
        model.sim=list('mdaq_adc_sim',5)
        model.in =[]
        model.out=[1;1]
        model.out2=[7;1]
        model.outtyp=[1;1]
        model.evtin=1
        model.rpar=[]
        model.ipar=[adc_converter;adc_range;adc_polarity;adc_mode;1;adc_channels]
        model.dstate=[];
        model.blocktype='d'
        model.dep_ut=[%t %f]
        exprs=["ADC01";sci2exp(adc_channels);sci2exp(adc_range);sci2exp(adc_polarity); sci2exp(adc_mode)]
        gr_i=['xstringb(orig(1),orig(2),[''CH: '' ; string(adc_channels)],sz(1),sz(2),''fill'');']
        x=standard_define([4 3],model,exprs,gr_i)
        x.graphics.in_implicit=[];
        x.graphics.exprs=exprs;
        x.graphics.style=["blockWithLabel;verticalLabelPosition=center;displayedLabel=CH:%2$s;fontColor=#5f5f5f"]
    end
endfunction


Fix mdaq_dsp_start

Fix mdaq_dsp_start

Now function uses error instead of printing error description. In case
of error script containging mdaq_dsp_start will be interrupted

function result = mdaq_dsp_start( arg1, arg2, arg3 )
    // Check version compatibility
    [is_supp vers] = mdaq_is_working('mdaq_dsp_start');
    if is_supp == %F then
        error('ERROR: ' + vers)
        return;
    end

    global %microdaq;
    result = -1;

    if argn(2) == 2 then
        dsp_firmware = arg1;
        model_freq = arg2;
    end

    if argn(2) == 3 then
        link_id = arg1;
        dsp_firmware = arg2;
        model_freq = arg3;
        if link_id < 0 then
            disp("ERROR: Invalid link ID!")
            return;
        end
    end

    if argn(2) > 3 | argn(2) < 2 | isfile(dsp_firmware) <> %T then
        mprintf("Description:\n");
        mprintf("\tStarts DSP execution\n");
        mprintf("Usage:\n");
        mprintf("\tmdaq_dsp_start(linkId, dspFirmware, stepTime);\n")
        mprintf("\tlinkId - connection id returned by mdaq_open() (OPTIONAL)\n");
        mprintf("\tdspFirmware - XCos generated DSP application\n");
        mprintf("\stepTime - custom model mode step or -1 to keep Xcos settings\n");
        return;
    end

    if argn(2) == 2 then
        link_id = mdaq_open();
        if link_id < 0 then
            disp("ERROR: Unable to connect to MicroDAQ device!");
            return;
        end
    end

    res = mlink_dsp_load(link_id, dsp_firmware, '');
    if res < 0 then
        res = mlink_dsp_load(link_id, dsp_firmware, '');
        if res < 0 then
            if argn(2) == 2 then
                mdaq_close(link_id);
            end
            error(mdaq_error2(res), 10000 + abs(res));
        end
    end

    res = mlink_dsp_start(link_id, model_freq);
    if res < 0 then
        if argn(2) == 2 then
            mdaq_close(link_id);
        end
        error(mdaq_error2(res), 10000 + abs(res));
    end

    //Give time to start DSP firmware
    sleep(200);

    %microdaq.dsp_loaded = %T;
    res = mlink_set_obj(link_id, 'ext_mode', 1 );

    if argn(2) == 2 then
        mdaq_close(link_id);
    end

    if res == 0 then
        result = client_connect(mdaq_get_ip(), 4344);
        if result < 0 then
            disp("ERROR: Unable to initialize TCP data stream for Ext mode!")
            %microdaq.dsp_loaded = %F;
            return;
        end
        %microdaq.dsp_ext_mode = %T;
    else
        %microdaq.dsp_ext_mode = %F;
    end
    result = 0;
endfunction

function result = mdaq_dsp_start( arg1, arg2, arg3 )
    // Check version compatibility
    [is_supp vers] = mdaq_is_working('mdaq_dsp_start');
    if is_supp == %F then
        error('ERROR: ' + vers)
        return;
    end

    global %microdaq;
    result = -1;

    if argn(2) == 2 then
        dsp_firmware = arg1;
        model_freq = arg2;
    end

    if argn(2) == 3 then
        link_id = arg1;
        dsp_firmware = arg2;
        model_freq = arg3;
        if link_id < 0 then
            disp("ERROR: Invalid link ID!")
            return;
        end
    end

    if argn(2) > 3 | argn(2) < 2 | isfile(dsp_firmware) <> %T then
        mprintf("Description:\n");
        mprintf("\tStarts DSP execution\n");
        mprintf("Usage:\n");
        mprintf("\tmdaq_dsp_start(link_id, dsp_firmware);\n")
        mprintf("\tlink_id - connection id returned by mdaq_open() (OPTIONAL)\n");
        mprintf("\tdsp_firmware - XCos generated DSP application path\n");
        return;
    end

    if argn(2) == 2 then
        link_id = mdaq_open();
        if link_id < 0 then
            disp("ERROR: Unable to connect to MicroDAQ device!");
            return;
        end
    end

    res = mlink_dsp_load(link_id, dsp_firmware, '');
    if res < 0 then
        res = mlink_dsp_load(link_id, dsp_firmware, '');
        if res < 0 then
            disp('ERROR: Unable to load DSP firmware - reboot MicroDAQ device!');
            if argn(2) == 1 then
                mdaq_close(link_id);
            end
            return;
        end
    end

    res = mlink_dsp_start(link_id, model_freq);
    if res < 0 then
        disp("ERROR: Unable to start DSP application!");
        if argn(2) == 1 then
            mdaq_close(link_id);
        end
        return;
    end

    if res < 0  then
        mdaq_error(res)
    end

    //Give time to start DSP firmware
    sleep(200);

    %microdaq.dsp_loaded = %T;
    res = mlink_set_obj(link_id, 'ext_mode', 1 );

    if argn(2) == 2 then
        mdaq_close(link_id);
    end

    if res == 0 then
        result = client_connect(mdaq_get_ip(), 4344);
        if result < 0 then
            disp("ERROR: Unable to connect to MicroDAQ - reboot MicroDAQ device!")
            %microdaq.dsp_loaded = %F;
            return;
        end
        %microdaq.dsp_ext_mode = %T;
    else
        %microdaq.dsp_ext_mode = %F;
    end
    result = 0;
endfunction


mdaq_func_key block simulation function fix

function block=mdaq_func_key_sim(block,flag)
    global %microdaq;
    if %microdaq.dsp_loaded == %F then
        select flag
        case -5 // Error
        case 0 // Derivative State Update
        case 1 // Output Update
            if %microdaq.private.connection_id > -1 then
                key_state = mdaq_key_read(%microdaq.private.connection_id,..
                                                block.ipar(1));
                if key_state then
                    block.outptr(1) = 1;
                else
                    block.outptr(1) = 0;
                end
            end
        case 2 // State Update
        case 3 // OutputEventTiming
        case 4 // Initialization
        case 5 // Ending
        case 6 // Re-Initialisation
        case 9 // ZeroCrossing
        else // Unknown flag
        end
    end
endfunction

function block=mdaq_func_key_sim(block,flag)
    global %microdaq;
    if %microdaq.dsp_loaded == %F then
        select flag
        case -5 // Error
        case 0 // Derivative State Update
        case 1 // Output Update
            if %microdaq.private.connection_id > -1 then
                block.outptr(1) = mdaq_key_read(%microdaq.private.connection_id,..
                                                block.ipar(1));
            end
        case 2 // State Update
        case 3 // OutputEventTiming
        case 4 // Initialization
        case 5 // Ending
        case 6 // Re-Initialisation
        case 9 // ZeroCrossing
        else // Unknown flag
        end
    end
endfunction


Minor changes in signal block

Minor changes in signal block

function block=mdaq_signal_sim(block,flag)
    select flag
    case -5 // Error
    case 0 // Derivative State Update

    case 1 // Output Update
        global %microdaq;
        if %microdaq.dsp_loaded == %T then
                if %microdaq.private.signal_buffer_index(block.ipar(1)) < 1 then
                    try
                        %microdaq.private.signal_buffer(block.ipar(1)) = mdaqDSPRead(block.ipar(1), block.insz(1), %microdaq.private.signal_buffer_size(block.ipar(1)), 5000);

                        %microdaq.private.signal_buffer_index(block.ipar(1)) = %microdaq.private.signal_buffer_size(block.ipar(1));
                    catch
                        warning("Unable to receive DSP data from MicroDAQ device");
                        return;
                    end

                end
                block.outptr(1) = %microdaq.private.signal_buffer(block.ipar(1))(%microdaq.private.signal_buffer_size(block.ipar(1)) + 1 - %microdaq.private.signal_buffer_index(block.ipar(1)),:);
                %microdaq.private.signal_buffer_index(block.ipar(1)) = %microdaq.private.signal_buffer_index(block.ipar(1)) - 1;
        else
            // Simply copy input to output
            block.outptr(1) = block.inptr(1);
        end
    case 2 // State Update
    case 3 // OutputEventTiming
    case 4 // Initialization
        global %microdaq;
        update_rate = 50;
        if %microdaq.private.model_tsamp < 1/update_rate then
            %microdaq.private.signal_buffer_size(block.ipar(1)) = (1/update_rate)/%microdaq.private.model_tsamp ;
        else
            %microdaq.private.signal_buffer_size(block.ipar(1)) = 1;
        end

        %microdaq.private.signal_buffer(block.ipar(1)) = zeros(%microdaq.private.signal_buffer_size(block.ipar(1)), block.insz(1));
        %microdaq.private.signal_buffer_index(block.ipar(1)) = 0;
    case 5 // Ending
    case 6 // Re-Initialisation
    case 9 // ZeroCrossing
    else // Unknown flag
    end
endfunction

function block=mdaq_signal_sim(block,flag)
    select flag
    case -5 // Error
    case 0 // Derivative State Update

    case 1 // Output Update
        global %microdaq;
        if %microdaq.dsp_loaded == %T then
                if %microdaq.private.signal_buffer_index(block.ipar(1)) < 1 then
                    try
                    %microdaq.private.signal_buffer(block.ipar(1)) = mdaqDSPRead(block.ipar(1), block.insz(1), %microdaq.private.signal_buffer_size(block.ipar(1)), 5000);

                    %microdaq.private.signal_buffer_index(block.ipar(1)) = %microdaq.private.signal_buffer_size(block.ipar(1));
                    catch
                        warning("Unable to receive DSP data from MicroDAQ device");
                        return;
                    end

                end
                block.outptr(1) = %microdaq.private.signal_buffer(block.ipar(1))(%microdaq.private.signal_buffer_size(block.ipar(1)) + 1 - %microdaq.private.signal_buffer_index(block.ipar(1)),:);
                %microdaq.private.signal_buffer_index(block.ipar(1)) = %microdaq.private.signal_buffer_index(block.ipar(1)) - 1;
        else
            // Simply copy input to output
            block.outptr(1) = block.inptr(1);
        end
    case 2 // State Update
    case 3 // OutputEventTiming
    case 4 // Initialization
        global %microdaq;
        update_rate = 25;

        if %microdaq.private.model_tsamp < 1/update_rate*2 then
            %microdaq.private.signal_buffer_size(block.ipar(1)) = (1/update_rate)/%microdaq.private.model_tsamp ;
        else
            %microdaq.private.signal_buffer_size(block.ipar(1)) = 1;
        end

        %microdaq.private.signal_buffer(block.ipar(1)) = zeros(%microdaq.private.signal_buffer_size(block.ipar(1)), block.insz(1));
        %microdaq.private.signal_buffer_index(block.ipar(1)) = 0;
    case 5 // Ending
    case 6 // Re-Initialisation
    case 9 // ZeroCrossing
    else // Unknown flag
    end
endfunction


INTEGRATION: CWS dr42 (1.5.146); FILE MERGED 2005/10/05 10:57:40 cn 1.5.146.1: #i55494# update of sc.sce and knownissues.xcl

### 114242 -o sc.ScPageObj
## 111147 -o sc.AccessibleEditableTextPara_PreviewNote
-o sc.AccessibleEditableTextPara_HeaderFooter
-o sc.AccessibleEditableTextPara_PreviewCell
-o sc.ScAccessibleCell
### i54260 -o sc.ScAccessibleCsvCell
### i54260 -o sc.ScAccessibleCsvGrid
### i54260 -o sc.ScAccessibleCsvRuler
### i54271 -o sc.ScAccessibleDocument
-o sc.ScAccessiblePageHeader
-o sc.ScAccessiblePageHeaderArea
-o sc.ScAccessiblePreviewCell
-o sc.ScAccessiblePreviewHeaderCell
-o sc.ScAccessiblePreviewTable
-o sc.ScAccessibleSpreadsheet
-o sc.ScAnnotationObj
-o sc.ScAnnotationShapeObj
-o sc.ScAnnotationsObj
-o sc.ScAreaLinkObj
-o sc.ScAreaLinksObj
-o sc.ScAutoFormatFieldObj
-o sc.ScAutoFormatObj
-o sc.ScAutoFormatsObj
-o sc.ScCellCursorObj
-o sc.ScCellFieldObj
-o sc.ScCellFieldsObj
-o sc.ScCellFormatsEnumeration
-o sc.ScCellFormatsObj
-o sc.ScCellObj
-o sc.ScCellRangeObj
-o sc.ScCellRangesObj
-o sc.ScCellSearchObj
-o sc.ScCellTextCursor
-o sc.ScCellsEnumeration
-o sc.ScCellsObj
-o sc.ScChartObj
-o sc.ScChartsObj
-o sc.ScConsolidationDescriptor
-o sc.ScDDELinkObj
-o sc.ScDDELinksObj
-o sc.ScDataPilotFieldGroupItemObj
-o sc.ScDataPilotFieldGroupObj
-o sc.ScDataPilotFieldGroupsObj
-o sc.ScDataPilotFieldObj
-o sc.ScDataPilotFieldsObj
-o sc.ScDataPilotItemObj
-o sc.ScDataPilotItemsObj
-o sc.ScDataPilotTableObj
-o sc.ScDataPilotTablesObj
-o sc.ScDatabaseRangeObj
-o sc.ScDatabaseRangesObj
-o sc.ScDocumentConfiguration
-o sc.ScDrawPageObj
-o sc.ScDrawPagesObj
-o sc.ScFilterDescriptorBase
-o sc.ScFunctionListObj
-o sc.ScHeaderFieldObj
-o sc.ScHeaderFieldsObj
-o sc.ScHeaderFooterContentObj
-o sc.ScHeaderFooterTextCursor
-o sc.ScHeaderFooterTextObj
-o sc.ScIndexEnumeration_CellAnnotationsEnumeration
-o sc.ScIndexEnumeration_CellAreaLinksEnumeration
-o sc.ScIndexEnumeration_DDELinksEnumeration
-o sc.ScIndexEnumeration_DataPilotFieldsEnumeration
-o sc.ScIndexEnumeration_DataPilotItemsEnumeration
-o sc.ScIndexEnumeration_DataPilotTablesEnumeration
-o sc.ScIndexEnumeration_DatabaseRangesEnumeration
-o sc.ScIndexEnumeration_FunctionDescriptionEnumeration
-o sc.ScIndexEnumeration_LabelRangesEnumeration
-o sc.ScIndexEnumeration_NamedRangesEnumeration
-o sc.ScIndexEnumeration_ScenariosEnumeration
-o sc.ScIndexEnumeration_SheetCellRangesEnumeration
-o sc.ScIndexEnumeration_SheetLinksEnumeration
-o sc.ScIndexEnumeration_SpreadsheetViewPanesEnumeration
-o sc.ScIndexEnumeration_SpreadsheetsEnumeration
-o sc.ScIndexEnumeration_SubTotalFieldsEnumeration
-o sc.ScIndexEnumeration_TableAutoFormatEnumeration
-o sc.ScIndexEnumeration_TableChartsEnumeration
-o sc.ScIndexEnumeration_TableColumnsEnumeration
-o sc.ScIndexEnumeration_TableConditionalEntryEnumeration
-o sc.ScIndexEnumeration_TableRowsEnumeration
-o sc.ScIndexEnumeration_TextFieldEnumeration
-o sc.ScLabelRangeObj
-o sc.ScLabelRangesObj
-o sc.ScModelObj
-o sc.ScNamedRangeObj
-o sc.ScNamedRangesObj
-o sc.ScRecentFunctionsObj
-o sc.ScScenariosObj
-o sc.ScShapeObj
-o sc.ScSheetLinkObj
-o sc.ScSheetLinksObj
-o sc.ScSpreadsheetSettings
-o sc.ScSpreadsheetSettingsObj
-o sc.ScStyleFamiliesObj
-o sc.ScStyleFamilyObj
-o sc.ScStyleObj
-o sc.ScSubTotalDescriptorBase
-o sc.ScSubTotalFieldObj
### 114209 -o sc.ScTabViewObj
-o sc.ScTableColumnObj
-o sc.ScTableColumnsObj
-o sc.ScTableConditionalEntry
-o sc.ScTableConditionalFormat
-o sc.ScTableRowObj
-o sc.ScTableRowsObj
-o sc.ScTableSheetObj
-o sc.ScUniqueCellFormatsEnumeration
-o sc.ScUniqueCellFormatsObj
-o sc.ScTableSheetsObj
-o sc.ScTableValidationObj
-o sc.ScViewPaneObj
-o sc.XMLContentExporter
-o sc.XMLContentImporter
-o sc.XMLExporter
-o sc.XMLImporter
-o sc.XMLMetaExporter
-o sc.XMLMetaImporter
-o sc.XMLSettingsExporter
-o sc.XMLSettingsImporter
-o sc.XMLStylesExporter
-o sc.XMLStylesImporter
-o sc.ScAccessibleDocumentPagePreview
-o sc.XMLExporter

### 114242 ### -o sc.ScPageObj
### 111147 ### -o sc.AccessibleEditableTextPara_PreviewNote
-o sc.AccessibleEditableTextPara_HeaderFooter
-o sc.AccessibleEditableTextPara_PreviewCell
-o sc.ScAccessibleCell
-o sc.ScAccessibleCsvCell
-o sc.ScAccessibleCsvGrid
-o sc.ScAccessibleCsvRuler
-o sc.ScAccessibleDocument
-o sc.ScAccessiblePageHeader
-o sc.ScAccessiblePageHeaderArea
-o sc.ScAccessiblePreviewCell
-o sc.ScAccessiblePreviewHeaderCell
-o sc.ScAccessiblePreviewTable
-o sc.ScAccessibleSpreadsheet
-o sc.ScAnnotationObj
-o sc.ScAnnotationShapeObj
-o sc.ScAnnotationsObj
-o sc.ScAreaLinkObj
-o sc.ScAreaLinksObj
-o sc.ScAutoFormatFieldObj
-o sc.ScAutoFormatObj
-o sc.ScAutoFormatsObj
-o sc.ScCellCursorObj
-o sc.ScCellFieldObj
-o sc.ScCellFieldsObj
-o sc.ScCellFormatsEnumeration
-o sc.ScCellFormatsObj
-o sc.ScCellObj
-o sc.ScCellRangeObj
-o sc.ScCellRangesObj
-o sc.ScCellSearchObj
-o sc.ScCellTextCursor
-o sc.ScCellsEnumeration
-o sc.ScCellsObj
-o sc.ScChartObj
-o sc.ScChartsObj
-o sc.ScConsolidationDescriptor
-o sc.ScDDELinkObj
-o sc.ScDDELinksObj
-o sc.ScDataPilotFieldObj
-o sc.ScDataPilotFieldsObj
-o sc.ScDataPilotItemObj
-o sc.ScDataPilotItemsObj
-o sc.ScDataPilotTableObj
-o sc.ScDataPilotTablesObj
-o sc.ScDatabaseRangeObj
-o sc.ScDatabaseRangesObj
-o sc.ScDocumentConfiguration
-o sc.ScDrawPageObj
-o sc.ScDrawPagesObj
-o sc.ScFilterDescriptorBase
-o sc.ScFunctionListObj
-o sc.ScHeaderFieldObj
-o sc.ScHeaderFieldsObj
-o sc.ScHeaderFooterContentObj
-o sc.ScHeaderFooterTextCursor
-o sc.ScHeaderFooterTextObj
-o sc.ScIndexEnumeration_CellAnnotationsEnumeration
-o sc.ScIndexEnumeration_CellAreaLinksEnumeration
-o sc.ScIndexEnumeration_DDELinksEnumeration
-o sc.ScIndexEnumeration_DataPilotFieldsEnumeration
-o sc.ScIndexEnumeration_DataPilotItemsEnumeration
-o sc.ScIndexEnumeration_DataPilotTablesEnumeration
-o sc.ScIndexEnumeration_DatabaseRangesEnumeration
-o sc.ScIndexEnumeration_FunctionDescriptionEnumeration
-o sc.ScIndexEnumeration_LabelRangesEnumeration
-o sc.ScIndexEnumeration_NamedRangesEnumeration
-o sc.ScIndexEnumeration_ScenariosEnumeration
-o sc.ScIndexEnumeration_SheetCellRangesEnumeration
-o sc.ScIndexEnumeration_SheetLinksEnumeration
-o sc.ScIndexEnumeration_SpreadsheetViewPanesEnumeration
-o sc.ScIndexEnumeration_SpreadsheetsEnumeration
-o sc.ScIndexEnumeration_SubTotalFieldsEnumeration
-o sc.ScIndexEnumeration_TableAutoFormatEnumeration
-o sc.ScIndexEnumeration_TableChartsEnumeration
-o sc.ScIndexEnumeration_TableColumnsEnumeration
-o sc.ScIndexEnumeration_TableConditionalEntryEnumeration
-o sc.ScIndexEnumeration_TableRowsEnumeration
-o sc.ScIndexEnumeration_TextFieldEnumeration
-o sc.ScLabelRangeObj
-o sc.ScLabelRangesObj
-o sc.ScModelObj
-o sc.ScNamedRangeObj
-o sc.ScNamedRangesObj
-o sc.ScRecentFunctionsObj
-o sc.ScScenariosObj
-o sc.ScShapeObj
-o sc.ScSheetLinkObj
-o sc.ScSheetLinksObj
-o sc.ScSpreadsheetSettings
-o sc.ScSpreadsheetSettingsObj
-o sc.ScStyleFamiliesObj
-o sc.ScStyleFamilyObj
-o sc.ScStyleObj
-o sc.ScSubTotalDescriptorBase
-o sc.ScSubTotalFieldObj
-o sc.ScTabViewObj
-o sc.ScTableColumnObj
-o sc.ScTableColumnsObj
-o sc.ScTableConditionalEntry
-o sc.ScTableConditionalFormat
-o sc.ScTableRowObj
-o sc.ScTableRowsObj
-o sc.ScTableSheetObj
-o sc.ScTableSheetsObj
-o sc.ScTableValidationObj
-o sc.ScViewPaneObj
-o sc.XMLContentExporter
-o sc.XMLContentImporter
-o sc.XMLExporter
-o sc.XMLImporter
-o sc.XMLMetaExporter
-o sc.XMLMetaImporter
-o sc.XMLSettingsExporter
-o sc.XMLSettingsImporter
-o sc.XMLStylesExporter
-o sc.XMLStylesImporter
-o sc.ScAccessibleDocumentPagePreview