motp/mota computation ready

motp/mota computation ready

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

//includes
exec('/home/andreu/dev/ros_ws/src/pipol_tracker/scilab/munkres.sci');

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

//inits
dd = 0;
total_matches = 0;
motp = [];
mota = [];
id_switch = 0;
fn_count = 0;
fp_count = 0;
total_gt_targets = 0;

//plot y/n
plot_flag = 0;

//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
tracks = list();
while (1) do
    tracks_row=[];
    str_line = mgetl(fd_tracks,1);
    if length(str_line) < 2 then
        break;
    else
        tkns = tokens(str_line,' ');
        for i=1:size(tkns,1)
            tracks_row = [tracks_row strtod(tkns(i))];
        end
        tracks($+1) = tracks_row;
    end
end

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

//interpolate ground truth at result time stamp point
ii = 1;
gt_intp = list();
for jj=1:size(tracks)
    ts = tracks(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

//set up plot
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 = "on";
    ah.auto_scale = "off";
    ah.data_bounds = [-3 0; 3 5];
    plot_colors = ["r";"g";"b";"k";"y"];
end

//MAIN LOOP TO COMPUTE MOT METRICS
for tt=1:size(tracks) //tt tracker iteration index (coincide with gorund truth interpolation index)

    //1. Filter out tracks with status lower than 15
    Nt_tracks = (size(tracks(tt),2)-1) / 4; //number of track targets (all)
    tk_sel = tracks(tt)(1); //track selection with status > 15. Init with timestamp
    for kk= 1:Nt_tracks
        if tracks(tt)(kk*4-1) >= 15 then
            tk_sel = [tk_sel tracks(tt)(kk*4-2:kk*4+1)]
        end
    end

    //2. Build D2 matrix. Sq Euclidean distance between all track-gt pairs
    Nt_gt = (size(gt_intp(tt),2)-1) / 3; //number of gt targets
    Nt_tracks = (size(tk_sel,2)-1) / 4; //number of track targets (selected according status)
    D2 = zeros(Nt_gt, Nt_tracks);
    for ii=1:Nt_gt //ii row/gt index
        gt_pos = [gt_intp(tt)(ii*3); gt_intp(tt)(ii*3+1)]; //gt ii position
        for jj= 1:Nt_tracks //jj column/track index
            tk_pos = [tk_sel(jj*4); tk_sel(jj*4+1)]; //track jj position
            D2(ii,jj) = (tk_pos(1)-gt_pos(1))^2 + (tk_pos(2)-gt_pos(2))^2; //sq euclidean distance
        end
    end

    //2. Check if any gt is further than d2_th to all tracks
    d2_th = 0.5*0.5; //0.5m threshold
    D2_chkd_rows = [];
    unassociated_gt_ids = [];
    associated_gt_ids = [];
    for ii=1:Nt_gt
        if ( min( D2(ii,:) ) > d2_th ) then
            unassociated_gt_ids = [unassociated_gt_ids gt_intp(tt)(ii*3-1)]; //save gt id as unassociated
        else
            D2_chkd_rows = [D2_chkd_rows; D2(ii,:)];
            associated_gt_ids = [associated_gt_ids gt_intp(tt)(ii*3-1)]; //save gt id as associated
        end
    end
    fn_count = fn_count + size(unassociated_gt_ids,2); //false negative counter: cases where a gt target is not tracked

    //3. In case D2_chkd_rows is non-empty, Check if any track is further than d2_th to all gt's
    unassociated_tk_ids = [];
    associated_tk_ids = [];
    D2_chkd = [];
    if ( size(associated_gt_ids) == 0 ) then
        fp_count = fp_count + Nt_tracks; //in case of no gt association, all tracks are false positives. D2_chkd remains void
    else
        for jj=1:Nt_tracks
            if ( min( D2_chkd_rows(:,jj) ) > d2_th ) then
                unassociated_tk_ids = [unassociated_tk_ids tk_sel(jj*4-2)]; //save track id as unassociated
            else
                D2_chkd = [D2_chkd D2_chkd_rows(:,jj)];
                associated_tk_ids = [associated_tk_ids tk_sel(jj*4-2)]; //save track id as associated
            end
        end
        fp_count = fp_count + size(unassociated_tk_ids,2); //false positives: a tracked target does not associate to any ground truth
    end

    //4. gt-tracks assignment. Munkres' Algorithm when more than 1 is involved
    mapping_current = [];
    [Nt_gt2 Nt_tracks] = size(D2_chkd);
    if ( Nt_gt2 > 0 ) then //to avoid degenerate case where no potential matchings exist
        if size(associated_gt_ids) == 1 then //case with a single gt. Find the nearest track and assign to it
            mapping_current = [associated_gt_ids(1) associated_tk_ids(find(~(D2_chkd(1,:)-min(D2_chkd(1,:))),1))];
            fp_count = fp_count + Nt_tracks-1; //all other tracks count as false positives
        else
            if size(associated_tk_ids) == 1 then //case with a single tk. Find the nearest gt and assign to it
                mapping_current = [associated_gt_ids(find(~(D2_chkd(:,1)-min(D2_chkd(:,1))),1)) associated_tk_ids(1)];
                fn_count = fn_count + Nt_gt2-1; //all other gt's count as false negatives
            else //general case. Munkres algorithm
                 munkres_result = munkres(D2_chkd);
                 npairs = size(munkres_result,1);
                 for kk=1:npairs
                         mapping_current = [mapping_current; associated_gt_ids(munkres_result(kk,1)) associated_tk_ids(munkres_result(kk,2))];
                 end
            end
        end
    end

    //5. compute MOTP
    npairs = size(mapping_current,1);
    for kk=1:npairs
        ii = 1;
        jj=1;
        while gt_intp(tt)(ii*3-1) ~= mapping_current(kk,1)
            ii = ii+1;
        end
        while tracks(tt)(jj*4-2) ~= mapping_current(kk,2)
            jj = jj+1;
        end
        gt_pos = [gt_intp(tt)(ii*3); gt_intp(tt)(ii*3+1)]; //gt ii position
        tk_pos = [tracks(tt)(jj*4); tracks(tt)(jj*4+1)]; //track jj position
        dd = dd + sqrt( (gt_pos(1)-tk_pos(1))^2 + (gt_pos(2)-tk_pos(2))^2 );
        total_matches = total_matches + 1;
        motp = [motp dd/total_matches];
    end

    //6. Compute MOTA
    if tt > 1 then //Check if ID switches by comparing current and previous mappings
        id_switch = 0;
        npairs_c = size(mapping_current,1);
        npairs_p = size(mapping_previous,1);
        for kk=1:npairs_c
            gt_id = mapping_current(kk,1);
            ii = find(~(mapping_previous(:,1)-gt_id));
            if ii == 1 then //this gt_id was already there at the previous iteration
                if mapping_current(kk,2) ~= mapping_previous(ii,2) then //but different assignment at previous iteration
                    id_switch = id_switch + 1;
                end
            end
        end
    end
    mapping_previous = mapping_current;
    total_gt_targets = total_gt_targets + Nt_gt
    if total_gt_targets ~= 0 then
        mota = [mota 1 - (fn_count + fp_count + id_switch)/total_gt_targets];
    end

    //7. DISPLAY
    disp("New iteration--------");
//    mprintf('TS: %10.10f\n', tracks(tt)(1));
//    disp('D2_chkd:'); disp(D2_chkd);
//    disp('fn_count:'); disp(fn_count);
//    disp('fp_count:'); disp(fp_count);
//    disp('mapping:'); disp(mapping_current);
    disp('motp:'); disp(motp($));
    disp('mota:'); disp(mota($));

    //8. PLOT
    if plot_flag then
        if Nt_gt2 > 0 then
            for ii=1:Nt_gt2
                gt_id = gt_intp(tt)(ii*3-1);
                color_id = plot_colors(pmodulo(gt_id-1,5)+1);
                plot(-gt_intp(tt)(ii*3+1),gt_intp(tt)(ii*3), color_id + '+');
            end
        end
        if Nt_tracks > 0 then
            for jj=1:Nt_tracks
                if tracks(tt)(jj*4-1) > 15 then //check status value: Visually confirmed or higher
                    tk_id = tracks(tt)(jj*4-2);
                    ii = find(~(mapping_current(:,2)-tk_id)); //in the mapping, look for the row corresponding to this track
                    if size(ii) == 1 then //check there is association with gt
                        ii = mapping_current(ii,1); //get associated gt from mapping
                        gt_id = gt_intp(tt)(ii*3-1);//get the associated ground truth id
                        color_id = plot_colors(pmodulo(gt_id-1,5)+1);
                        plot(-tracks(tt)(jj*4+1),tracks(tt)(jj*4), color_id + '.');
                    end
                end
            end
        end
    end
end

//COMPUTE DISTANCES -> MOTP

//CHECK MAPPING SWITCHES -> sw

//COUNT FALSE POSITIVES -> fp_count

//COUNT FALSE NEGATIVES -> fn_count

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

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

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

//includes
exec('/home/andreu/dev/ros_ws/src/pipol_tracker/scilab/munkres.sci');

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

//plot y/n
plot_flag = 1;

//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
tracks = list();
while (1) do
    tracks_row=[];
    str_line = mgetl(fd_tracks,1);
    if length(str_line) < 2 then
        break;
    else
        tkns = tokens(str_line,' ');
        for i=1:size(tkns,1)
            tracks_row = [tracks_row strtod(tkns(i))];
        end
        tracks($+1) = tracks_row;
    end
end

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

//interpolate ground truth at result time stamp point
ii = 1;
gt_intp = list();
for jj=1:size(tracks)
    ts = tracks(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

//set up plot
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];
    plot_colors = ["r";"g";"b";"k";"y"];
end

//MAIN LOOP TO COMPUTE MOT METRICS
for tt=1:size(tracks) //tt tracker iteration index (coincide with gorund truth interpolation index)

    //1. Filter out tracks with status lower than 15
    Nt_tracks = (size(tracks(tt),2)-1) / 4; //number of track targets (all)
    tk_sel = tracks(tt)(1); //track selection with status > 15. Init with timestamp
    for kk= 1:Nt_tracks
        if tracks(tt)(kk*4-1) >= 15 then
            tk_sel = [tk_sel tracks(tt)(kk*4-2:kk*4+1)]
        end
    end

    //2. Build D2 matrix. Sq Euclidean distance between all track-gt pairs
    Nt_gt = (size(gt_intp(tt),2)-1) / 3; //number of gt targets
    Nt_tracks = (size(tk_sel,2)-1) / 4; //number of track targets (selected according status)
    D2 = zeros(Nt_gt, Nt_tracks);
    for ii=1:Nt_gt //ii row/gt index
        gt_pos = [gt_intp(tt)(ii*3); gt_intp(tt)(ii*3+1)]; //gt ii position
        for jj= 1:Nt_tracks //jj column/track index
            tk_pos = [tk_sel(jj*4); tk_sel(jj*4+1)]; //track jj position
            D2(ii,jj) = (tk_pos(1)-gt_pos(1))^2 + (tk_pos(2)-gt_pos(2))^2; //sq euclidean distance
        end
    end

    //2. Check if any gt is further than d2_th to all tracks
    d2_th = 0.5*0.5; //0.5m threshold
    D2_chkd_rows = [];
    unassociated_gt = [];
    associated_gt = [];
    for ii=1:Nt_gt
        if ( min( D2(ii,:) ) > d2_th ) then
            unassociated_gt = [unassociated_gt gt_intp(tt)(ii*3-1)]; //save gt id as unassociated
        else
            D2_chkd_rows = [D2_chkd_rows; D2(ii,:)];
            associated_gt = [associated_gt gt_intp(tt)(ii*3-1)]; //save gt id as associated
        end
    end
    fn_count = size(unassociated_gt,2); //false negative counter: cases where a gt target is not tracked

    //3. In case D2_chkd_rows is non-empty, Check if any track is further than d2_th to all gt's
    unassociated_tk = [];
    associated_tk = [];
    D2_chkd = [];
    if ( size(associated_gt) == 0 ) then
        fp_count = Nt_tracks; //in case of any potential gt association, all tracks are counted as false positive
    else
        for jj=1:Nt_tracks
            if ( min( D2_chkd_rows(:,jj) ) > d2_th ) then
                unassociated_tk = [unassociated_tk tk_sel(jj*4-2)]; //save track id as unassociated
            else
                D2_chkd = [D2_chkd D2_chkd_rows(:,jj)];
                associated_tk = [associated_tk tk_sel(jj*4-2)]; //save track id as associated
            end
        end
        fp_count = size(unassociated_tk,2); //false positiveS: a tracked target does not associate to any ground truth
    end

    //4. gt-tracks assignment. Munkres' Algorithm when more than 1 is involved
    mapping_current = [];
    [Nt_gt Nt_tracks] = size(D2_chkd);
    if ( Nt_gt > 0 ) then //to avoid degenerate case where no potential matchings exist
        if size(associated_gt) == 1 then //case with a single gt. Find the nearest track and assign to it
            mapping_current = [associated_gt(1)  associated_tk(find(~(D2_chkd(1,:)-min(D2_chkd(1,:))),1))];
            fp_count = fp_count + Nt_tracks-1; //all other tracks count as false positives
        else
            if size(associated_tk) == 1 then //case with a single tk. Find the nearest gt and assign to it
                mapping_current = [associated_gt(find(~(D2_chkd(:,1)-min(D2_chkd(:,1))),1)) associated_tk(1)];
                fn_count = fn_count + Nt_gt-1; //all other gt's count as false negatives
            else //general case. Munkres algorithm
                mapping_current = munkres(D2_chkd);
            end
        end
    end

    //5. Check if ID switches by comparing current and previous mappings
    if tt > 1 then
        // to do
    end
    mapping_previous = mapping_current;

    //6. DISPLAY
    disp("New iteration--------");
    mprintf('TS: %10.10f\n', tracks(tt)(1));
    disp('D2_chkd:'); disp(D2_chkd);
    disp('fn_count:'); disp(fn_count);
    disp('fp_count:'); disp(fp_count);
    disp('mapping:');disp(mapping_current);

    //7. PLOT
    if plot_flag then
        if Nt_gt > 0 then
            for kk=1:Nt_gt
                plot(-gt_intp(tt)(kk*3+1),gt_intp(tt)(kk*3),plot_colors(pmodulo(gt_intp(tt)(kk*3-1)-1,5)+1)+'+');
            end
        end
        if Nt_tracks > 0 then
            for kk=1:Nt_tracks
                if tracks(tt)(kk*4-1) > 15 then //check status value: Visually confirmed or higher
                    plot(-tracks(tt)(kk*4+1),tracks(tt)(kk*4),plot_colors(pmodulo(tracks(tt)(kk*4-2)-1,5)+1)+'.');
                end
            end
        end
    end
end

//COMPUTE DISTANCES -> MOTP

//CHECK MAPPING SWITCHES -> sw

//COUNT FALSE POSITIVES -> fp_count

//COUNT FALSE NEGATIVES -> fn_count

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

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


sb120: #i111252# disabled failing tests for now

#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

#i98339 -o svx.AccessibleControlShape
-o svx.AccessibleEditableTextPara
#i111252 -o svx.AccessibleGraphicShape
#i46736 -o svx.AccessibleImageBullet
#i111252 -o svx.AccessibleOLEShape
-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


fix for SCHEDULING-1399

fix for SCHEDULING-1399

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

function outputs = PAsolve(varargin)
    global ('PA_connected','DataRegistry', 'DataRegistryInit', 'SOLVEid')

    if ~exists('PA_connected') | PA_connected ~= 1
        error('A connection to the ProActive scheduler must be established in order to use PAsolve, see PAconnect');
    end

    if exists('SOLVEid') & type(SOLVEid) == 8
        SOLVEid = SOLVEid + 1;
    else
        SOLVEid = int32(0);
    end

    opt=PAoptions();

    deff ("y=ischar(x)","y=type(x)==10","n");
    if ischar(varargin(1)) then
        Func = varargin(1);
        NN=length(varargin)-1;
        Tasks = PATask(1,NN);
        Tasks(1,1:NN).Func = Func;
        for i=1:NN
            if typeof(varargin(i+1)) == 'list'
                Tasks(1,i).Params =varargin(i+1);
            else
                Tasks(1,i).Params =list(varargin(i+1));
            end
        end
        MM = 1;
    elseif typeof(varargin(1)) == 'PATask'
        if length(varargin) == 1
            Tasks = varargin(1);
            NN = size(Tasks,2);
            MM = size(Tasks,1);
        else
            NN=argn(2);
            MM = -1;
            for i=1:NN
                if typeof(varargin(i)) == 'PATask'
                    if (size(varargin(i),2) ~= 1)
                        error(strcat(['parameter ', string(i), ' should be a column vector.']));
                    end
                    sz = size(varargin(i),1);
                    if MM == -1
                        MM = sz;
                        Tasks=PATask(MM,NN);
                    elseif MM ~= sz
                        error(strcat(['parameter ', string(i), ' should be a column vector of the same length than other parameters.']));
                    end
                    Tasks(1:sz,i) = varargin(i);
                else
                    error(strcat(['parameter ', num2str(i), ' is a ', typeof(varargin(i)), ', expected PATask instead.']));
                end
            end

        end
    end

    jimport org.ow2.proactive.scheduler.ext.scilab.common.PASolveScilabGlobalConfig;
    jimport org.ow2.proactive.scheduler.ext.scilab.common.PASolveScilabTaskConfig;
    jimport org.ow2.proactive.scheduler.ext.common.util.FileUtils;
    jimport org.ow2.proactive.scheduler.ext.matsci.client.AODataspaceRegistry;
    jimport java.lang.String;
    jimport java.net.URL;
    jimport java.io.File;

    solve_config = jnewInstance(PASolveScilabGlobalConfig);

    solve_config.setDebug(opt.Debug);
    solve_config.setTimeStamp(opt.TimeStamp);
    solve_config.setFork(opt.Fork);
    solve_config.setRunAsMe(opt.RunAsMe);
    solve_config.setPriority(opt.Priority);
    solve_config.setTransferSource(opt.TransferSource);
    //solve_config.setTransferEnv(opt.TransferEnv);
    solve_config.setTransferVariables(opt.TransferVariables);
    solve_config.setKeepEngine(opt.KeepEngine);
    jinvoke(solve_config,'setWindowsStartupOptionsAsString',opt.WindowsStartupOptions);
    jinvoke(solve_config,'setLinuxStartupOptionsAsString',opt.LinuxStartupOptions);

    solve_config.setInputSpaceName('ScilabInputSpace');
    solve_config.setOutputSpaceName('ScilabOutputSpace');

    solve_config.setVersionPref(opt.VersionPref);
    solve_config.setVersionRejAsString(opt.VersionRej);
    solve_config.setVersionMin(opt.VersionMin);
    solve_config.setVersionMax(opt.VersionMax);
    solve_config.setCheckMatSciUrl(opt.FindScilabScript);
    if ischar(opt.CustomScript)
        selects = opt.CustomScript
        try
            url=URL.new(selects);
            ok = true;
        catch
            ok = false;
        end
        jremove(url);

        if ~ok
            solve_config.setCustomScriptUrl(strcat(['file:', selects]));
        else
            solve_config.setCustomScriptUrl(selects);
        end
    end

    solve_config.setZipSourceFiles(%f);

    curr_dir = pwd();
    fs=filesep();
    curr_dir_java = File.new(curr_dir);
    if ~jinvoke(curr_dir_java,'canWrite')
        jremove(curr_dir_java);
        error('Current Directory should have write access rights');
    end
    jremove(curr_dir_java);

    // PAScheduler sub directory init

    subdir = '.PAScheduler';
    solve_config.setTempSubDirName(subdir);

    if isempty(opt.CustomDataspaceURL)
        if ~isdir(strcat([curr_dir, fs, subdir]))
            mkdir(curr_dir,subdir);
        end
        pa_dir = strcat([curr_dir, fs, subdir]);
    else
        if isempty(opt.CustomDataspacePath)
            error('if CustomDataspaceURL is specified, CustomDataspacePath must be specified also');
        end
        if ~isdir(strcat([opt.CustomDataspacePath, fs, subdir]))
            mkdir(opt.CustomDataspacePath,subdir);
        end
        pa_dir = strcat([opt.CustomDataspacePath, fs, subdir]);
    end

    if isempty(opt.CustomDataspaceURL)
        if ~exists('DataRegistryInit') | DataRegistryInit ~= 1
            DataRegistry = AODataspaceRegistry.new('ScilabInputSpace','ScilabOutputSpace','ScilabSession',opt.Debug);
            DataRegistryInit = 1;
        end
        pair = DataRegistry.createDataSpace(curr_dir);
        px=jinvoke(pair,'getX');
        py=jinvoke(pair,'getY');
        pxs = jcast(px,'java.lang.String');
        pys = jcast(py,'java.lang.String');
        solve_config.setInputSpaceURL(pxs);
        solve_config.setOutputSpaceURL(pys);
        if opt.Debug then
            disp('using Dataspace:')
            disp(pxs)
        end

    else
        solve_config.setOutputSpaceURL(opt.CustomDataspaceURL);
        solve_config.setInputSpaceURL(opt.CustomDataspaceURL);
    end

    variableInFileBaseName = ['ScilabPAsolveVarIn_' string(SOLVEid)];
    variableOutFileBaseName = ['ScilabPAsolveVarOut_' string(SOLVEid)];
    outVarFiles = list(NN);
    //tmpFiles = list();
    taskFilesToClean = list();

    task_configs = jarray('org.ow2.proactive.scheduler.ext.scilab.common.PASolveScilabTaskConfig', NN,MM);
    for i=1:NN
        taskFilesToClean($+1)=list();
        for j=1:MM
            t_conf = jnewInstance(PASolveScilabTaskConfig);
            task_configs(i-1,j-1) = t_conf;
            if ~isempty(Tasks(j,i).Description) then
                t_conf.setDescription(Tasks(j,i).Description);
            end

            // Input Files
            if ~isempty(Tasks(j,i).InputFiles) then
                ilen = length(Tasks(j,i).InputFiles);
                if ilen > 0 then
                    inputFiles = jarray('java.lang.String', ilen);
                    filelist = Tasks(j,i).InputFiles;
                    for k=1:ilen
                        filename = filelist(k);
                        inputFiles(k-1)=String.new(strsubst(filename,'\','/'));
                    end

                    t_conf.setInputFiles(inputFiles);
                    t_conf.setInputFilesThere(%t);
                end
            end

            // Output Files
            if ~isempty(Tasks(j,i).OutputFiles) then
                filelist = Tasks(j,i).OutputFiles;
                ilen = length(filelist);
                if ilen > 0 then
                    outputFiles = jarray('java.lang.String', ilen);
                    for k=1:ilen
                        filename = filelist(k);
                        outputFiles(k-1)=String.new(strsubst(filename,'\','/'));
                    end

                    t_conf.setOutputFiles(outputFiles);
                    t_conf.setOutputFilesThere(%t);
                end
            end

            // Custom Script
            if ~isempty(Tasks(j,i).SelectionScript) then
                selects = Tasks(j,i).SelectionScript;
                try
                    url = URL.new(selects);
                    ok = %t;
                catch
                    ok = %f;
                end
                jremove(url);

                if ~ok
                    t_conf.setCustomScriptUrl(strcat(['file:', selects ]));
                else
                    t_conf.setCustomScriptUrl(selects);
                end
            end

            // Function
            Func = Tasks(j,i).Func;
            execstr(strcat(['functype = type(';Func;');']));
            if (functype <> 13) & (functype <> 11)  then
                error('invalid function type for function ""' + Func + '"". Consider calling this function with a macro instead.');
            end

            // Source Files

            if ~isempty(Tasks(j,i).Sources) then
                srcs = Tasks(j,i).Sources;
                for k=1:length(srcs)
                    srcPath = srcs(k);
                    if isfile(srcPath) then
                        [ppath,fname,extension]=fileparts(srcPath);
                        srcName = strcat(strcat([fname,extension]));

                        if opt.Debug then
                            disp(strcat(['Copying file ', srcPath, ' to ',pa_dir]));
                        end
                        copyfile(srcPath,pa_dir);
                        // TODO find a cleaning mechanisme
                        //taskFilesToClean(i)=lstcat(taskFilesToClean(i), list(pa_dir+fs+fname+extension));
                        //tmpFiles($+1)=strcat([pa_dir,fs,fname,extension]);

                        strName = String.new(srcName);
                        t_conf.addSourceFile(strName);
                    else
                        error(strcat(['Source file ', srcPath, ' cannot be found']));
                    end

                end

            end

            // Saving main function name (with or without Sources attribute)
            sourceNames = jarray('java.lang.String', 1);
            sFN = 'ScilabPAsolve_src'+string(SOLVEid)+indToFile([i j])+'.bin';
            execstr('save(pa_dir+fs+sFN,'+Func+');');
            strName = String.new(sFN);
            sourceNames(0) = strName;
            t_conf.setFunctionVarFiles(sourceNames);
            code=[];
            taskFilesToClean(i)=lstcat(taskFilesToClean(i), list(pa_dir+fs+sFN));

            t_conf.setFunctionName(Func);
            t_conf.addSourceFile(sFN);

            // Params
            argi = Tasks(j,i).Params;
            if opt.TransferVariables
                inVarFN = strcat([variableInFileBaseName, indToFile([i j]), '.dat']);
                outVarFN = strcat([variableOutFileBaseName, indToFile([i j]), '.dat']);
                inVarFP = strcat([pa_dir, fs, inVarFN]);
                outVarFP = strcat([pa_dir, fs, outVarFN]);
                // Creating input parameters mat files
                fd=mopen(inVarFP,'wb');
                inl = argi;
                if length(inl) == 0
                    inl=list(%t);
                end
                for k=1:length(inl)
                    execstr('in'+string(k)+'=inl(k);');
                    execstr('save(fd,in'+string(k)+')');
                end
                mclose(fd);

                jinvoke(t_conf,'setInputVariablesFileName',inVarFN);
                jinvoke(t_conf,'setOutputVariablesFileName',outVarFN);
                if j > 1 & Tasks(j,i).Compose
                    cinVarFN = strcat([variableOutFileBaseName,indToFile([i j-1]),'.dat']);
                    cinVarFP = pa_dir+fs+cinVarFN;
                    jinvoke(t_conf,'setComposedInputVariablesFileName',cinVarFN);
                end
                outVarFiles(i) = outVarFP;
                taskFilesToClean(i)=lstcat(taskFilesToClean(i), list(inVarFP));
                //if j < MM
                // because of disconnected mode, the final out is handled
                //differently
                taskFilesToClean(i)=lstcat(taskFilesToClean(i), list(outVarFP));
                //end

                inputscript = 'i=0';
            else
                inputscript = createInputScript(argi);
            end

            t_conf.setInputScript(inputscript);

            //mainScript = createMainScript(Func, opt);
            mainScript = 'out = '+Tasks(j,i).Func+'(';
            if j > 1 & Tasks(j,i).Compose
                mainScript = mainScript + 'in';
                if length(argi) > 0 then
                    mainScript = mainScript + ',';
                end
            end
            if length(argi) > 0
                for k=1:length(argi)-1
                    mainScript = mainScript + 'in'+string(k)+',';
                end
                mainScript = mainScript + ('in'+string(length(argi)));
            end
            mainScript = mainScript + ');';
            t_conf.setMainScript(mainScript);

            t_conf.setOutputs('out');

        end
    end
    jimport org.ow2.proactive.scheduler.ext.scilab.client.ScilabSolver;
    jimport org.objectweb.proactive.api.PAFuture;
    solver = jnewInstance(ScilabSolver);

    pairinfolist = solver.solve(solve_config, task_configs);

    jobinfo = jinvoke(pairinfolist,'getX');
    resfutureList =  jinvoke(pairinfolist,'getY');
    jid = string(jinvoke(jobinfo,'getJobId'));
    disp('Job submitted : '+ jid);

    ftn = jinvoke(jobinfo,'getFinalTasksNamesAsList');

    taskinfo = struct('cleanFileSet',[],'cleanDirSet',[], 'outFile',[], 'jobid',[], 'taskid',[] );
    results=list(NN);
    for i=1:NN
        taskinfo.cleanFileSet = taskFilesToClean(i);
        taskinfo.cleanDirSet = list(pa_dir);
        taskinfo.outFile = outVarFiles(i);
        taskinfo.jobid = jid;
        taskinfo.taskid = jinvoke(ftn,'get',i-1);

        results(i)=PAResult(jinvoke(resfutureList,'get',i-1), taskinfo);

    end
    outputs = PAResL(results);
    jremove(solver, solve_config, task_configs);

endfunction

function nm=indToFile(ind)
    nm='';
    if ind==-1
        return;
    end
    for JJ=ind
        nm=strcat([nm, '_', string(JJ)]);
    end
endfunction

function inputScript = createInputScript(arg)
    // We transform the argument to executable scilab code
    argcode = sci2exp(arg,'in');
    // The inputscript will contain the argument and the code of the functions
    inputscript_array=[argcode];
    // The code defining the function is made of many lines, we pack it by using ASCII 31 delimiters
    s=size(inputscript_array);
    inputscript_str='';
    for j=1:(s(1)-1)
        inputscript_str=inputscript_str+inputscript_array(j)+ascii(31);
    end
    inputscript_str=inputscript_str+inputscript_array(s(1));
    // We tranform the final packed command as an assigment to evaluate
    inputscript_assignment = sci2exp(inputscript_str, 'inputscript');
    // We add the code used to decode the packed instructions
    inputscript_decode = 'TOKENS = tokens(inputscript,ascii(31)); execstr(TOKENS,''errcatch'',''m'');';
    inputScript = strcat([inputscript_assignment;';';inputscript_decode]);
endfunction

function mainScript = createMainScript(funcName, opt)
    debugv = opt.Debug;
    if debugv == 1
        //mainScript = strcat(['mode(3)';ascii(31);'out=';funcName;'(in)';ascii(31);ascii(30);'output = sci2exp(output,''''output'''',0)';ascii(31);'disp(out)']);
        mainScript = strcat(['mode(3)';ascii(31);'out=';funcName;'(in)';ascii(31);'disp(out)']);
    else
        //mainScript = strcat(['out=';funcName;'(in);';ascii(31);ascii(30);'output = sci2exp(output,''''output'''',0);']);
        mainScript = strcat(['out=';funcName;'(in);']);
    end
endfunction

function outputs = PAsolve(varargin)
    global ('PA_connected','DataRegistry', 'DataRegistryInit', 'SOLVEid')

    if ~exists('PA_connected') | PA_connected ~= 1
        error('A connection to the ProActive scheduler must be established in order to use PAsolve, see PAconnect');
    end

    if exists('SOLVEid') & type(SOLVEid) == 8
        SOLVEid = SOLVEid + 1;
    else
        SOLVEid = int32(0);
    end

    opt=PAoptions();

    deff ("y=ischar(x)","y=type(x)==10","n");
    if ischar(varargin(1)) then
        Func = varargin(1);
        NN=length(varargin)-1;
        Tasks = PATask(1,NN);
        Tasks(1,1:NN).Func = Func;
        for i=1:NN
            if typeof(varargin(i+1)) == 'list'
                Tasks(1,i).Params =varargin(i+1);
            else
                Tasks(1,i).Params =list(varargin(i+1));
            end
        end
        MM = 1;
    elseif typeof(varargin(1)) == 'PATask'
        if length(varargin) == 1
            Tasks = varargin(1);
            NN = size(Tasks,2);
            MM = size(Tasks,1);
        else
            NN=argn(2);
            MM = -1;
            for i=1:NN
                if typeof(varargin(i)) == 'PATask'
                    if (size(varargin(i),2) ~= 1)
                        error(strcat(['parameter ', string(i), ' should be a column vector.']));
                    end
                    sz = size(varargin(i),1);
                    if MM == -1
                        MM = sz;
                        Tasks=PATask(MM,NN);
                    elseif MM ~= sz
                        error(strcat(['parameter ', string(i), ' should be a column vector of the same length than other parameters.']));
                    end
                    Tasks(1:sz,i) = varargin(i);
                else
                    error(strcat(['parameter ', num2str(i), ' is a ', typeof(varargin(i)), ', expected PATask instead.']));
                end
            end

        end
    end

    jimport org.ow2.proactive.scheduler.ext.scilab.common.PASolveScilabGlobalConfig;
    jimport org.ow2.proactive.scheduler.ext.scilab.common.PASolveScilabTaskConfig;
    jimport org.ow2.proactive.scheduler.ext.common.util.FileUtils;
    jimport org.ow2.proactive.scheduler.ext.matsci.client.AODataspaceRegistry;
    jimport java.lang.String;
    jimport java.net.URL;
    jimport java.io.File;

    solve_config = jnewInstance(PASolveScilabGlobalConfig);

    solve_config.setDebug(opt.Debug);
    solve_config.setTimeStamp(opt.TimeStamp);
    solve_config.setFork(opt.Fork);
    solve_config.setRunAsMe(opt.RunAsMe);
    solve_config.setPriority(opt.Priority);
    solve_config.setTransferSource(opt.TransferSource);
    //solve_config.setTransferEnv(opt.TransferEnv);
    solve_config.setTransferVariables(opt.TransferVariables);
    solve_config.setKeepEngine(opt.KeepEngine);
    jinvoke(solve_config,'setWindowsStartupOptionsAsString',opt.WindowsStartupOptions);
    jinvoke(solve_config,'setLinuxStartupOptionsAsString',opt.LinuxStartupOptions);

    solve_config.setInputSpaceName('ScilabInputSpace');
    solve_config.setOutputSpaceName('ScilabOutputSpace');

    solve_config.setVersionPref(opt.VersionPref);
    solve_config.setVersionRejAsString(opt.VersionRej);
    solve_config.setVersionMin(opt.VersionMin);
    solve_config.setVersionMax(opt.VersionMax);
    solve_config.setCheckMatSciUrl(opt.FindScilabScript);
    if ischar(opt.CustomScript)
        selects = opt.CustomScript
        try
            url=URL.new(selects);
            ok = true;
        catch
            ok = false;
        end
        jremove(url);

        if ~ok
            solve_config.setCustomScriptUrl(strcat(['file:', selects]));
        else
            solve_config.setCustomScriptUrl(selects);
        end
    end

    solve_config.setZipSourceFiles(%f);

    curr_dir = pwd();
    fs=filesep();
    curr_dir_java = File.new(curr_dir);
    if ~jinvoke(curr_dir_java,'canWrite')
        jremove(curr_dir_java);
        error('Current Directory should have write access rights');
    end
    jremove(curr_dir_java);

    // PAScheduler sub directory init

    subdir = '.PAScheduler';
    solve_config.setTempSubDirName(subdir);

    if isempty(opt.CustomDataspaceURL)
        if ~isdir(strcat([curr_dir, fs, subdir]))
            mkdir(curr_dir,subdir);
        end
        pa_dir = strcat([curr_dir, fs, subdir]);
    else
        if isempty(opt.CustomDataspacePath)
            error('if CustomDataspaceURL is specified, CustomDataspacePath must be specified also');
        end
        if ~isdir(strcat([opt.CustomDataspacePath, fs, subdir]))
            mkdir(opt.CustomDataspacePath,subdir);
        end
        pa_dir = strcat([opt.CustomDataspacePath, fs, subdir]);
    end

    if isempty(opt.CustomDataspaceURL)
        if ~exists('DataRegistryInit') | DataRegistryInit ~= 1
            DataRegistry = AODataspaceRegistry.new('ScilabInputSpace','ScilabOutputSpace','ScilabSession',opt.Debug);
            DataRegistryInit = 1;
        end
        pair = DataRegistry.createDataSpace(curr_dir);
        px=jinvoke(pair,'getX');
        py=jinvoke(pair,'getY');
        pxs = jcast(px,'java.lang.String');
        pys = jcast(py,'java.lang.String');
        solve_config.setInputSpaceURL(pxs);
        solve_config.setOutputSpaceURL(pys);
        if opt.Debug then
            disp('using Dataspace:')
            disp(pxs)
        end

    else
        solve_config.setOutputSpaceURL(opt.CustomDataspaceURL);
        solve_config.setInputSpaceURL(opt.CustomDataspaceURL);
    end

    variableInFileBaseName = ['ScilabPAsolveVarIn_' string(SOLVEid)];
    variableOutFileBaseName = ['ScilabPAsolveVarOut_' string(SOLVEid)];
    outVarFiles = list(NN);
    //tmpFiles = list();
    taskFilesToClean = list();

    task_configs = jarray('org.ow2.proactive.scheduler.ext.scilab.common.PASolveScilabTaskConfig', NN,MM);
    for i=1:NN
        taskFilesToClean($+1)=list();
        for j=1:MM
            t_conf = jnewInstance(PASolveScilabTaskConfig);
            task_configs(i-1,j-1) = t_conf;
            if ~isempty(Tasks(j,i).Description) then
                t_conf.setDescription(Tasks(j,i).Description);
            end

            // Input Files
            if ~isempty(Tasks(j,i).InputFiles) then
                ilen = length(Tasks(j,i).InputFiles);
                if ilen > 0 then
                    inputFiles = jarray('java.lang.String', ilen);
                    filelist = Tasks(j,i).InputFiles;
                    for k=1:ilen
                        filename = filelist(k);
                        inputFiles(k-1)=String.new(strsubst(filename,'\','/'));
                    end

                    t_conf.setInputFiles(inputFiles);
                    t_conf.setInputFilesThere(%t);
                end
            end

            // Output Files
            if ~isempty(Tasks(j,i).OutputFiles) then
                filelist = Tasks(j,i).OutputFiles;
                ilen = length(filelist);
                if ilen > 0 then
                    outputFiles = jarray('java.lang.String', ilen);
                    for k=1:ilen
                        filename = filelist(k);
                        outputFiles(k-1)=String.new(strsubst(filename,'\','/'));
                    end

                    t_conf.setOutputFiles(outputFiles);
                    t_conf.setOutputFilesThere(%t);
                end
            end

            // Custom Script
            if ~isempty(Tasks(j,i).SelectionScript) then
                selects = Tasks(j,i).SelectionScript;
                try
                    url = URL.new(selects);
                    ok = true;
                catch
                    ok = false;
                end
                jremove(url);

                if ~ok
                    t_conf.setCustomScriptUrl(strcat(['file:', selects ]));
                else
                    t_conf.setCustomScriptUrl(selects);
                end
            end

            // Function
            Func = Tasks(j,i).Func;
            execstr(strcat(['functype = type(';Func;');']));
            if (functype <> 13) & (functype <> 11)  then
                error('invalid function type for function ""' + Func + '"". Consider calling this function with a macro instead.');
            end

            // Source Files

            if ~isempty(Tasks(j,i).Sources) then
                srcs = Tasks(j,i).Sources;
                for k=1:length(srcs)
                    srcPath = srcs(k);
                    if isfile(srcPath) then
                        [ppath,fname,extension]=fileparts(srcPath);
                        srcName = strcat(strcat([fname,extension]));

                        if opt.Debug then
                            disp(strcat(['Copying file ', srcPath, ' to ',pa_dir]));
                        end
                        copyfile(srcPath,pa_dir);
                        // TODO find a cleaning mechanisme
                        //taskFilesToClean(i)=lstcat(taskFilesToClean(i), list(pa_dir+fs+fname+extension));
                        //tmpFiles($+1)=strcat([pa_dir,fs,fname,extension]);

                        strName = String.new(srcName);
                        t_conf.addSourceFile(strName);
                    else
                        error(strcat(['Source file ', srcPath, ' cannot be found']));
                    end

                end

            end

            // Saving main function name (with or without Sources attribute)
            sourceNames = jarray('java.lang.String', 1);
            sFN = 'ScilabPAsolve_src'+string(SOLVEid)+indToFile([i j])+'.bin';
            execstr('save(pa_dir+fs+sFN,'+Func+');');
            strName = String.new(sFN);
            sourceNames(0) = strName;
            t_conf.setFunctionVarFiles(sourceNames);
            code=[];
            taskFilesToClean(i)=lstcat(taskFilesToClean(i), list(pa_dir+fs+sFN));

            t_conf.setFunctionName(Func);
            t_conf.addSourceFile(sFN);

            // Params
            argi = Tasks(j,i).Params;
            if opt.TransferVariables
                inVarFN = strcat([variableInFileBaseName, indToFile([i j]), '.dat']);
                outVarFN = strcat([variableOutFileBaseName, indToFile([i j]), '.dat']);
                inVarFP = strcat([pa_dir, fs, inVarFN]);
                outVarFP = strcat([pa_dir, fs, outVarFN]);
                // Creating input parameters mat files
                fd=mopen(inVarFP,'wb');
                inl = argi;
                if length(inl) == 0
                    inl=list(%t);
                end
                for k=1:length(inl)
                    execstr('in'+string(k)+'=inl(k);');
                    execstr('save(fd,in'+string(k)+')');
                end
                mclose(fd);

                jinvoke(t_conf,'setInputVariablesFileName',inVarFN);
                jinvoke(t_conf,'setOutputVariablesFileName',outVarFN);
                if j > 1 & Tasks(j,i).Compose
                    cinVarFN = strcat([variableOutFileBaseName,indToFile([i j-1]),'.dat']);
                    cinVarFP = pa_dir+fs+cinVarFN;
                    jinvoke(t_conf,'setComposedInputVariablesFileName',cinVarFN);
                end
                outVarFiles(i) = outVarFP;
                taskFilesToClean(i)=lstcat(taskFilesToClean(i), list(inVarFP));
                //if j < MM
                // because of disconnected mode, the final out is handled
                //differently
                taskFilesToClean(i)=lstcat(taskFilesToClean(i), list(outVarFP));
                //end

                inputscript = 'i=0';
            else
                inputscript = createInputScript(argi);
            end

            t_conf.setInputScript(inputscript);

            //mainScript = createMainScript(Func, opt);
            mainScript = 'out = '+Tasks(j,i).Func+'(';
            if j > 1 & Tasks(j,i).Compose
                mainScript = mainScript + 'in';
                if length(argi) > 0 then
                    mainScript = mainScript + ',';
                end
            end
            if length(argi) > 0
                for k=1:length(argi)-1
                    mainScript = mainScript + 'in'+string(k)+',';
                end
                mainScript = mainScript + ('in'+string(length(argi)));
            end
            mainScript = mainScript + ');';
            t_conf.setMainScript(mainScript);

            t_conf.setOutputs('out');

        end
    end
    jimport org.ow2.proactive.scheduler.ext.scilab.client.ScilabSolver;
    jimport org.objectweb.proactive.api.PAFuture;
    solver = jnewInstance(ScilabSolver);

    pairinfolist = solver.solve(solve_config, task_configs);

    jobinfo = jinvoke(pairinfolist,'getX');
    resfutureList =  jinvoke(pairinfolist,'getY');
    jid = string(jinvoke(jobinfo,'getJobId'));
    disp('Job submitted : '+ jid);

    ftn = jinvoke(jobinfo,'getFinalTasksNamesAsList');

    taskinfo = struct('cleanFileSet',[],'cleanDirSet',[], 'outFile',[], 'jobid',[], 'taskid',[] );
    results=list(NN);
    for i=1:NN
        taskinfo.cleanFileSet = taskFilesToClean(i);
        taskinfo.cleanDirSet = list(pa_dir);
        taskinfo.outFile = outVarFiles(i);
        taskinfo.jobid = jid;
        taskinfo.taskid = jinvoke(ftn,'get',i-1);

        results(i)=PAResult(jinvoke(resfutureList,'get',i-1), taskinfo);

    end
    outputs = PAResL(results);
    jremove(solver, solve_config, task_configs);

endfunction

function nm=indToFile(ind)
    nm='';
    if ind==-1
        return;
    end
    for JJ=ind
        nm=strcat([nm, '_', string(JJ)]);
    end
endfunction

function inputScript = createInputScript(arg)
    // We transform the argument to executable scilab code
    argcode = sci2exp(arg,'in');
    // The inputscript will contain the argument and the code of the functions
    inputscript_array=[argcode];
    // The code defining the function is made of many lines, we pack it by using ASCII 31 delimiters
    s=size(inputscript_array);
    inputscript_str='';
    for j=1:(s(1)-1)
        inputscript_str=inputscript_str+inputscript_array(j)+ascii(31);
    end
    inputscript_str=inputscript_str+inputscript_array(s(1));
    // We tranform the final packed command as an assigment to evaluate
    inputscript_assignment = sci2exp(inputscript_str, 'inputscript');
    // We add the code used to decode the packed instructions
    inputscript_decode = 'TOKENS = tokens(inputscript,ascii(31)); execstr(TOKENS,''errcatch'',''m'');';
    inputScript = strcat([inputscript_assignment;';';inputscript_decode]);
endfunction

function mainScript = createMainScript(funcName, opt)
    debugv = opt.Debug;
    if debugv == 1
        //mainScript = strcat(['mode(3)';ascii(31);'out=';funcName;'(in)';ascii(31);ascii(30);'output = sci2exp(output,''''output'''',0)';ascii(31);'disp(out)']);
        mainScript = strcat(['mode(3)';ascii(31);'out=';funcName;'(in)';ascii(31);'disp(out)']);
    else
        //mainScript = strcat(['out=';funcName;'(in);';ascii(31);ascii(30);'output = sci2exp(output,''''output'''',0);']);
        mainScript = strcat(['out=';funcName;'(in);']);
    end
endfunction


sb120: #i111197# disabled failing tests for now

-o sw.CharacterStyle
-o sw.ConditionalParagraphStyle
-o sw.PageStyle
-o sw.ParagraphStyle
#i111197 -o sw.SwAccessibleDocumentPageView
#i86751 -o sw.SwAccessibleDocumentView
#i111185 -o sw.SwAccessibleEndnoteView
-o sw.SwAccessibleFooterView
#i111185 -o sw.SwAccessibleFootnoteView
-o sw.SwAccessibleHeaderView
#i89022 -o sw.SwAccessiblePageView
-o sw.SwAccessibleParagraphView
-o sw.SwAccessibleTableCellView
#i85634 -o sw.SwAccessibleTableView
#i111178 -o sw.SwAccessibleTextEmbeddedObject
#i111178 -o sw.SwAccessibleTextFrameView
-o sw.SwAccessibleTextGraphicObject
-o sw.SwXAutoTextContainer
-o sw.SwXAutoTextEntry
-o sw.SwXAutoTextGroup
#i111185 -o sw.SwXBodyText
-o sw.SwXBookmark
-o sw.SwXBookmarks
-o sw.SwXCell
-o sw.SwXCellRange
-o sw.SwXChapterNumbering
#i111185 -o sw.SwXDocumentIndex
#i111185 -o sw.SwXDocumentIndexMark
-o sw.SwXDocumentIndexes
-o sw.SwXDrawPage
#i111185 -o sw.SwXEndnoteProperties
-o sw.SwXFieldEnumeration
-o sw.SwXFieldMaster
#i111185 -o sw.SwXFootnote
#i111185 -o sw.SwXFootnoteProperties
#i111185 -o sw.SwXFootnoteText
#i111185 -o sw.SwXFootnotes
-o sw.SwXFrames
#i111185 -o sw.SwXHeadFootText
-o sw.SwXLineNumberingProperties
#i85640 -o sw.SwXMailMerge
-o sw.SwXModule
-o sw.SwXNumberingRules
#i103696 -o sw.SwXParagraph
-o sw.SwXParagraphEnumeration
-o sw.SwXPrintSettings
-o sw.SwXPropertySet
-o sw.SwXPropertySetInfo
-o sw.SwXReferenceMark
-o sw.SwXReferenceMarks
#i111190 -o sw.SwXShape
-o sw.SwXStyleFamilies
-o sw.SwXStyleFamily
#i111185 -o sw.SwXTableCellText
-o sw.SwXTableColumns
-o sw.SwXTableRows
-o sw.SwXTextColumns
-o sw.SwXTextCursor
#i89021 -o sw.SwXTextDefaults
#i111185 -o sw.SwXTextDocument
-o sw.SwXTextEmbeddedObject
-o sw.SwXTextEmbeddedObjects
-o sw.SwXTextField
-o sw.SwXTextFieldMasters
-o sw.SwXTextFieldTypes
-o sw.SwXTextFrame
#i111185 -o sw.SwXTextFrameText
-o sw.SwXTextGraphicObject
-o sw.SwXTextGraphicObjects
#i103696 -o sw.SwXTextPortion
-o sw.SwXTextPortionEnumeration
-o sw.SwXTextRange
-o sw.SwXTextRanges
-o sw.SwXTextSearch
-o sw.SwXTextSection
-o sw.SwXTextSections
-o sw.SwXTextTable
-o sw.SwXTextTableCursor
-o sw.SwXTextTableRow
-o sw.SwXTextTables
#i85580 -o sw.SwXTextView
-o sw.SwXTextViewCursor
-o sw.SwXViewSettings
-o sw.XMLContentExporter
#i23394 -o sw.XMLContentImporter
#i111194-o sw.XMLExporter
-o sw.XMLImporter
#i23394 -o sw.XMLMetaExporter
-o sw.XMLMetaImporter
-o sw.XMLSettingsExporter
-o sw.XMLSettingsImporter
-o sw.XMLStylesExporter
#i23394 -o sw.XMLStylesImporter
-o sw.DocumentSettings

-o sw.CharacterStyle
-o sw.ConditionalParagraphStyle
-o sw.PageStyle
-o sw.ParagraphStyle
-o sw.SwAccessibleDocumentPageView
#i86751 -o sw.SwAccessibleDocumentView
#i111185 -o sw.SwAccessibleEndnoteView
-o sw.SwAccessibleFooterView
#i111185 -o sw.SwAccessibleFootnoteView
-o sw.SwAccessibleHeaderView
#i89022 -o sw.SwAccessiblePageView
-o sw.SwAccessibleParagraphView
-o sw.SwAccessibleTableCellView
#i85634 -o sw.SwAccessibleTableView
#i111178 -o sw.SwAccessibleTextEmbeddedObject
#i111178 -o sw.SwAccessibleTextFrameView
-o sw.SwAccessibleTextGraphicObject
-o sw.SwXAutoTextContainer
-o sw.SwXAutoTextEntry
-o sw.SwXAutoTextGroup
#i111185 -o sw.SwXBodyText
-o sw.SwXBookmark
-o sw.SwXBookmarks
-o sw.SwXCell
-o sw.SwXCellRange
-o sw.SwXChapterNumbering
#i111185 -o sw.SwXDocumentIndex
#i111185 -o sw.SwXDocumentIndexMark
-o sw.SwXDocumentIndexes
-o sw.SwXDrawPage
#i111185 -o sw.SwXEndnoteProperties
-o sw.SwXFieldEnumeration
-o sw.SwXFieldMaster
#i111185 -o sw.SwXFootnote
#i111185 -o sw.SwXFootnoteProperties
#i111185 -o sw.SwXFootnoteText
#i111185 -o sw.SwXFootnotes
-o sw.SwXFrames
#i111185 -o sw.SwXHeadFootText
-o sw.SwXLineNumberingProperties
#i85640 -o sw.SwXMailMerge
-o sw.SwXModule
-o sw.SwXNumberingRules
#i103696 -o sw.SwXParagraph
-o sw.SwXParagraphEnumeration
-o sw.SwXPrintSettings
-o sw.SwXPropertySet
-o sw.SwXPropertySetInfo
-o sw.SwXReferenceMark
-o sw.SwXReferenceMarks
#i111190 -o sw.SwXShape
-o sw.SwXStyleFamilies
-o sw.SwXStyleFamily
#i111185 -o sw.SwXTableCellText
-o sw.SwXTableColumns
-o sw.SwXTableRows
-o sw.SwXTextColumns
-o sw.SwXTextCursor
#i89021 -o sw.SwXTextDefaults
#i111185 -o sw.SwXTextDocument
-o sw.SwXTextEmbeddedObject
-o sw.SwXTextEmbeddedObjects
-o sw.SwXTextField
-o sw.SwXTextFieldMasters
-o sw.SwXTextFieldTypes
-o sw.SwXTextFrame
#i111185 -o sw.SwXTextFrameText
-o sw.SwXTextGraphicObject
-o sw.SwXTextGraphicObjects
#i103696 -o sw.SwXTextPortion
-o sw.SwXTextPortionEnumeration
-o sw.SwXTextRange
-o sw.SwXTextRanges
-o sw.SwXTextSearch
-o sw.SwXTextSection
-o sw.SwXTextSections
-o sw.SwXTextTable
-o sw.SwXTextTableCursor
-o sw.SwXTextTableRow
-o sw.SwXTextTables
#i85580 -o sw.SwXTextView
-o sw.SwXTextViewCursor
-o sw.SwXViewSettings
-o sw.XMLContentExporter
#i23394 -o sw.XMLContentImporter
#i111194-o sw.XMLExporter
-o sw.XMLImporter
#i23394 -o sw.XMLMetaExporter
-o sw.XMLMetaImporter
-o sw.XMLSettingsExporter
-o sw.XMLSettingsImporter
-o sw.XMLStylesExporter
#i23394 -o sw.XMLStylesImporter
-o sw.DocumentSettings


AI scan init - reshape scan summary info

function  mdaqAIScanInit(arg1, arg2, arg3, arg4, arg5, arg6)
    link_id = -1;

    if argn(2) == 5 then
        channels = arg1;
        aiRange = arg2;
        aiMode = arg3;
        scan_freq = arg4;
        scan_time = arg5;
    end

    if argn(2) == 6 then
        link_id = arg1;
        channels = arg2;
        aiRange = arg3;
        aiMode = arg4;
        scan_freq = arg5;
        scan_time = arg6;

        if link_id < 0 then
            error("Invalid connection ID!")
            return;
        end
    end

    global %microdaq;
    if %microdaq.private.mdaq_hwid <> [] then
        adc_info = get_adc_info(%microdaq.private.mdaq_hwid);
        if argn(2) > 6 | argn(2) < 5 then
            mprintf("Description:\n");
            mprintf("\tInit AI scan\n");
            mprintf("Usage:\n");
            mprintf("\tmdaqAIScanInit(link_id, channels, range, mode, frequency, duration);\n");                     mprintf("\tlink_id - connection id returned by mdaqOpen() (OPTIONAL)\n");
            mprintf("\tchannels - analog input channels to read\n");
            mprintf("\trange - analog input range matrix e.g.\n");
            mprintf("\t        [-10,10] - single range argument applied for all used channels\n");
            mprintf("\t        [-10,10;-5,5] - multi-range argument for two channels\n");
            mprintf("\tfrequency - scan frequency\n");
            mprintf("\tduration - scan duration in seconds\n");
            return;
        end
    else
        error('Unable to detect MicroDAQ confituration - run mdaqHWInfo and try again!');
        return;
    end

    if scan_time < 0 then
        scan_time = -1;
    end

    if size(channels, 'r') > 1 then
        error('Wrong channel - scalar or single row vector expected')
    end

    if size(aiRange, 'c') <> 2 then
        error('Wrong range - matrix range [low,high;low,high;...] expected')
    end

    if size(aiMode, 'r') > 1 then
        error('Wrong mode - scalar or single row vector expected')
    end

    ch_count = size(channels, 'c');

    aiRangeSize = size(aiRange, 'r');
    if aiRangeSize <> 1 & aiRangeSize <> ch_count then
        error('Range vector should match selected AI channels')
    end

    aiModeSize = size(aiMode, 'c');
    if aiModeSize <> 1 & aiModeSize <> ch_count then
        error('Mode vector should match selected AI channels')
    end

    if aiRangeSize == 1 then
        range_tmp = aiRange;
        aiRange = ones(ch_count,2);
        aiRange(:,1) = range_tmp(1);
        aiRange(:,2) = range_tmp(2);
        clear range_tmp;
    end

    aiRange_t = aiRange;
    aiRange = matrix(aiRange', 1, ch_count*2);

    aiMode(find(aiMode==%T))=1;
    if aiModeSize == 1 then
        aiMode = ones(1, ch_count) * aiMode;
    end

    if argn(2) == 5 then
        link_id = mdaqOpen();
        if link_id < 0 then
            error("Unable to connect to MicroDAQ device!");
        end
    end

    result = [];
    real_freq = scan_freq;
    [result real_freq] = call("sci_mlink_ai_scan_init",..
                    link_id, 1, "i",..
                    channels, 2, "i",..
                    ch_count, 3, "i",..
                    aiRange, 4, "d",..
                    aiMode, 5, "i",..
                    scan_freq, 6, "d",..
                    scan_time, 7, "d",..
                "out",..
                    [1, 1], 9, "i",..
                    [1, 1], 8, "d");

    if result < 0 & result <> -88 then
        if argn(2) == 5 then
            mdaqClose(link_id);
        end
        error(mdaq_error2(result), 10000 + abs(result));
    else
        if result == -88 then
            disp("Warninng: AI scanning interrupted!")
            mdaqAIScanStop()

            // time to terminate TCP connection
            sleep(200);
            [result real_freq] = call("sci_mlink_ai_scan_init",..
                            link_id, 1, "i",..
                            channels, 2, "i",..
                            ch_count, 3, "i",..
                            aiRange, 4, "d",..
                            aiMode, 5, "i",..
                            scan_freq, 6, "d",..
                            scan_time, 7, "d",..
                        "out",..
                            [1, 1], 9, "i",..
                            [1, 1], 8, "d");
        end

        if argn(2) == 5 then
            mdaqClose(link_id);
        end

        if result < 0 then
            error(mdaq_error2(result), 10000 + abs(result));
        end

        if result == 1 then
            limited_cap = %t;
        else
            limited_cap = %f;
        end

        rows = [];
        row = '';

        adc_res = strtod(part(adc_info.resolution, 1:2))
        for j=1:ch_count
            if aiMode(j) == 1 then
                measure_type = "Differential"
            elseif (aiMode(j) == 0)
                measure_type = "Single-ended"
            end
            adc_range = aiRange_t(j, 2) - aiRange_t(j, 1);
            resolution = string((int(adc_range/2^adc_res * 1000000)) / 1000);
            rangeStr="";
            if aiRange_t(j, 1) < 0 then
                rangeStr = "±" + string(aiRange_t(j, 2))+"V";
            else
                rangeStr = "0-" + string(aiRange_t(j, 2))+"V";
            end
            rows = [rows; "AI"+string(channels(j)), measure_type, rangeStr, resolution+"mV"]
        end

        mprintf("\nAnalog input scanning session settings:\n");
        mprintf("\t--------------------------------------------------\n")
        str2table(rows, ["Channel", "Measurement type", "Range", "Resolution"], 3)
        mprintf("\t--------------------------------------------------\n")
        if scan_freq >= 1000
            mprintf("\tScan frequency:\t\t%.5f kHz\n", scan_freq/1000);
            mprintf("\tActual scan frequency:\t%.5f kHz\n", real_freq/1000);
        else
            mprintf("\tScan frequency:\t\t%.5f Hz\n", scan_freq);
            mprintf("\tActual scan frequency:\t%.5f Hz\n", real_freq);
        end
        if 1 /real_freq > 0.001 then
            mprintf("\tScan period: \t\t%.5f seconds\n", 1 / real_freq);
        end

        if 1 /real_freq <= 0.001 then
            mprintf("\tScan period: \t\t%.5f ms\n", 1 / real_freq * 1000);
        end

        if scan_time < 0
            mprintf("\tNumber of channels:\t%d\n", ch_count)
            mprintf("\tNumber of scans:\tInf\n");
            mprintf("\tDuration:\t\tInf\n");
        else
            mprintf("\tNumber of channels:\t%d\n", ch_count)
            mprintf("\tNumber of scans:\t%d\n", scan_time * scan_freq);
            if scan_time == 1
                mprintf("\tDuration:\t\t%.2f second\n", scan_time);
            else
                mprintf("\tDuration:\t\t%.2f seconds\n", scan_time);
            end
        end
        mprintf("\t--------------------------------------------------\n")
    end
endfunction

function  mdaqAIScanInit(arg1, arg2, arg3, arg4, arg5, arg6)
    link_id = -1;

    if argn(2) == 5 then
        channels = arg1;
        aiRange = arg2;
        aiMode = arg3;
        scan_freq = arg4;
        scan_time = arg5;
    end

    if argn(2) == 6 then
        link_id = arg1;
        channels = arg2;
        aiRange = arg3;
        aiMode = arg4;
        scan_freq = arg5;
        scan_time = arg6;

        if link_id < 0 then
            error("Invalid connection ID!")
            return;
        end
    end

    global %microdaq;
    if %microdaq.private.mdaq_hwid <> [] then
        adc_info = get_adc_info(%microdaq.private.mdaq_hwid);
        if argn(2) > 6 | argn(2) < 5 then
            mprintf("Description:\n");
            mprintf("\tInit AI scan\n");
            mprintf("Usage:\n");
            mprintf("\tmdaqAIScanInit(link_id, channels, range, mode, frequency, duration);\n");                     mprintf("\tlink_id - connection id returned by mdaqOpen() (OPTIONAL)\n");
            mprintf("\tchannels - analog input channels to read\n");
            mprintf("\trange - analog input range matrix e.g.\n");
            mprintf("\t        [-10,10] - single range argument applied for all used channels\n");
            mprintf("\t        [-10,10;-5,5] - multi-range argument for two channels\n");
            mprintf("\tfrequency - scan frequency\n");
            mprintf("\tduration - scan duration in seconds\n");
            return;
        end
    else
        error('Unable to detect MicroDAQ confituration - run mdaqHWInfo and try again!');
        return;
    end

    if scan_time < 0 then
        scan_time = -1;
    end

    if size(channels, 'r') > 1 then
        error('Wrong channel - scalar or single row vector expected')
    end

    if size(aiRange, 'c') <> 2 then
        error('Wrong range - matrix range [low,high;low,high;...] expected')
    end

    if size(aiMode, 'r') > 1 then
        error('Wrong mode - scalar or single row vector expected')
    end

    ch_count = size(channels, 'c');

    aiRangeSize = size(aiRange, 'r');
    if aiRangeSize <> 1 & aiRangeSize <> ch_count then
        error('Range vector should match selected AI channels')
    end

    aiModeSize = size(aiMode, 'c');
    if aiModeSize <> 1 & aiModeSize <> ch_count then
        error('Mode vector should match selected AI channels')
    end

    if aiRangeSize == 1 then
        range_tmp = aiRange;
        aiRange = ones(ch_count,2);
        aiRange(:,1) = range_tmp(1);
        aiRange(:,2) = range_tmp(2);
        clear range_tmp;
    end

    aiRange_t = aiRange;
    aiRange = matrix(aiRange', 1, ch_count*2);

    aiMode(find(aiMode==%T))=1;
    if aiModeSize == 1 then
        aiMode = ones(1, ch_count) * aiMode;
    end

    if argn(2) == 5 then
        link_id = mdaqOpen();
        if link_id < 0 then
            error("Unable to connect to MicroDAQ device!");
        end
    end

    result = [];
    real_freq = scan_freq;
    [result real_freq] = call("sci_mlink_ai_scan_init",..
                    link_id, 1, "i",..
                    channels, 2, "i",..
                    ch_count, 3, "i",..
                    aiRange, 4, "d",..
                    aiMode, 5, "i",..
                    scan_freq, 6, "d",..
                    scan_time, 7, "d",..
                "out",..
                    [1, 1], 9, "i",..
                    [1, 1], 8, "d");

    if result < 0 & result <> -88 then
        if argn(2) == 5 then
            mdaqClose(link_id);
        end
        error(mdaq_error2(result), 10000 + abs(result));
    else
        if result == -88 then
            disp("Warninng: AI scanning interrupted!")
            mdaqAIScanStop()

            // time to terminate TCP connection
            sleep(200);
            [result real_freq] = call("sci_mlink_ai_scan_init",..
                            link_id, 1, "i",..
                            channels, 2, "i",..
                            ch_count, 3, "i",..
                            aiRange, 4, "d",..
                            aiMode, 5, "i",..
                            scan_freq, 6, "d",..
                            scan_time, 7, "d",..
                        "out",..
                            [1, 1], 9, "i",..
                            [1, 1], 8, "d");
        end

        if argn(2) == 5 then
            mdaqClose(link_id);
        end

        if result < 0 then
            error(mdaq_error2(result), 10000 + abs(result));
        end

        if result == 1 then
            limited_cap = %t;
        else
            limited_cap = %f;
        end

        rows = [];
        row = '';

        adc_res = strtod(part(adc_info.resolution, 1:2))
        for j=1:ch_count
            if aiMode(j) == 1 then
                measure_type = "Differential"
            elseif (aiMode(j) == 0)
                measure_type = "Single-ended"
            end
            adc_range = aiRange_t(j, 2) - aiRange_t(j, 1);
            resolution = string((int(adc_range/2^adc_res * 1000000)) / 1000);
            rangeStr="";
            if aiRange_t(j, 1) < 0 then
                rangeStr = "±" + string(aiRange_t(j, 2))+"V";
            else
                rangeStr = "0-" + string(aiRange_t(j, 2))+"V";
            end
            rows = [rows; string(channels(j)), measure_type, rangeStr, resolution+"mV"]
        end

        mprintf("\nAnalog input scanning session settings:\n");
        mprintf("\t--------------------------------------------------\n")
        str2table(rows, ["Channel", "Measurement type", "Range", "Resolution"], 3)
        mprintf("\t--------------------------------------------------\n")
        if scan_freq >= 1000
            mprintf("\tScan frequency:\t\t%.4fkHz\n", scan_freq/1000);
            mprintf("\tActual scan frequency:\t%.4fkHz\n", real_freq/1000);
        else
            mprintf("\tScan frequency:\t\t%.4fHz\n", scan_freq);
            mprintf("\tActual scan frequency:\t%.4fHz\n", real_freq);
        end
        if 1 /real_freq > 0.001 then
            mprintf("\tScan period: \t\t%fs\n", 1 / real_freq);
        end

        if 1 /real_freq <= 0.001 then
            mprintf("\tScan period: \t\t%fms\n", 1 / real_freq * 1000);
        end

        if scan_time < 0
            mprintf("\tDuration:\t\tInf\n");
            mprintf("\tNumber of scans:\tInf\n");
            mprintf("\tNumber of channels:\t%d\n", ch_count)
        else
            mprintf("\tDuration:\t\t%.2fs\n", scan_time);
            mprintf("\tNumber of scans:\t%d\n", scan_time * scan_freq);
            mprintf("\tNumber of channels:\t%d\n", ch_count)
        end
        mprintf("\t--------------------------------------------------\n")
    end
endfunction


By default enable help builder

By default enable help builder

// Copyright (c) 2015, Embedded Solutions
// All rights reserved.

// This file is released under the 3-clause BSD license. See COPYING-BSD.

mode(-1);
lines(0);

function main_builder()
  TOOLBOX_NAME  = "microdaq";
  TOOLBOX_TITLE = "MicroDAQ toolbox";
  toolbox_dir   = get_absolute_file_path("builder.sce");

// Check Scilab's version
// =============================================================================

  // check minimal version (xcosPal required)
  if ~isdef('xcosPal') then
    // and xcos features required
    error(gettext('Scilab 5.3.2 or more is required.'));
  end

// Check modules_manager module availability
// =============================================================================

  if ~isdef('tbx_build_loader') then
    error(msprintf(gettext('%s module not installed.'), 'modules_manager'));
  end

  if ~isdir(toolbox_dir+filesep()+"images"+filesep()+"h5")
      [status, msg] = mkdir(toolbox_dir+filesep()+"images"+filesep()+"h5");
      if and(status <> [1 2])
          error(msg);
      end
  end

// Action
// =============================================================================

  tbx_builder_macros(toolbox_dir);
  tbx_builder_help(toolbox_dir);
  tbx_build_loader(TOOLBOX_NAME, toolbox_dir);
  tbx_build_cleaner(TOOLBOX_NAME, toolbox_dir);

  //delete mblockstmpdir file to force loader to rebuild mdaq palette
  deletefile(toolbox_dir+filesep()+"etc"+filesep()+"mblockstmpdir");

endfunction

if with_module('xcos') then
  main_builder();
  clear main_builder; // remove main_builder on stack
end

// Copyright (c) 2015, Embedded Solutions
// All rights reserved.

// This file is released under the 3-clause BSD license. See COPYING-BSD.

mode(-1);
lines(0);

function main_builder()
  TOOLBOX_NAME  = "microdaq";
  TOOLBOX_TITLE = "MicroDAQ toolbox";
  toolbox_dir   = get_absolute_file_path("builder.sce");

// Check Scilab's version
// =============================================================================

  // check minimal version (xcosPal required)
  if ~isdef('xcosPal') then
    // and xcos features required
    error(gettext('Scilab 5.3.2 or more is required.'));
  end

// Check modules_manager module availability
// =============================================================================

  if ~isdef('tbx_build_loader') then
    error(msprintf(gettext('%s module not installed.'), 'modules_manager'));
  end

  if ~isdir(toolbox_dir+filesep()+"images"+filesep()+"h5")
      [status, msg] = mkdir(toolbox_dir+filesep()+"images"+filesep()+"h5");
      if and(status <> [1 2])
          error(msg);
      end
  end

// Action
// =============================================================================

  tbx_builder_macros(toolbox_dir);
//  tbx_builder_help(toolbox_dir);
  tbx_build_loader(TOOLBOX_NAME, toolbox_dir);
  tbx_build_cleaner(TOOLBOX_NAME, toolbox_dir);

  //delete mblockstmpdir file to force loader to rebuild mdaq palette
  deletefile(toolbox_dir+filesep()+"etc"+filesep()+"mblockstmpdir");

endfunction

if with_module('xcos') then
  main_builder();
  clear main_builder; // remove main_builder on stack
end


Change FFT demo to infinite running

Change FFT demo to infinite running

// Copyright (c) 2017, Embedded Solutions
// All rights reserved.
// This file is released under the 3-clause BSD license. See COPYING-BSD.
// FFT, AI scan function - DEMO

figH = figure("Figure_name","MicroDAQ FFT demo");
notInitialized = 1;
divFac = 10;
axisH = [];

// AI scan parameters
scanFreq = 100000;
channel = 1;
AIRange = [-5 5];
isDifferential = %F;
numOfSmaples = scanFreq/divFac;
duration = -1;

// Initialize analog input scanning
mdaqAIScanInit(channel, AIRange, isDifferential, scanFreq, duration);

while %T
    // Acquire data
    [data result] = mdaqAIScan(numOfSmaples, %T);

    // Calculate FFT
    data = data - mean(data);
    y = fft(data');
    f = scanFreq*(0:(numOfSmaples/10))/numOfSmaples;
    n = size(f,'*');

    // Update plot
    if is_handle_valid(figH) then
        if notInitialized == 1 then
            clf();
            plot(f,abs(y(1:n)));
            title("FFT", "fontsize", 3);
            xlabel("Frequency [Hz]","fontsize", 3);
            notInitialized = 0;
            axisH = gca();
        else
            axisH.children.children.data(:,2) = abs(y(1:n))';
        end
    else
        // Stop scanning
        mdaqAIScanStop();
        break;
    end
end

// Close plot
mprintf("\nFFT demo has been stopped.");
if is_handle_valid(figH) then
    close(figH);
end

// Copyright (c) 2017, Embedded Solutions
// All rights reserved.
// This file is released under the 3-clause BSD license. See COPYING-BSD.
// FFT, AI scan function - DEMO

figH = figure("Figure_name","MicroDAQ FFT demo");
notInitialized = 1;
divFac = 10;
axisH = [];

// AI scan parameters
scanFreq = 100000;
channel = 1;
AIRange = [-5 5];
isDifferential = %F;
numOfSmaples = scanFreq/divFac;
duration = 120;

// Initialize analog input scanning
mdaqAIScanInit(channel, AIRange, isDifferential, scanFreq, duration);

for i=1:(duration*divFac)
    // Acquire data
    [data result] = mdaqAIScan(numOfSmaples, %T);

    // Calculate FFT
    data = data - mean(data);
    y = fft(data');
    f = scanFreq*(0:(numOfSmaples/10))/numOfSmaples;
    n = size(f,'*');

    // Update plot
    if is_handle_valid(figH) then
        if notInitialized == 1 then
            clf();
            plot(f,abs(y(1:n)));
            title("FFT", "fontsize", 3);
            xlabel("scanFrequency [Hz]","fontsize", 3);
            notInitialized = 0;
            axisH = gca();
        else
            axisH.children.children.data(:,2) = abs(y(1:n))';
        end
    else
        // Stop scanning
        mdaqAIScanStop();
        break;
    end
end

// Close plot
mprintf("\nFFT demo has been stopped.");
if is_handle_valid(figH) then
    close(figH);
end


More changes

More changes

# Prologue
import numpy as np
from os import listdir
from os.path import isfile, join

path = Path[0]
CSVFiles = [f for f in listdir(path) if f[-4:] == '.csv']
CSVFiles.sort()

names = s.getColumnNames()
path = param(s, 'Path')
# Delete old columns
for name in names:
  if not name in ['row', 'InputFile', 'CSVFiles', 'Path']:
    s.deleteColumn(name)
# Get the file to process
# Check for a missing file
if len(InputFile) == 0:
  if not this_file in CSVFiles:
    InputFile = ["***File not found"]
else:
  this_file = InputFile[0]
  full_file = join(path, this_file)
  new_columns = importCSV(s, full_file)

# Prologue
import numpy as np
from os import listdir
from os.path import isfile, join

path = param(s, 'Path')
InputFile[2] = "h"
CSVFiles = [f for f in listdir(path) if f[-4:] == '.csv']
CSVFiles.sort()

names = s.getColumnNames()
path = param(s, 'Path')
# Delete old columns
for name in names:
  if not name in ['row', 'InputFile', 'CSVFiles', 'Path']:
    s.deleteColumn(name)
# Get the file to process
this_file = InputFile[0]
# Check for a missing file
InputFile[2] = "h"
if len(this_file) > 0:
  if not this_file in CSVFiles:
    InputFile[1] = "***File"
  else:
    InputFile[1] = None
    full_file = join(path, this_file)
    new_columns = importCSV(s, full_file)


Delete Gustatory_Synesthesia_Localizer_MRI.sce

########################################################
# Sounds -> Synesthesia - blocked fMRI
# O. Colizoli, 2012
# Universiteit van Amsterdam (Dept. Psych.)

# Presentation SCE file
# blocked fMRI - ABCDABCD
# 16 seconds active, 16 sec baseline (fixation cross)
# 4 conditions:
# Dutch words spoken
# Foreign words spoken
# Musical instruments
# Daily environmental sounds
# Instructions - passive viewing, maintain fixation
# 4 conditions x 5 blocks = 20 blocks total
# 16 images per block x 5 blocks per condition
########################################################

scenario = "Gustatory_Synesthesia_Localizer_MRI";

default_background_color = 0, 0, 0;
default_font = "courier new";
default_font_size = 60;
default_text_color = 255,255,255;
response_matching = simple_matching;
response_logging = log_all;
active_buttons = 8;
button_codes = 1,2,3,4,5,6,7,8;

scenario_type = fMRI_emulation;
scan_period = 2000;   # (ms) only here to make emulation possible if desired
#scenario_type = fMRI;
pulses_per_scan = 1;
pulse_code = 255;

begin;

################ STIMULUS DEFINITIONS ################

array{ #spoken words dutch
sound { wavefile { filename = "Dutch_news1.wav";};  description = "DutchNews1"; } dutch_spoken1; #1
sound { wavefile { filename = "Dutch_news2.wav";};  description = "DutchNews2"; } dutch_spoken2; #2
sound { wavefile { filename = "Dutch_news3.wav";};  description = "DutchNews3"; } dutch_spoken3; #3
sound { wavefile { filename = "Dutch_news4.wav";};  description = "DutchNews4"; } dutch_spoken4; #4
sound { wavefile { filename = "Dutch_news5.wav";};  description = "DutchNews5"; } dutch_spoken5; #5
} spoken_dutch;

array{ #spoken words dutch
sound { wavefile { filename = "Turkish_news1.wav";};  description = "TurkishNews1"; } foreign_spoken1; #1
sound { wavefile { filename = "Turkish_news2.wav";};  description = "TurkishNews2"; } foreign_spoken2; #2
sound { wavefile { filename = "Turkish_news3.wav";};  description = "TurkishNews3"; } foreign_spoken3; #3
sound { wavefile { filename = "Russian_news1.wav";};  description = "RussianNews1"; } foreign_spoken4; #4
sound { wavefile { filename = "Russian_news2.wav";};  description = "RussianNews2"; } foreign_spoken5; #5
} spoken_foreign;

array{ # 10 musical instruments
sound { wavefile { filename = "Doedelzak fragment.wav";};  description = "bagpipe"; } music1; #1
sound { wavefile { filename = "Drums fragment.wav";};  description = "drums"; } music2; #2
sound { wavefile { filename = "Gitaar fragment.wav";}; description = "guitar"; } music3; #3
sound { wavefile { filename = "Hobo fragment.wav";}; description = "oboe"; } music4; #4
sound { wavefile { filename = "Trompet fragment.wav";}; description = "trumpet"; } music5; #5
sound { wavefile { filename = "triangel.wav";}; description = "triangle"; } music6; #6
sound { wavefile { filename = "accordeon.wav";}; description = "accordian"; } music7; #7
sound { wavefile { filename = "trommels.wav";}; description = "drumline"; } music8; #8
sound { wavefile { filename = "mondharmonica.wav";}; description = "harmonica"; } music9; #9
sound { wavefile { filename = "xylofoon.wav";}; description = "xylophone"; } music10; #10
} music;

array{ # 80 words
sound { wavefile { filename = "Applause.wav";};  description = "applause"; } noise1; #1
sound { wavefile { filename = "Rain.wav";};  description = "rain"; } noise2; #2
sound { wavefile { filename = "Siren.wav";}; description = "siren"; } noise3; #3
sound { wavefile { filename = "wind.wav";}; description = "wind"; } noise4; #4
sound { wavefile { filename = "electric_fan.wav";}; description = "electric_fan"; } noise5; #5
sound { wavefile { filename = "pckeyboard.wav";}; description = "keyboard"; } noise6; #6
sound { wavefile { filename = "typewriter.wav";}; description = "typewriter"; } noise7; #7
sound { wavefile { filename = "race_car.wav";}; description = "race_car"; } noise8; #8
} noise;

picture { description = "rest"; text {caption = "+"; font_size = 30; font = "Times New Roman";}; x = 0; y = 0; } rest;

#Instructions for participants
picture { text {caption = "You will hear a series of words and sounds.

Please keep your eyes closed during this entire scan.

The experiment will start at any moment.
Make sure that you stay still and close your eyes! ";
font_size = 24; font = "Times New Roman";
}; x = 0; y = 0; } startTrialPicture;

# Blank and fixation screens
picture {background_color = 0,0,0;} white_screen;
picture {text {caption = "+";  font_size=30; font = "Times New Roman";} fix_text; x = 0; y = 0; }  pic_fix;

############ Start fMRI Trial ####################
trial {
   picture startTrialPicture;
   time = 0;
   duration = next_picture;
   picture startTrialPicture;
   mri_pulse = 1;
   duration = 1000;
} startTrial;

################# Spoken language Trial ################################
trial {
		all_responses = false;	           # Does not log all responses, only those during active events #
		trial_duration = 15995;
		trial_type = fixed;

	stimulus_event {
					sound music1;
					time = 0;
					duration = 15995; # 16 seconds
					response_active = true;
					}spoken_event;

} spoken_trial;

################# Music Trial ################################
trial {
		all_responses = false;
		trial_duration = 7995; # Does not log all responses, only those during active events #
		trial_type = fixed;

	stimulus_event {
					sound music1;
					time = 0;
					duration = 7995; # 8 seconds
					response_active = true;
					}music_event;

} music_trial;

################# Noise Trial ################################
trial {
		all_responses = false;	           # Does not log all responses, only those during active events #
		trial_duration = 1995;
		trial_type = fixed;

	stimulus_event {
					sound music1;
					time = 0;
					duration = 1995; # 2 seconds
					response_active = true;
					}noise_event;

} noise_trial;

################# Baseline ################################
trial {
		all_responses = false;	           # Does not log all responses, only those during active events #
		trial_type = fixed;

	stimulus_event {
					picture white_screen;
					time = 0;
					duration = 15995;
					code = "rest";
					response_active = false;
					}rest_event;

} rest_trial;

################################## START PCL ####################################

begin_pcl;

############# DECLARATIONS ##############
preset int run = 1;

int start_time = clock.time();

string subnr = logfile.subject();
logfile.set_filename(subnr + "_run" + string(run) + "_Sound_Color_Syn_Localizer_MRI.log");
output_file output = new output_file;
output.open( subnr + "_run" + string(run) + "_Sound_Color_Syn_Localizer_MRI_output.txt" );
output.print(start_time);output.print("\n");
output.print( "block\ttrialnr\tpic_trial\tsound\tresponse_button\tRT\n" );

string sound_is = "";
int isi = 0;
int j = 1;
int k1 = 1;
int k2 = 1;
int m = 1;
int c1 = 1;
int c2 = 1;
int z = 1;

string dspoken = "1";
string fspoken = "2";
string minstr = "3";
string environ = "4";
string baseline = "5";

int lastResponse = 0;
double lastRT = 0.0;

int trial_number = 1;

###############################################################################

### START OF THE TRIALS LOOPS ###

###################
sub condition1 begin # dutch_spoken

		spoken_event.set_stimulus( spoken_dutch[k1] );
		sound_is = spoken_dutch[k1].description();
		spoken_event.set_event_code(dspoken);

		spoken_trial.present();

		if response_manager.response_count() > 0
			then
				stimulus_data last = stimulus_manager.last_stimulus_data();
				lastRT = last.reaction_time_double();
				lastResponse = response_manager.last_response();
			else
				lastRT = 0.0;
				lastResponse = 0;
		end;

		output.print("dutch_spoken");output.print("\t");
		output.print(trial_number);output.print("\t");
		output.print(k1);output.print("\t");
		output.print(sound_is);output.print("\t");
		output.print(lastResponse);output.print("\t");
		output.print(lastRT);output.print("\n");

		trial_number = trial_number + 1;

		k1 = k1 + 1;
end;

###################
sub condition2 begin # dutch_foreign

		spoken_event.set_stimulus( spoken_foreign[k2] );
		sound_is = spoken_foreign[k2].description();
		spoken_event.set_event_code(fspoken);

		spoken_trial.present();

		if response_manager.response_count() > 0
			then
				stimulus_data last = stimulus_manager.last_stimulus_data();
				lastRT = last.reaction_time_double();
				lastResponse = response_manager.last_response();
			else
				lastRT = 0.0;
				lastResponse = 0;
		end;

		output.print("foreign_spoken");output.print("\t");
		output.print(trial_number);output.print("\t");
		output.print(k2);output.print("\t");
		output.print(sound_is);output.print("\t");
		output.print(lastResponse);output.print("\t");
		output.print(lastRT);output.print("\n");

		trial_number = trial_number + 1;

		k2 = k2 + 1;
end;

###################
sub condition3 begin # music

loop j = 1 until j > 2  begin;

		music_event.set_stimulus( music[c1] );
		sound_is = music[c1].description();
		music_event.set_event_code(minstr);

		music_trial.present();

		if response_manager.response_count() > 0
			then
				stimulus_data last = stimulus_manager.last_stimulus_data();
				lastRT = last.reaction_time_double();
				lastResponse = response_manager.last_response();
			else
				lastRT = 0.0;
				lastResponse = 0;
		end;

		output.print("music");output.print("\t");
		output.print(trial_number);output.print("\t");
		output.print(c1);output.print("\t");
		output.print(sound_is);output.print("\t");
		output.print(lastResponse);output.print("\t");
		output.print(lastRT);output.print("\n");

		trial_number = trial_number + 1;

		c1 = c1 + 1;
		j = j + 1;
	end;
end;

###################
sub condition4 begin # noise

noise.shuffle();

loop j = 1 until j > 8  begin;

		noise_event.set_stimulus( noise[j] );
		sound_is = noise[j].description();
		noise_event.set_event_code(environ);

		noise_trial.present();

		if response_manager.response_count() > 0
			then
				stimulus_data last = stimulus_manager.last_stimulus_data();
				lastRT = last.reaction_time_double();
				lastResponse = response_manager.last_response();
			else
				lastRT = 0.0;
				lastResponse = 0;
		end;

		output.print("noise");output.print("\t");
		output.print(trial_number);output.print("\t");
		output.print(j);output.print("\t");
		output.print(sound_is);output.print("\t");
		output.print(lastResponse);output.print("\t");
		output.print(lastRT);output.print("\n");

		trial_number = trial_number + 1;

		j = j + 1;
	end;
end;

######### Define subject conditions, counterbalancing

array <int> randomize_conditions [4][20] =
{
	{4,2,3,1,2,1,3,4,1,2,3,4,2,1,3,4,1,2,4,3},
	{1,2,4,3,2,1,3,4,1,2,4,3,1,2,3,4,3,4,2,1},
	{2,4,1,3,1,2,4,3,1,4,3,2,3,4,1,2,4,3,2,1},
	{3,2,4,1,3,1,2,4,3,2,4,1,4,1,2,3,1,2,4,3}
};

		spoken_dutch.shuffle();
		spoken_foreign.shuffle();
		music.shuffle();

		startTrial.present();

		# Begin with rest - Baseline block

		rest_event.set_event_code(baseline);
		rest_event.set_duration(17995);

		rest_event.set_stimulus( rest );
		rest_trial.present();

	loop k1 = 1 until k1 > spoken_dutch.count() begin;
	loop k2 = 1 until k2 > spoken_foreign.count() begin;
	loop c1 = 1 until c1 > 5 begin;
	# loop c2 = 1 until c2 > noise.count() begin;

		#the run number picks which of the 4 pseudo randomized condition orders
	loop z = 1 until z > 20 begin;

			if randomize_conditions[run][z] == 1
					then condition1();
					# Baseline block
					rest_event.set_event_code(baseline);
					rest_event.set_duration(15995);
					rest_event.set_stimulus( rest );
					rest_trial.present();
					z = z + 1;
			elseif randomize_conditions[run][z] == 2
					then condition2();
					# Baseline block
					rest_event.set_event_code(baseline);
					rest_event.set_stimulus( rest );
					rest_event.set_duration(15995);
					rest_trial.present();
					z = z + 1;
			elseif randomize_conditions[run][z] == 3
					then condition3();
					# Baseline block
					rest_event.set_event_code(baseline);
					rest_event.set_stimulus( rest );
					rest_event.set_duration(15995);
					rest_trial.present();
					z = z + 1;
			elseif randomize_conditions[run][z] == 4
					then condition4();
					# Baseline block
					rest_event.set_event_code(baseline);
					rest_event.set_stimulus( rest );
					rest_event.set_duration(15995);
					rest_trial.present();
					z = z + 1;
			end;

		end;
	end;
	end;
end;

int end_time = clock.time();
output.print(end_time);output.print("\n");


Temporarily disable test Java API tests that cause crash-on-exit.

The tests themselves do pass, however.  The crash is caused by some
sort of cleanup, due to someone calling a pure virtual function or
some such.

I'll work on converting these tests into C++.


INTEGRATION: CWS api01ea (1.2.34); FILE MERGED 2004/02/27 15:29:07 cn 1.2.34.1: 112363# DocumentProperties removed

-o fwk.DispatchRecorder
-o fwk.DispatchRecorderSupplier
-o fwk.Frame
-o fwk.JobExecutor
-o fwk.JobHandler
-o fwk.MailToDispatcher
-o fwk.ServiceHandler
-o fwk.SoundHandler
-o fwk.URLTransformer
-o fwl.ContentHandlerFactory
-o fwl.FilterFactory
-o fwl.FrameLoaderFactory
-o fwl.SubstituteVariables
-o fwl.TypeDetection
-o fwl.PathSettings
-o fwk.Desktop
-o fwk.ModuleManager
-o fwk.UIElementFactoryManager
-o fwk.LayoutManager
-o fwk.UIConfigurationManager
-o fwk.MenuBarFactory
-o fwk.FontSizeMenuController
-o fwk.FooterMenuController
-o fwk.FormatMenuController
-o fwk.HeaderMenuController
-o fwk.ControlMenuController
-o fwk.FontMenuController
-o fwk.ModuleUIConfigurationManagerSupplier
-o fwk.ObjectMenuController
-o fwk.ModuleUIConfigurationManager
-o fwk.PopupMenuControllerFactory

-o fwk.DispatchRecorder
-o fwk.DispatchRecorderSupplier
-o fwk.DocumentProperties
-o fwk.Frame
-o fwk.JobExecutor
-o fwk.JobHandler
-o fwk.MailToDispatcher
-o fwk.ServiceHandler
-o fwk.SoundHandler
-o fwk.URLTransformer
-o fwl.ContentHandlerFactory
-o fwl.FilterFactory
-o fwl.FrameLoaderFactory
-o fwl.SubstituteVariables
-o fwl.TypeDetection
-o fwl.PathSettings
-o fwk.Desktop
-o fwk.ModuleManager
-o fwk.UIElementFactoryManager
-o fwk.LayoutManager
-o fwk.UIConfigurationManager
-o fwk.MenuBarFactory
-o fwk.FontSizeMenuController
-o fwk.FooterMenuController
-o fwk.FormatMenuController
-o fwk.HeaderMenuController
-o fwk.ControlMenuController
-o fwk.FontMenuController
-o fwk.ModuleUIConfigurationManagerSupplier
-o fwk.ObjectMenuController
-o fwk.ModuleUIConfigurationManager
-o fwk.PopupMenuControllerFactory


Added wav file

Added wav file

[testsign,Fs,bits]=wavread("SCI/modules/sound/demos/filterTest2(anja).wav");
//[testsign,Fs,bits]=wavread("SCI/modules/sound/demos/filterTest1(H-style).wav");
testsign = testsign(1,:);
t = [1:1:length(testsign)]*1/Fs;
[LD_coeff, amplitude, frequentie] = wfir('lp',80,[750/Fs 0],'hm',[0 0]);
LD_polynoom = poly(LD_coeff, 'z', 'coeff');
LD_functie = horner(LD_polynoom, 1/%z);
LD_lineair_system = syslin('d', LD_functie);
LD_output = flts(testsign, LD_lineair_system);

plot(t, testsign)
plot(t, LD_output, 'r');

wavwrite(LD_output, 'SCI/modules/sound/demos/'+'yolo.wav');

t = [0: 0.0000625: 0.02];
N = size(t, '*');
sin_100Hz = 2*sin(2*%pi*700*t);
sin_1000Hz = 2*sin(2*%pi*1000*t);
sin_5000Hz = 2*sin(2*%pi*5000*t);
testsign = sin_100Hz + sin_1000Hz + sin_5000Hz;
[LD_coeff, amplitude, frequentie] = wfir('lp',100,[750/16000 0],'hm',[0 0]);
LD_polynoom = poly(LD_coeff, 'z', 'coeff');
LD_functie = horner(LD_polynoom, 1/%z);
LD_lineair_system = syslin('d', LD_functie);
LD_output = flts(testsign, LD_lineair_system);

Frequentie_FFT = abs(fft(testsign));
f = 16000 * (0:(N/2))/N;
n = size(f, '*');
figure;

subplot(311);
plot(f, Frequentie_FFT(1:n));
plot(frequentie*16000, amplitude*N, 'black');
subplot(312);
plot(t, LD_output, 'r');
subplot(313);
plot(t, testsign)
plot(t, LD_output, 'r');
plot(t, sin_100Hz, 'g');


INTEGRATION: CWS dba24a (1.4.130); FILE MERGED 2007/08/29 13:23:15 oj 1.4.130.1: #i69084# lock and release mutex

-o complex.dbaccess.SingleSelectQueryComposer
-o complex.dbaccess.RowSet
-o complex.dbaccess.PropertyBag
-o complex.dbaccess.Query
-o complex.dbaccess.QueryInQuery
-o complex.dbaccess.Storable


Fix typo

Fix typo

function mdaqAIScanSync(arg1, arg2, arg3)
    link_id = -1;
    result = [];

    if argn(2) == 2 then
        dio = arg1;
        edge = arg2;
    end

    if argn(2) == 3 then
        link_id = arg1;
        dio = arg2;
        edge = arg3;

        if link_id < 0 then
            error("Invalid connection ID!")
            return;
        end
    end

    if argn(2) > 3 | argn(2) < 2 then
        mprintf("Description:\n");
        mprintf("\tSynchronizes analg input conversion with digital input\n");
        mprintf("Usage:\n");
        mprintf("\tmdaqAIScanSync(linkID, dio, edge)\n");
		mprintf("\tlinkID - connection id returned by mdaqOpen() (OPTIONAL)\n");
        mprintf("\tdio - digital input pin (1-8)\n");
        mprintf("\tedge - type of edge which triggers analog input conversion\n");
        mprintf("\t\t 1 - falling edge\n");
        mprintf("\t\t 2 - rising edge\n");
        mprintf("\t\t 3 - falling or rising edge\n");
        return;
    end

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

    trigger = 1; // AI_TRIGGER
    result = [];
    result = call("sci_mlink_scan_trigger_conv",..
                    link_id, 1, "i",..
                    trigger, 2, "i",..
                    dio, 3, "i",..
                    edge, 4, "i",..
                "out",..
                    [1, 1], 5, "i");

    if result < 0 then
        if argn(2) == 2 then
            mdaqClose(link_id);
        end
        error(mdaq_error2(result), 10000 + abs(result));
    end

    if argn(2) == 5 then
            mdaqClose(link_id);
    end
endfunction

function result = mdaqAIScanSync(arg1, arg2, arg3)
    link_id = -1;
    result = [];

    if argn(2) == 2 then
        dio = arg1;
        edge = arg2;
    end

    if argn(2) == 3 then
        link_id = arg1;
        dio = arg2;
        edge = arg3;

        if link_id < 0 then
            error("Invalid connection ID!")
            return;
        end
    end

    if argn(2) > 3 | argn(2) < 2 then
        mprintf("Description:\n");
        mprintf("\tSynchronizes analg input conversion with digital input\n");
        mprintf("Usage:\n");
        mprintf("\tmdaqAIScanSync(linkID, dio, edge)\n");
		mprintf("\tlinkID - connection id returned by mdaqOpen() (OPTIONAL)\n");
        mprintf("\tdio - digital input pin (1-8)\n");
        mprintf("\tedge - type of edge which triggers analog input conversion\n");
        mprintf("\t\t 1 - falling edge\n");
        mprintf("\t\t 2 - rising edge\n");
        mprintf("\t\t 3 - falling or rising edge\n");
        return;
    end

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

    trigger = 1; // AI_TRIGGER
    result = [];
    result = call("sci_mlink_scan_trigger_conv",..
                    link_id, 1, "i",..
                    trigger, 2, "i",..
                    dio, 3, "i",..
                    edge, 4, "i",..
                "out",..
                    [1, 1], 5, "i");

    if result < 0 then
        if argn(2) == 2 then
            mdaqClose(link_id);
        end
        error(mdaq_error2(result), 10000 + abs(result));
    end

    if argn(2) == 5 then
            mdaqClose(link_id);
    end
endfunction