function fig = compiler_survey(which_screen, flag, d)
%COMPILER_SURVEY   Run the compiler survey to compare 
%                  Compiler 2.1 performance to the MATLAB interpreter.
%
%   COMPILER_SURVEY, by itself, runs the compiler survey from the
%   MATLAB command prompt.  This will assist The MathWorks in
%   improving the performance of M code both within the interpreter
%   and when using the MATLAB Compiler.  In order to use this survey,
%   you will need to provide an M file with no inputs and no outputs
%   (it can load data from a .MAT file.) that executes your algorithm.
%   The survey tool will perform timings on this M file to determine
%   the performance in the interpreter and with each of the two
%   compilers (C and C++).  At the end of the survey, you will be
%   asked to include your M source for the purpose of improving the
%   Compiler and MATLAB Interpreter.
%

% $Revision: 1.9 $  $Date: 2000/08/31 21:33:44 $
% Copyright 1984-2000 The MathWorks, Inc.

persistent myfig;

if (isempty(myfig) | ~ishandle(myfig))
    myfig = findobj( get(0,'CurrentFigure'), 'Tag', 'CompilerSurvey' );
    if (isempty( myfig) )
        myfig = [];
    end
end
if (exist('survey_settings.mat')~=2)    
    d = tempname;
    unix( ['mkdir ' d] );
    addpath(d);
    day = date;
    if (strcmp(computer,'PCWIN'))
        exe_ext = '.exe';
        zip_ext = '.zip';
    else
        exe_ext = '';
        zip_ext = '.tar';
    end
    matfiles = {};
    optfiles = {};
    save( fullfile( d, 'survey_settings'), 'day', 'd', 'exe_ext', ...
        'zip_ext', 'matfiles', 'optfiles' );
end

if (nargin < 3)
    d = load_variable_from_matfile( 'survey_settings', 'd' );
end

if (nargin < 1)
        which_screen = 0;
end

clearerr(myfig);

switch (which_screen)
    case -1
        myfig = closefig(myfig);        
    case 0
        myfig = closefig(myfig);
        myfig = get_mfilename(d);
    case 1
        myfig = detail_screen( myfig );
    case 2
        myfig = measure_performance( myfig, d );
    case 3
        myfig = survey_barchart( myfig, d, flag );
    case 4
        myfig = ask_and_bundle( myfig, d );
    case 5
        myfig = bundle(myfig, d);
    case 6
        save_send_settings( myfig, d );
    case 7
        myfig = closefig(myfig);
        myfig = get_bug_filename( d );
    case 8
        myfig = collect_bug_info( myfig, d );
    case 9
        myfig = bug_detail_screen( myfig );
    case 10
        myfig = bundle( myfig, d, 1 );
    otherwise
        error('Error: Please call the compiler_survey GUI without providing an argument');
end

if (nargout > 0)
        fig = myfig;
end

function myfig = closefig(myfig)
        if (~isempty(myfig))
                close(myfig);
                myfig = [];
        end
        
function myfig = detail_screen(fig)
myfig = fig;
fig = figure('Color',[0.8 0.8 0.8], ...
             'InvertHardcopy','off', ...
             'PaperUnits','points', ...
             'Position',[22 505 640 480], ...
             'Resize','Off', ...
             'NumberTitle', 'Off', ...
             'Name', 'Compiler Survey Details',...
             'Tag', 'CompilerSurvey' );
center(fig);
set( myfig, 'UserData', fig );
set( fig, 'UserData', myfig );
title = maketitle( fig, 'Compiler Survey Details' );

intro = static_text( fig, [0.0391 0.5125 0.925 0.31875], ...
[ 'The MathWorks is very interested in improving the performance of M '...
  'code in MATLAB and of code generated using the MATLAB Compiler.  '...
  'The intent of this compiler_survey is for us to gather some real-world M '...
  'applications to use as performance benchmarks. By completing this compiler_survey, ' ...
  'you will allow us evaluate the performance of your application  '...
  'in the interpreter, and when using the latest '...
  'version of the MATLAB Compiler that is currently under development.  ', ...
  'The compiler_survey program '...
  'will measure the performance of Compiler-generated code '...
  'in stand-alone C/C++ mode only.  '] );

intro2 = static_text( fig, [ 0.0391 0.158333333333333 0.9375 0.0666666666666667 ], ...
        ['NOTE:Before running the compiler_survey, you must have setup '...
         'the mbuild tool (using mbuild -setup) for your compiler. (see the "Chapter 4 on Standalone Applications" in the Compiler '...
         'manual.) ' ] );
set( intro2, 'ForeGroundColor', [ 1 0 0 ] );

intro3 = static_text( fig, [.0391 0.25 0.9047 0.2687], ...
[ 'In order to complete this compiler_survey you will need to provide '...
  'an M function.  This function will be used to compare the performance of '...
  'the M code in MATLAB with the performance of the compiler-generated stand-alone  '...
  'application for the same M file. ' ...  
  'Requirements for this M-file function are: ' ...
  '- it has no inputs or outputs ' ...
  '- the M-file must take longer than 1 second to run, due to clock precision limitations'...
  '- it may not include any graphics or GUI functions ', ...  
'(If your application ',...
  'completes in less than 1 second in any of the timings, we recommend.  '...,
  'adding a loop until the time is greater than 1 second in all tests.)  ',...
' For example, this function could load data from a .mat file and call ',...
  'an algorithm that you are interested in timing.    ',...
  'cannot be used because they are unavailable in stand-alone code.' ] );

ok = make_ok( fig, 'h = get(gcbf, ''UserData''); set( h, ''UserData'', 0 ); close(gcbf); figure(h);' );

set( ok, 'Position',[ 0.390625 0.0520833333333333 0.18125 ...
        0.0958333333333333 ] );



function fig = get_mfilename(d)
    fig = figure('Color',[0.8 0.8 0.8], ...
                 'InvertHardcopy','off', ...
                 'PaperUnits','points', ...
                 'Position',[22 505 640 480], ...
                 'Resize','Off', ...
                 'NumberTitle', 'Off', ...
                 'Name', 'Compiler Survey',...
                 'UserData', 0,...
                 'Tag', 'CompilerSurvey' );
    center(fig);

    hmname = uicontrol('Parent', fig, ...
                       'Units','Normalized', ...
                       'BackgroundColor',[1 1 1], ...
                       'ListboxTop',0, ...
                       'Position',[ 0.465625 0.79375 0.4703125 0.0520833333333333 ],...
                       'HorizontalAlignment','left', ...
                       'Style','edit', ...
                       'Tag','mname');

    mname = load_variable_from_matfile( 'survey_settings', 'mname' );
    if (~isempty(mname))
        set( hmname, 'String', mname );
    end

    title = maketitle( fig, 'Compiler Survey' );



                
    make_continue( fig, 'compiler_survey(2);' );
    make_cancel( fig, ...
        ['h = get(gcbf, ''UserData'');',...
         'if (h ~= 0),',... 
         'close(h);',...
         'end;',...
         'compiler_survey(-1);' ]);

    make_details( fig, ['if (get( gcbf, ''UserData'') == 0), compiler_survey(1);, ',...
                       'else, figure(get(gcbf, ''UserData'')); end'] );

    hcpp_too = make_checkbox( fig, [0.465625 0.6625 0.36875 0.05416666666666667], ...
                             'Measure C++ performance', 'cpp_too' );

    cpp_too = load_variable_from_matfile( 'survey_settings', 'cpp_too' );
    if (~isempty( cpp_too))
        set( hcpp_too, 'Value', cpp_too );
    end

    clear_old = make_checkbox( fig, [ 0.4640625 0.597916666666667 0.36875 0.0541666666666667 ], ...
                               'Clear results', 'clear_old' );

    [path,basename,ext,ver] = fileparts( mname );
    matname = fullfile( d, [basename '.mat']);
    
    if (exist( matname ) ~= 2)
        M_time = [];
    else
        M_time = load_variable_from_matfile( matname, 'M_time' );
    end

    if (isempty(M_time))
        set( clear_old, 'Enable', 'off' );
    else
        set( clear_old, 'Enable', 'on' );
    end

    prompt = static_text( fig, [ 0.075 0.7875 0.359375 0.05625 ], ...
                          '1. Enter the name of an M file to test:' );
    static_text( fig, [0.075 0.7229166666666667 0.359375 0.05625], ...
                 '2. Clear any partial results (if desired):' );
    static_text( fig, [0.075 0.6625 0.359375 0.05625], ...
                 '3. Options:' );
    static_text( fig, [0.075 0.4166666666666667 0.859375 0.05208333333333334],  ...
                 '4. This survey measures and compares the performance of (each test is run 3 times):' );
    static_text( fig, [0.1171875 0.3645833333333333 0.8203125 0.05208333333333334], ...
                 '- The M code running in the interpreter' );
    static_text( fig, [0.1171875 0.3125 0.6640625 0.05625], ...
                 '- The C code produced by the MATLAB Compiler 2.1' );
    static_text( fig, [0.1171875 0.2604166666666667 0.859375 0.05625], ...
                '- The C++ code produced by the MATLAB Compiler 2.1 ("Measure C++ performance")' );

    
function fig = measure_performance( fig, d )

    [mname,omname,e] = get_mname( fig, d, 0);

    if (e ~= 0)
        return;
    end

    w = waitbar( 0, 'Initializing...' );
    err = 0;

    try
        err = measure_performance_werr( fig, d, mname, w, ~strcmp(mname, omname));
    catch
        err=2;
    end

    close(w);
    if (err ~= 0)
        if (err == 2)
            seterr( fig, lasterr );
        end
    else
        disp('Performance measurement complete' );        
        compiler_survey(3,0);
    end

function err = measure_performance_werr( fig, d, mname, w, mbad )
        
    err = 0;
    runs_per_test = 3;
    tr = 0;
    sts_text = findall( w, 'Type', 'text' );

    if (length(sts_text) > 1 | isempty(sts_text))
        seterr( fig, 'Error: Error starting the waitbar' );
        err = 1;
        return
    end


    matname = fullfile( d, [ mname '.mat' ] );

    hclear_old = findobj( fig, 'Tag', 'clear_old' );
    clear_old = 0;
    if (~isempty( hclear_old ) )
        clear_old = get( hclear_old, 'Value' );
    end
        
    if (clear_old)
        disp( 'Clearing old results' );
        delete(matname );
    end

    ntests = 1;
    cp_too = 0;

    hcpp_too = findobj( fig, 'Tag', 'cpp_too' );

    if (~isempty( hcpp_too) )        
        cpp_too = get( hcpp_too, 'Value' );
    end

    save( '-append', fullfile( d, 'survey_settings'), 'cpp_too');

    if (cpp_too)
        disp( 'Computing the performance numbers for C++ as well as C' );
        ntests = ntests*2;
    end
    ntests = ntests+1;

    if (exist(matname) ~= 2)    
        day = date;
        save(matname, 'day' );        
    end
    omname = load_variable_from_matfile( matname, 'mname' );
    save( '-append', matname, 'mname' );

    M_time = load_variable_from_matfile( matname, 'M_time' );
    pct = 0;
    top = 1/ntests;

    disp( 'Measuring the M performance' );
    set( sts_text, 'String', 'Caching the M code...' );
    drawnow;        

    if (isempty( M_time) | mbad == 1)
        before = length( get(0, 'Children') );
        matfiles = {};
        save( '-append', fullfile( d, 'survey_settings') , 'matfiles' );

        mccdir = which('mcc');
        [path,basename,ext,ver] = fileparts( mccdir );

        addpath( fullfile( path, 'load_mat' ) );  % instrument load to save the .mat file names

        t = measure_m_file( fig, mname );    % throw 1 away for caching
        
        rmpath( fullfile( path, 'load_mat' ) );        

        after = length( get(0, 'Children' ) );

        if (t == 0 & before ~= after)
            err = 1;
            return;
        end
        if (before ~= after)
            seterr( fig, ['Handle Graphics applications cannot be compiled.  ',... 
                        'Please choose an M-file that does not use Handle Graphics.'] );
            err = 1;
            return;
        end
        pct = pct + top / (runs_per_test+1);
        waitbar( pct, w );
        matfiles = load_variable_from_matfile( 'survey_settings', 'matfiles' );
        if (~isempty(matfiles))
            for i = 1:length(matfiles)
                [path, name, ext] = fileparts( matfiles{i} );
                
                str = [ 'copy ' matfiles{i} ' ' fullfile( d, [name ext] ) ];
                disp(str);
                dos(str);
            end
        end
    end

    if (isempty( M_time))

        for i = 1:runs_per_test
            set( sts_text, 'String', [ 'Measuring M performance(' num2str( i ) ')...' ] );
            drawnow;
            M_time(i) = measure_m_file( fig, mname );
            if (~M_time(i)) 
                err = 1;
                return;
            end
            pct = pct + top / (runs_per_test+1);
            waitbar(pct, w );
        end
        disp( 'Saving the results of the M performance' );
        save( matname, '-append', 'M_time' );
        save( fullfile( d, 'survey_settings'), '-append', 'M_time' );
    end
    
    tr = tr+1;
    pct = tr*top;
    waitbar( pct, w );
    drawnow;
    fprintf( 1, 'Average M time = %5.3f seconds\n', mean(M_time) );
    
    C20_time = load_variable_from_matfile( matname, 'C20_time' );
    set( sts_text, 'String', 'Compiling using C compiler 2.1' );
    drawnow;
    if (isempty( C20_time ))
        C20_timing = 0;
        save( matname, '-append', 'C20_timing' );
        if (M_compileC20( fig, d, mname, '' ))        
            err = 1;
            return;
        else
            pct = pct + top / (runs_per_test+1);
            waitbar( pct, w );
            for i =1:runs_per_test
                set( sts_text, 'String', [ 'Measuring C 2.1 performance(' num2str( i ) ')...' ] );
                drawnow;
                C20_time(i) = measure_c20_file( fig, d, mname );
                if (~C20_time(i))
                    seterr( fig, 'Zero time returned from running compiler 2.1 test, check for compilation errors' );
                    err = 1;
                    return;
                end                    
                pct = pct +  top / (runs_per_test+1);
                waitbar(pct, w );
            end
            disp( 'Saving the results of the C 2.1 performance' );
            save( matname, '-append', 'C20_time' );
        end
    end
    
    tr = tr+1;
    pct = tr * top;
    waitbar( pct, w );
    drawnow;
    fprintf( 1, 'Average C 2.1 time = %5.3f seconds\n', mean(C20_time) );


    if (cpp_too)

        CPP20_time = load_variable_from_matfile( matname, 'CPP20_time' );
        set( sts_text, 'String', 'Compiling using C++ compiler 2.1' );
        drawnow;
        if (isempty( CPP20_time ))
            CPP20_timing = 0;
            save( matname, '-append', 'CPP20_timing' );
            if (M_compileCPP20( fig, d, mname, '' ))        
                err = 1;
                return;
            else
                pct = pct + top / (runs_per_test+1);
                waitbar( pct, w );
                for i =1:runs_per_test
                    set( sts_text, 'String', [ 'Measuring CPP 2.1 performance(' num2str( i ) ')...' ] );
                    drawnow;
                    CPP20_time(i) = measure_cpp20_file( fig, d, mname );
                    if (~CPP20_time(i))
                        err = 1;
                        return;
                    end                    
                    pct = pct +  top / (runs_per_test+1);
                    waitbar(pct, w );
                end
                disp( 'Saving the results of the C++ 2.1 performance' );
                save( matname, '-append', 'CPP20_time' );
            end
        end
        tr = tr+1;
        pct = tr * top;
        waitbar( pct, w );
        drawnow;
        fprintf( 1, 'Average C++ 2.1 time = %5.3f seconds\n', mean(CPP20_time) );
    end


function [fig, ok, cancel, title, herr, efig ] = seterr( fig, err, cancel, bug_report )        
    if (nargin < 3 )
        cancel = 1;
    end
    if (nargin < 4)
        bug_report = 0;
    end
    if (bug_report == 1)
        kind = 'Bug Report';
    else
        kind = 'Survey';
    end

    hebar = findobj( fig, 'Tag', 'errorbar' );
    if (~isempty( hebar ))
        set( hebar, 'String', err );
    else
        efig = figure('Color',[0.8 0.8 0.8], ...
             'InvertHardcopy','off', ...
             'PaperUnits','points', ...
             'Position',[702 659 475 198], ...
             'Resize','Off', ...
             'Tag', 'CompilerSurveyError',...
             'NumberTitle', 'Off', ...
             'Name', ['Compiler ' kind ' Error' ], ...
             'WindowStyle', 'modal');
        center( efig );
        title = maketitle( efig, ['Compiler ' kind ' Error' ]);
        if (strcmp(computer,'PCWIN'))
                fsize = 14;
        else
                fsize = 16;
        end
        set( title, 'ForegroundColor',[1 0 0], 'FontSize', fsize * font_scale_factor );
        herr = static_text( efig, [ 0.0968421052631579 0.338383838383838 0.831578947368421 0.474747474747475 ],...
                            err );
        set( herr, 'ForeGroundColor', [1 0 0 ] );

        ok = make_ok( efig, 'close(gcf);' );
        set( ok, 'Position', [0.2631578947368421 0.1262626262626263 0.1894736842105263 0.1919191919191919] );
        if (cancel == 0)
            set( ok, 'Position', [0.42105263157895 0.1262626262626263 0.1894736842105263 0.1919191919191919 ] );
        else
            cancel = make_cancel( efig, 'close(gcf); compiler_survey(-1);' );
            set( cancel, 'Position', [0.57894736842105   0.12626262626263   0.18526315789474   0.19696969696970] );
        end
        fig = efig;
    end
    
    
function clearerr( fig )
    hebar = findobj( fig, 'Tag', 'errorbar' );
    if (isempty( hebar ))
        return;
    end
    set( hebar, 'String', '' );
        
function y = load_variable_from_matfile( matname, varname )
    y = [];
    vars = whos( '-file', matname );
    for (i=1:length( vars ))
        if (strcmp( vars(i).name, varname ))
            st = builtin( 'load', matname, varname );
            cl = struct2cell(st);
            y = cl{1};
        end
    end
    
function y= measure_m_file( fig, name )
    tstart = clock;
    err =0;

    try 
        feval( name );
    catch
        err = 1;
    end

    if (err==1)
        seterr( fig, lasterr );
        y = 0;
        return
    end
    y = etime(clock,tstart);
    fprintf( 1, 'Finished run time = %5.3f seconds\n', y );
    if (y == 0)
        seterr( fig, [ 'No test can take 0 time.  Please add for loops into the M code to make it take longer than 1 second.  Running "' name '.m"' ] );
        y = 0;
        return;
    end

function fout = waitbar(x,whichbar)
%WAITBAR Display wait bar.
%   H = WAITBAR(X,'title') creates and displays a wait bar of 
%   fractional length X.  The handle to the waitbar figure is
%   returned in H.  X should be between 0 and 1.
%
%   WAITBAR(X,H) will set the length of the bar in waitbar H
%   to the fractional length X.
%
%   WAITBAR(X) will set the length of the bar in the most recently
%   created waitbar window to the fractional length X.
%
%   WAITBAR is typically used inside a FOR loop that performs a 
%   lengthy computation.  A sample usage is shown below:
%
%       h = waitbar(0,'Please wait...');
%       for i=1:100,
%           % computation here %
%           waitbar(i/100,h)
%       end
%       close(h)

%   Clay M. Thompson 11-9-92


if nargin==2 & ischar(whichbar)
   type=2; %we are initializing
   name=whichbar;
elseif nargin==2 & isnumeric(whichbar)
   type=1; %we are updating, given a handle
   f=whichbar;
elseif nargin==1
   f = findobj(allchild(0),'flat','Tag','TMWWaitbar');
   
   if isempty(f)
      type=2;
      name='Waitbar';
   else
      type=1;
      f=f(1);
   end   
elseif nargin==2
   error('Two-argument syntax requires WAITBAR(X,''title'') or WAITBAR(X,H)')
else
   error('Input arguments not valid.');
end

x = max(0,min(100*x,100));

switch type
case 1,  % waitbar(x)    update
   p = findobj(f,'Type','patch');
   l = findobj(f,'Type','line');
   if isempty(f) | isempty(p) | isempty(l), 
      error('Couldn''t find waitbar handles.'); 
   end
   xpatch = get(p,'XData');
   %replace 0 with xpatch(2)
   xpatch = [0 x x 0];
   set(p,'XData',xpatch')
   xline = get(l,'XData');
   set(l,'XData',xline);

case 2,  % waitbar(x,name)  initialize

   pos = get(0,'ScreenSize');
   pointsPerPixel = 72/get(0,'ScreenPixelsPerInch');
   
   if (strcmp(computer,'PCWIN'))
        pointsPerPixel = pointsPerPixel * 1.5;
   end
   width = 360 * pointsPerPixel;
   height = 75 * pointsPerPixel;
   pos = [pos(3)/2-width/2 pos(4)/2-height/2 width height];

   f = figure(...
           'Position', pos, ...
           'CreateFcn','', ...
           'NumberTitle','off', ...
           'IntegerHandle','off', ...
           'Tag','TMWWaitbar', ...
           'NumberTitle', 'Off', ...
           'MenuBar', 'None',...
           'Name', 'Compiler Survey Waitbar',...
           'DoubleBuffer','on');
       
   colormap([]);
   
   h = axes('XLim',[0 100],'YLim',[0 1]);
   title(name);
   set(h, ...
           'Box','on', ...
           'Position',[.05 .3 .9 .2],...
           'XTickMode','manual',...
           'YTickMode','manual',...
           'XTick',[],...
           'YTick',[],...
           'XTickLabelMode','manual',...
           'XTickLabel',[],...
           'YTickLabelMode','manual',...
           'YTickLabel',[]);

   xpatch = [0 x x 0];
   ypatch = [0 0 1 1];
   xline = [100 0 0 100 100];
   yline = [0 0 1 1 0];
   p = patch(xpatch,ypatch,'r','EdgeColor','r');
   l = line(xline,yline);
   set(l,'Color',get(gca,'XColor'));

   set(f,'HandleVisibility','callback');
   
end  % case

if nargout==1,
  fout = f;
end
center(f);


function y = measure_check(fig, y, exe)

    exe_ext = load_variable_from_matfile( 'survey_settings', 'exe_ext' );
    if (isempty(y))
        seterr( fig, [ 'Unable to run the executable "' exe ...
                exe_ext '"' ]  );
        y = 0;
        return;
    end
    if (y == 0)
        seterr( fig, [ 'No test can take 0 time.  Please add for loops into the M code to make it take longer than 1 second.  Running "' ...
                exe exe_ext '"' ] );
        y = 0;
        return;
    end
        

function s = M_compileC20( fig, d, name, options )
        
    s = 0;
    newm = fullfile( d, ['mw20_' name '.m' ]);
    fp = fopen( newm, 'w' );
    fprintf( fp, 'function %s\n', ['mw20_' name ] );
    fprintf( fp, '\tdisp(''Starting to run'' );\n\n\t' );
    fprintf( fp, 'tstart = clock;\n\n\t' );
    fprintf( fp, '%s;\n', name );
    fprintf( fp, '\n\tC20_timing = etime(clock,tstart);\n\n\t' );
    fprintf( fp, '%s\n\n\t', 'fprintf( 1, ''Finished run time = %5.3f seconds\n'', C20_timing );' );
    fprintf( fp, 'fn = ''%s'';\n\t', fullfile( d, [ name '.mat' ] ));    
    fprintf( fp, 'save( fn, ''-append'', ''C20_timing'' );\n' );
    fclose( fp );

    if (nargin < 3)
        options = '';
    end
    exe_ext = load_variable_from_matfile( 'survey_settings', 'exe_ext' );
    exename = fullfile( d, [name 'C20' exe_ext] );

    if (exist( exename ) == 2)
        delete( exename );
    end
    opt = [ '-vmh' options ];
    s = 0;
    try
        str = [ 'mcc -V2.0 ' opt ' -d' d ' mw20_' name ' -o ' ...
                name 'C20' ' -O all' ];
        disp(str);
        mcc( '-V2.0', opt, '-d', d, ['mw20_', name], '-o', [name ...
                    'C20'], '-O', 'all' );
    catch
        disp(lasterr);
        s = 1;
    end
    if (s ~= 0 | exist( exename ) ~= 2)
        disp('Unable to produce executable' );
        seterr(fig, 'Unable to compile the file.  Please see the command window for details.' );
        s = 1;
    end
    
    
function y = measure_c20_file( fig, d, name )
    exe = fullfile( d, [name 'C20'] );
    commands = { exe };
    s = run_commands(d, commands);
    if (s)
        exe_ext = load_variable_from_matfile( 'survey_settings', 'exe_ext' );
        seterr( fig, [ 'Unable to run the executable "' exe ...
                exe_ext '"' ]  );
        y = 0;
        return
    end
    y = load_variable_from_matfile( name, 'C20_timing' );
    y = measure_check(fig, y, exe);

function s = M_compileCPP20( fig, d, name, options )
    cpp20path = fullfile( d, 'c20path' );

    s = 0;
    newm = fullfile( d, ['mw20_' name '.m' ]);
    fp = fopen( newm, 'w' );
    fprintf( fp, 'function %s\n', ['mw20_' name ] );
    fprintf( fp, '\tdisp(''Starting to run'' );\n\n\t' );
    fprintf( fp, 'tstart = clock;\n\n\t' );
    fprintf( fp, '%s;\n', name );
    fprintf( fp, '\n\tCPP20_timing = etime(clock,tstart);\n\n\t' );
    fprintf( fp, '%s\n\n\t', 'fprintf( 1, ''Finished run time = %5.3f seconds\n'', CPP20_timing );' );
    fprintf( fp, 'fn = ''%s'';\n\t', fullfile( d, [ name '.mat' ] ));    
    fprintf( fp, 'save( fn, ''-append'', ''CPP20_timing'' );\n' );
    fclose( fp );

    exe_ext = load_variable_from_matfile( 'survey_settings', 'exe_ext' );
    exename = fullfile( d, [ name 'CPP20' exe_ext ] );

    if (exist( exename ) == 2)
        delete( exename );
    end
    if (nargin < 3)
        options = '';
    end

    opt = [ '-vph' options ];

    s = 0;
    try
        mcc( '-V2.0', opt, '-d', d, ['mw20_', name], '-o', [ name 'CPP20' ] );
    catch
        s = 1;
    end

    if (s ~= 0 | exist( exename ) ~= 2)        
        seterr(fig, 'Unable to compile the file.  Please see the command window for details.' );
        s = 1;
    end
    
    
function y = measure_cpp20_file( fig, d, name )
    exe = fullfile( d, [name 'CPP20']);
    commands = { exe };
    s = run_commands( d, commands );
    if (s)
        exe_ext = load_variable_from_matfile( 'survey_settings', 'exe_ext' );
        seterr( fig, [ 'Unable to run the executable "' exe ...
                exe_ext '"' ] );
        y = 0;
        return
    end
    y = load_variable_from_matfile( name, 'CPP20_timing' );
    y = measure_check(fig, y, exe);


function center(h)

    pos = get(h,'Position' );
    screen_size = get(0, 'ScreenSize' );
    pos(1) = (screen_size(3)-pos(3))/2;
    pos(2) = (screen_size(4)-pos(4))/2;

    set( h, 'Position', pos );
    
function fig = survey_barchart( fig, d, ltflag )

    mname = load_variable_from_matfile( 'survey_settings', 'mname' );
    [path,mname,ext,ver] = fileparts( mname );
    cpp_too = load_variable_from_matfile( 'survey_settings', 'cpp_too' );

    if (isempty(mname) | isempty(cpp_too))
        return;
    end

    
    M_time = load_variable_from_matfile( mname, 'M_time' );
    C20_time = load_variable_from_matfile( mname, 'C20_time' );
    CPP20_time = load_variable_from_matfile( mname, 'CPP20_time' );

    if (isempty(M_time) | isempty(C20_time) ...
        | (cpp_too & (isempty(CPP20_time))))
        seterr( fig, 'Internal Error: measurement .mat file is empty' )
        return;
    end

    barvect = [ mean(M_time) mean(C20_time) ];    
    
    if (cpp_too)
        barvect = [ barvect mean(CPP20_time) ];
    end

    if (min(barvect)<1 & ~ltflag)
        [efig, ok, cancel, htitle] = seterr( fig, ['Warning: Some of the tests took less than 1 second ',...
                'to run.  Due to clock granularity, we recommend '...
                'adding a for loop into the M file to bring the time up to 1 second in all tests.  ',...
                'The shortest test averaged ' sprintf( '%4.3f', min(barvect) ) '  seconds.  ', ...
                'Press Ok to go back and re-run the tests, press Continue to examine the results.' ] );                
        set( htitle, 'String', 'Compiler Survey Warning' );
        set( ok, 'Position', [ 0.105263157894737 0.126262626262626 0.187368421052632 0.191919191919192 ] );
        set( cancel, 'Position', [ 0.631578947368421 0.126262626262626 0.187368421052632 0.196969696969697 ] );
        cont = make_continue( efig, 'close(gcf); compiler_survey(3,1);' );
        set( cont, 'Position', [ 0.368421052631579 0.126262626262626 0.189473684210526 0.191919191919192 ] );
        return;
    end
    close(fig);
    
    
    fig = figure('Color',[0.8 0.8 0.8], ...
                 'InvertHardcopy','off', ...
                 'PaperUnits','points', ...
                 'Position',[22 505 640 480], ...
                 'NumberTitle', 'Off', ...
                 'Name', 'Compiler Survey Results',...
                 'Tag', 'CompilerSurvey' );
    center(fig);
    colormap(cool);

    htitle = maketitle( fig, 'Compiler Survey Results' );

    bar_axis = axes('Parent',fig, ...
                    'Units','normalized', ...
                    'CameraUpVector',[0 1 0], ...
                    'Color',[1 1 1], ...
                    'position',[ 0.0921875 0.204166666666667 0.828125 0.466666666666667 ],...
                    'Tag','bar_axis', ...
                    'XColor',[0 0 0], ...
                    'YColor',[0 0 0], ...
                    'ZColor',[0 0 0]);

    

    ibarvect = barvect;
    barvect = barvect ./ barvect(1);
    barvect = 1 ./ barvect;

    barlab = { 'M', 'C 2.1', 'C++ 2.1' };
        
    barlab = barlab( 1:length(barvect) );

    [barvect,k] = sort( barvect );

    barlab = barlab(k);

    disp( barlab );
    disp( barvect );
    axes( bar_axis );

    mycolors = 'ymcrgbk';

    htitle = title( 'Normalized performance (interpreter=1.0)' );
    set( htitle, 'FontUnits', 'points', 'FontSize', 12 * font_scale_factor );
    
    hold on;
    for i = 1:length(barvect)
        hbar = barh( i, barvect(i), mycolors(i) );
        set(hbar, 'FaceColor', 'Flat' );
        set( hbar, 'CData',  barvect(i));
    end
    hold off;

    axis([0 max(barvect)+.05*max(barvect) 0 length(barvect)+1]);
        
    set(bar_axis,'ytick',1:length(barvect),'yticklabel',barlab)
    set( bar_axis, 'Xgrid', 'on' );

    tend = floor(max(barvect)+1);
    step = floor(max(barvect)/20)+1;
    start = 1;
    xtick = start: step: tend;
    while (length( xtick ) < 10)
        step = step / 2;
        start = start/2;
        xtick = start: step: tend;
    end
        
    set( bar_axis, 'xtick', xtick);
        
    explain = static_text( fig, [ 0.040625 0.729166666666667 0.9484375 0.127083333333333 ], ...
        [ 'The bar chart below displays the results of this compiler_survey on your M file.  ',...
          'It displays the normalized performance (where M code = 1.0) of the code in descending order.  ',...
          'In your case, for example, ' barlab{length(barvect)} ' was the fastest and was ' ,...
          sprintf( '%5.3f', barvect(end) ) ' times faster than the M code.',...
        ]);

    make_ccb(fig, 'compiler_survey(0);', 'compiler_survey(4);', 'compiler_survey(-1)' );



function fig = ask_and_bundle(fig, d, bug_report)
    if (nargin < 3)
        bug_report = 0;
    end

    closefig( fig );
    if (bug_report == 1)
        wname = 'Complete Compiler Bug Report';
        wprompt = [ 'We will make every effort to correct this problem and to contact you with a resolution as soon as is possible. '...
                    'Thanks for taking the time to help us make the MATLAB Compiler a better product!' ];
        wsend = 'Send M-Code with the bug report';
    else
        wname = 'Complete Compiler Survey';
        wprompt = [ 'Thanks for taking the time to complete this compiler_survey.  The next step is to send the results of the compiler_survey ',...
                    'back to The MathWorks.  You will include the raw data used to produce the graph that you just saw. '...
                    'We ask that you include the M example code that you used in the compiler_survey.  This M '...
                    'code will be used specifically to improve the performance of the M interpreter and the MATLAB Compiler products ',...
                    'and for no other purpose.  Thanks again!' ];
        wsend = 'Send M-Code for future performance improvements';
    end

    fig = figure('Color',[0.8 0.8 0.8], ...
                 'InvertHardcopy','off', ...
                 'PaperUnits','points', ...
                 'Position',[22 505 640 480], ...
                 'Resize','Off', ...
                 'NumberTitle', 'Off', ...
                 'Name', wname,...
                 'Tag', 'CompilerSurvey' );
    center(fig);
    htitle = maketitle( fig, wname );

exit_interview = static_text( fig, [ 0.0390625 0.685416666666667 0.9078125 0.179166666666667 ], wprompt );

prompt1 = static_text( fig, [ 0.040625 0.597916666666667 0.2796875 0.0583333333333333 ],...
                       '1. Send the M-code?' );

hmcode = make_checkbox( fig, [ 0.3453125 0.62 0.571875 0.0520833333333333 ], ...
                        wsend, 'mcode' );
mcode = load_variable_from_matfile( 'survey_settings', 'mcode' );
if (isempty(mcode))
        mcode = 1;
end

set( hmcode, 'Value', mcode );

prompt2 = static_text( fig, [ 0.040625 0.522916666666667 0.2796875 0.0583333333333333 ], ...
                       '2. Your Name:' );

    hname = uicontrol('Parent', fig, ...
                       'Units','Normalized', ...
                       'BackgroundColor',[1 1 1], ...
                       'ListboxTop',0, ...
                       'Position',[ 0.346875 0.533333333333333 0.54375 0.0520833333333333 ], ...
                       'HorizontalAlignment','left', ...
                       'Style','edit', ...
                       'Tag','name');
    name = load_variable_from_matfile( 'survey_settings', 'name' );
    if (~isempty(name))
        set( hname, 'String', name );
    end

prompt3 = static_text( fig, [ 0.040625 0.425 0.2984375 0.0666666666666667 ], ...
                       '3. MATLAB Access code:' );
    haccess = uicontrol('Parent', fig, ...
                       'Units','Normalized', ...
                       'BackgroundColor',[1 1 1], ...
                       'ListboxTop',0, ...
                       'Position',[ 0.3484375 0.44375 0.334375 0.0520833333333333 ], ...
                       'HorizontalAlignment','left', ...
                       'Style','edit', ...
                       'Tag','access');
    access = load_variable_from_matfile( 'survey_settings', 'access' );
    if (~isempty(access))
        set( haccess, 'String', access );
    end

prompt4 = static_text( fig, [ 0.040625 0.305 0.2984375 0.0666666666666667 ], ...
                       '4. Send the results:' );

sendframe = uicontrol('Parent',fig, ...
	'Units','normalized', ...
        'BackgroundColor',[0.8 0.8 0.8], ...
	'ListboxTop',0, ...
	'Position',[ 0.3515625 0.20625 0.54375 0.1625 ], ...
	'Style','frame', ...
	'Tag','sendframe');

send_ftp = uicontrol('Parent',fig, ...
                     'Units','normalized', ...
                     'ListboxTop',0, ...
                     'BackgroundColor',[0.8 0.8 0.8], ...
                     'Position',[ 0.3640625 0.289583333333333 0.5078125 0.0708333333333333 ], ...
                     'Style','radiobutton', ...
                     'String', 'Zip/Tar the results and send them via FTP',...
                     'HorizontalAlignment','Left',...
                     'Tag','send_ftp');
send_zip_only = uicontrol('Parent',fig, ...
        	'Units','normalized', ...
                'ListboxTop',0, ...
                'BackgroundColor',[0.8 0.8 0.8], ...
                'Position',[ 0.3640625 0.220833333333333 0.5078125 0.0708333333333333 ], ...
                'Style','radiobutton', ...
                'String', 'Zip/Tar the results only (please send them later)',...
                'HorizontalAlignment','Left',...
                'Tag','send_zip_only');



err =0;
try 
        make_rb_group( sendframe, send_ftp, send_zip_only );
catch
        err=2;
end
if (err ~= 0)
        seterr( fig, lasterr, 1, bug_report );
        return;
end
flag = load_variable_from_matfile( 'survey_settings', 'flag' );
if (~isempty(flag))
        hvalue = get( sendframe, 'UserData' );
        set( hvalue(3-flag), 'Value', get(hvalue(3-flag), 'Min' ));
        set( hvalue(flag), 'Value', get(hvalue(flag), 'Max' ));
        set( sendframe, 'Value', flag );
end

    if (bug_report == 1)
        make_ccb( fig, 'compiler_survey(6);compiler_survey(7);', 'compiler_survey(10);', 'compiler_survey(-1);' );
    else
        make_ccb( fig, 'compiler_survey(6);compiler_survey(3,1);', 'compiler_survey(5);', 'compiler_survey(-1);' );
    end


function fig = bundle(fig,d,bug_report)

    if (nargin <3)
        bug_report = 0;
    end
    [name,access,flag,mcode] = save_send_settings(fig,d);
    if (isempty(name))
        seterr( fig, 'Error: Please fill in your name',1, bug_report );
        return
    end
    if (isempty(access))
        seterr( fig, 'Error: Please enter an access code or "None" if you do not have one',1 ,bug_report );
        return
    end

    mname = load_variable_from_matfile( 'survey_settings', 'mname' );
    [path,mname,ext,ver] = fileparts( mname );
    lic = license;
    [mver, mdate] = version;
    comp = computer;
    filename = fullfile( d, [mname '.mat'] );
    if (exist( filename ) == 2)
        save('-append',fullfile( d, mname),'lic', 'mver','mdate','name','access','comp');
    else
        save(fullfile( d, mname),'lic', 'mver','mdate','name','access','comp');
    end
    
    zip_ext = load_variable_from_matfile( 'survey_settings', ...
        'zip_ext' );
    
    zip = [ tempname '_' mname zip_ext ];

    [path,basename,ext,ver] = fileparts( zip );
    if (flag == 1)
        zip = fullfile( d, [basename ext] );
    else
        zip = [basename ext];
    end
    [path,basename,ext,ver] = fileparts( zip );

    if (exist(zip) == 2)
        delete(zip);
    end

    if (strcmp(computer, 'PCWIN'))
        zipcmdfn = @pcwin_zip;        
    else
        zipcmdfn = @unix_tar;        
    end

	close all;
    fig = [];

    deps = {};
    matfiles = {};

    if (mcode)
        deps = depfun( mname );
        matfiles = load_variable_from_matfile( 'survey_settings', 'matfiles' );
    end

    optfiles = {};
    if (strcmp(computer, 'PCWIN'))
        optfile = 'compopts.bat';
        if (exist(optfile) ~= 2)
            optfile = fullfile( prefdir, 'compopts.bat' );
            if (exist( optfile ) ~= 2 )
                optfile = fullfile( matlabroot, 'bin', 'win32', 'compopts.bat' );
                if (exist( optfile ) ~= 2 )
                    seterr( fig, 'Internal Error: Cannot identify compiler options file currently in use.',1, bug_report );
                end                
            end
        end        
        optfiles = { optfile };
    end
                 
    deps = { filename deps{:} matfiles{:} optfiles{:} };
    for i = 1:length(deps)
        str = feval( zipcmdfn, fig, i ~= 1, zip, deps{i} ); 
        disp(str);
        res = dos( str );
        % Intentionally ignore the return result from ZIP
    end

    if (flag == 1)
        ftp_script = fullfile( d, 'ftp_script.txt' );
        fp = fopen( ftp_script, 'w' );
        fprintf( fp, 'open ftp.mathworks.com\n');
        if (bug_report == 1)
            fprintf( fp, 'user anonymous compiler_bugs@mathworks.com\n' );
            fprintf( fp, 'cd incoming/compiler_bugs\n' );           
        else
            fprintf( fp, 'user anonymous compiler_survey@mathworks.com\n' );
            fprintf( fp, 'cd incoming/compiler_survey\n' );
        end
        
        fprintf( fp, 'binary\n' );
        fprintf( fp, 'lcd %s\n', path  );
        fprintf( fp, 'put %s%s\n', basename, ext );
        fprintf( fp, 'quit\n' );
        fclose(fp);

        if (strcmp( computer, 'PCWIN'))
            str = ['ftp -n -s:' ftp_script ];
        else
            str = ['ftp -n -v < ' ftp_script ];
        end
        
        disp(str);
        res = dos(str);
        if (res)
            seterr( fig, 'Unable to FTP the results, try another option',1,bug_report );
            return;
        end

        delete(ftp_script);
        delete( zip );
        if (bug_report == 1)
            [fig, ok, cancel,title, herr,efig] = seterr( fig, ['Thanks for completing this bug report  ',...
                                         'The Zip file has been successfully sent. ' ], 0, bug_report );
        else
            [fig, ok, cancel,title, herr,efig] = seterr( fig, ['Thanks for completing the compiler survey!  ',...
                                         'The Zip file has been successfully sent. ' ], 0, bug_report );
        end
    else
        disp( [ 'NOTE: Please send the file "' zip '" to the MathWorks at compiler_survey@mathworks.com' ] );
        if (bug_report == 1)
            [fig, ok, cancel,title,herr,efig] = seterr( fig, ['Thanks for completing this compiler bug report.  Please attach ' zip ,...
                      ' and mail to compiler_bugs@mathworks.com. ' ],0, bug_report );        
        else            
            [fig, ok, cancel,title,herr,efig] = seterr( fig, ['Thanks for completing the compiler survey!  Please attach ' zip ,...
                      ' and mail to compiler_survey@mathworks.com. ' ],0, bug_report );        
        end
    end

    if (bug_report == 1)
        set( efig, 'Name', 'Compiler Bug Report' );
        set( title, 'ForegroundColor',[0 0 0.627450980392157], 'String', 'Compiler Bug Report' );
    else
        set( efig, 'Name', 'Compiler Survey Results' );
        set( title, 'ForegroundColor',[0 0 0.627450980392157], 'String', 'Compiler Survey Results' );
    end
    set( herr,  'ForegroundColor', [ 0 0 0 ] );

    disp( 'Done, Thank you for completing the compiler compiler_survey.' );

    disp(['Removing ' d '.' ] );
    if (strcmp( computer, 'PCWIN' ))
       dos( ['del /q ' fullfile( d, 'bin', '*') ]);
       dos( ['rmdir ' fullfile(d,'bin')] );       
       dos( ['del /q ' fullfile( d, '*' ) ] );
       dos( ['rmdir ' d] );
    else
       unix( ['rm -rf ' d] );
    end

function str = find_set( txt, varname )
    
    i = findstr( varname, txt );
    i = i(1);
    
    oi = i;
    while (i > 0 & txt(i) >= 32)
        i = i-1;
    end
    while (oi < length(txt) & txt(oi) >=32)
        oi = oi+1;
    end
    str = txt(i+1:oi-1);

function make_ccb(fig, back_call, continue_call, cancel_call )

makecc( fig, continue_call, cancel_call );

make_back( fig, back_call );

function [cont, cancel ] = makecc( fig, continue_call, cancel_call )
        cont = make_continue( fig, continue_call );
        cancel = make_cancel( fig, cancel_call );

function title = maketitle( fig, string )
        
        if (strcmp(computer,'PCWIN'))
            fontname = 'Times New Roman';
        else
            fontname = 'Times';
        end
        
        title = uicontrol('Parent',fig, ...
             'BackgroundColor',[0.8 0.8 0.8], ...
             'ListboxTop',0, ...
             'Units','Normalized', ...
             'Position',[ 0.0515625 0.852083333333333 0.9046875 0.102083333333333 ], ...
             'String',string, ...
             'Style','text', ...
             'Tag','title',...
             'FontName',fontname,...
             'FontUnits','Points', ...
             'FontSize', 27 * font_scale_factor, ...
             'ForegroundColor',[0 0 0.627450980392157] );

function text = static_text( fig, pos, txt )

text = uicontrol('Parent',fig, ...
                  'Units','Normalized', ...
                  'BackgroundColor',[0.8 0.8 0.8], ...
                  'FontUnits','Points', ...
                  'FontSize',12 * font_scale_factor, ...
                  'HorizontalAlignment','left', ...
                  'ListboxTop',0, ...
                  'Position',pos, ...
                  'String', txt, ...
                  'Style','text', ...
                  'Tag','stext');

function check = make_checkbox( fig, pos, title, tag )
check = uicontrol('Parent',fig, ...
	'Units','Normalized', ...
	'BackgroundColor',[0.8 0.8 0.8], ...
	'ListboxTop',0, ...
	'Position',pos, ...
	'String',title, ...
	'Style','checkbox', ...
        'HorizontalAlignment','Left',...
	'Tag',tag);

function cont = make_continue( fig, continue_call );

cont = uicontrol('Parent',fig, ...
	'Units','Normalized', ...
	'FontSize',0.2301587301587301, ...
	'ListboxTop',0, ...
	'Callback',continue_call, ...
	'Position',[ 0.390625 0.0520833333333333 0.18125 0.0958333333333333 ],...
	'String','Continue', ...
	'Tag','continue');

function cancel = make_cancel( fig, cancel_call )
cancel = uicontrol('Parent',fig, ...
	'FontSize',0.2301587301587301, ...
	'Units','Normalized', ...
	'Callback',cancel_call, ...
	'ListboxTop',0, ...
	'Position',[ 0.7421875 0.0520833333333333 0.18125 0.0958333333333333 ], ...
	'String','Cancel', ...
	'Tag','cancel');

function ok = make_ok( fig, cancel_call )
ok = uicontrol('Parent',fig, ...
	'FontSize',0.2301587301587301, ...
	'Units','Normalized', ...
	'Callback',cancel_call, ...
	'ListboxTop',0, ...
	'Position',[ 0.234375 0.0520833333333333 0.18125 0.0958333333333333 ], ...
	'String','OK', ...
	'Tag','cancel');

function back = make_back( fig, back_call )
back = uicontrol('Parent',fig, ...
	'Units','Normalized', ...
	'FontSize',0.2301587301587301, ...
	'ListboxTop',0, ...
	'Callback',back_call, ...
	'Position',[ 0.078125 0.0520833333333333 0.1765625 0.09375 ], ...
	'String','Back', ...
	'Tag','back');

function details = make_details( fig, details_call )
details = uicontrol('Parent',fig, ...
	'Units','Normalized', ...
	'FontSize',0.2301587301587301, ...
	'ListboxTop',0, ...
	'Callback',details_call, ...
	'Position',[ 0.078125 0.0520833333333333 0.1765625 0.09375 ], ...
	'String','Details...', ...
	'Tag','back');

function errorbar = make_errbar( fig )
errorbar = uicontrol('Parent',fig, ...
	'Units','Normalized', ...
	'BackgroundColor',[0.8 0.8 0.8], ...
        'FontUnits','Points', ...
	'FontSize',12 * font_scale_factor, ...
	'FontWeight','bold', ...
	'ForegroundColor',[1 0 0], ...
	'HorizontalAlignment','left', ...
	'ListboxTop',0, ...
	'Position',[0.0781 0.2083 0.8984 0.1042], ...
	'Style','text', ...
	'Tag','errorbar');

function y = font_scale_factor
        if (strcmp(computer,'PCWIN'))
            
            sp = get(0,'Screenpixels');

            y = (96/sp)^2;
        else
            y =0.8 ;
        end
        

function make_rb_group( frame, varargin )
        nbuttons = nargin-1;
        if (nbuttons <=0)
            error('Cannot make a radio button group without at least one button' );
        end
        userdata = [ varargin{:} ];
        set( frame, 'UserData', userdata );
        set( frame, 'Value', 1 );
        set( varargin{1}, 'Value', 1 );

        for i=1:nbuttons
                set( varargin{i}, 'Min', 0, 'Max', i );
                set( varargin{i}, 'UserData', frame );
                set( varargin{i}, 'CallBack', ...
                    [ 'h = get( gco, ''UserData'' ); ',...
                      'hr = get( h, ''UserData''); ',...
                      'cv = get( h, ''Value'' ); ', ...
                      'set( hr( cv ), ''Value'', 0 ); ',...
                      'nv = find( hr == gco ); ',...
                      'set( h, ''Value'', nv )' ] );
        end

function err = run_commands(d, commands)

        err = 0;
        if (strcmp( computer, 'PCWIN'))           
            for i=1:length(commands)
                err = unix( commands{i} );
                if (err)
                    return;
                end
            end
        else
            for i=1:length(commands)
                err = unix( commands{i} );
                if (err)
                    return;
                end
            end
        end
                

function [name, access, flag, mcode] = save_send_settings( fig, d )

    name = [];
    access = [];
    flag = [];
    mcode = [];

    sendframe = findobj( fig, 'Tag', 'sendframe' );
    if (~isempty(sendframe))
        flag = get( sendframe, 'Value' );
        save( '-append', fullfile( d, 'survey_settings'), 'flag' );
    end

    hname = findobj( fig, 'Tag', 'name' );
    if (~isempty(hname))
        name = get( hname, 'String' );
        save( '-append', fullfile( d, 'survey_settings'), 'name');
    end
    
    haccess = findobj( fig, 'Tag', 'access' );
    if (~isempty( haccess))
        access = get( haccess, 'String' );
        save( '-append', fullfile( d, 'survey_settings'), 'access');
    end
    hmcode = findobj( fig, 'Tag', 'mcode' );
    if (~isempty(hmcode))
        mcode = get( hmcode, 'Value' );
        save( '-append', fullfile( d, 'survey_settings'), 'mcode' );
    end
     
function f = cfullfile(varargin)
   f = fullfile(varargin{:});
   f = strrep(f,'\','\\');


function s = pcwin_zip(fig, update, zip, file )
    exe_ext = load_variable_from_matfile( 'survey_settings', 'exe_ext' );
    zipexe = fullfile( matlabroot, 'bin', 'zip' );
    if (exist([zipexe exe_ext ]) ~= 2)
        zipexe = fullfile( matlabroot, 'bin', 'win32', 'zip' );
        if (exist( [zipexe exe_ext]) ~=2)
            seterr( fig, 'Internal Error: Unable to zip the results.', 1 );
        end
    end
    if (update == 1)
        s = [zipexe ' -j -u ' zip ' ' file];
    else
        s = [zipexe ' -j ' zip ' ' file]; 
    end
    
function s= unix_tar( fig, update, zip, file )
    [path,basename,ext,ver] = fileparts( file );
    
    if (update == 1)
        s = [ 'tar uvf ' zip ' -C ' path ' ' basename ext ];
    else
        s = ['tar cvf ' zip ' -C ' path ' ' basename ext ];
    end

function fig = get_bug_filename(d)
    fig = figure('Color',[0.8 0.8 0.8], ...
                 'InvertHardcopy','off', ...
                 'PaperUnits','points', ...
                 'Position',[22 505 640 480], ...
                 'Resize','Off', ...
                 'NumberTitle', 'Off', ...
                 'Name', 'Compiler Bug Report',...
                 'UserData', 0,...
                 'Tag', 'CompilerBugReport' );
    center(fig);

    hmname = uicontrol('Parent', fig, ...
                       'Units','Normalized', ...
                       'BackgroundColor',[1 1 1], ...
                       'ListboxTop',0, ...
                       'Position',[0.46875 0.78125 0.4703125 0.05208333333333334], ...
                       'HorizontalAlignment','left', ...
                       'Style','edit', ...
                       'Tag','mname');

    mname = load_variable_from_matfile( 'survey_settings', 'mname' );
    if (~isempty(mname))
        set( hmname, 'String', mname );
    end

    title = maketitle( fig, 'Compiler Bug Report' );


    prompt = static_text( fig, [0.078125 0.78125 0.359375 0.05625], ...
                          '1. Enter the name of the M file:' );

                
    prompt2 = static_text( fig, [0.078125 0.672916666666667 0.9 0.05625], ...
                          '2. Describe the nature of the compiler problem:' );
    hdescription = uicontrol('Parent', fig, ...
                       'Units','Normalized', ...
                       'BackgroundColor',[1 1 1], ...
                       'ListboxTop',0, ...
                       'Position',[ 0.08125 0.189583333333333 0.8359375 0.45625 ], ...
                       'HorizontalAlignment','left', ...
                       'Style','edit',...
                       'Max', 2,...
                       'Tag','description');

    description = load_variable_from_matfile( 'survey_settings', 'description' );
    if (~isempty(description))
        set( hdescription, 'String', description );
    end

    make_continue( fig, 'compiler_survey(8);' );
    make_cancel( fig, ...
        ['h = get(gcbf, ''UserData'');',...
         'if (h ~= 0),',... 
         'close(h);',...
         'end;',...
         'compiler_survey(-1);' ]);

    make_details( fig, ['if (get( gcbf, ''UserData'') == 0), compiler_survey(9);, ',...
                       'else, figure(get(gcbf, ''UserData'')); end'] );


function myfig = bug_detail_screen(fig)
myfig = fig;
fig = figure('Color',[0.8 0.8 0.8], ...
             'InvertHardcopy','off', ...
             'PaperUnits','points', ...
             'Position',[22 505 640 480], ...
             'Resize','Off', ...
             'NumberTitle', 'Off', ...
             'Name', 'Compiler Bug Report Details',...
             'Tag', 'CompilerSurvey' );
center(fig);
set( myfig, 'UserData', fig );
set( fig, 'UserData', myfig );
title = maketitle( fig, 'Compiler Bug Report Details' );

intro = static_text( fig, [0.0391 0.5125 0.925 0.31875], ...
[ 'The MathWorks is very interested in improving the quality of the MATLAB Compiler. '...
  'We want to hear about any problems or invonvieniences that you experience in using our products. '...
  'The intent of this form is to collect the details from you about a problem that you have '...
  'with the MATLAB Compiler, and to optionally provide us with the M code that you were using when '...
  'the problem arose.  This M source code will be used exclusively to diagnose and correct the problem ' ...
  'that you experienced and for no other reason.  Please include information on how to run the M file'...
  'so that we will be able to reproduce your problem.' ] );


ok = make_ok( fig, 'h = get(gcbf, ''UserData''); set( h, ''UserData'', 0 ); close(gcbf); figure(h);' );

set( ok, 'Position',[ 0.390625 0.0520833333333333 0.18125 ...
        0.0958333333333333 ] );


function fig = collect_bug_info( fig, d )

    [mname,omname, e ] = get_mname( fig, d, 1 );
    hdesc = findobj( fig, 'Tag', 'description' );
    if (isempty(hdesc))
        seterr( fig, 'Error: Provide a description of the problem that you encountered.', 1, bug_report );
    end
    description = get( hdesc, 'String' );
    if (isempty(description))
        seterr( fig, 'Error: Provide a description of the problem that you encountered.',1, bug_report );
    end
    save( '-append', fullfile( d, 'survey_settings'), 'description');
    fig = ask_and_bundle(fig, d, 1);

function [mname,omname,e] = get_mname( fig, d, bug_report )

    mname = '';
    hmname = findobj(fig, 'Tag', 'mname' );
    if (isempty(hmname))
        seterr( fig, 'Error: Provide the name of the M file', 1, bug_report );
        return
    end
    mname = get( hmname, 'String' );
    if (isempty(mname))
        seterr( fig, 'Error: Provide the name of the M file', 1, bug_report);
        return
    end
    omname = load_variable_from_matfile( 'survey_settings', 'mname' ); 
    save( '-append', fullfile( d, 'survey_settings'), 'mname');
    [path,mname,ext,ver] = fileparts( mname );

    if (~isempty( path ))
        disp( ['Adding ' path ' to the MATLAB path' ]);
        eval( ['addpath ' path ] );
    end

    e = exist(mname);
    if (e ~= 2)
        seterr( fig, [ 'Error: "' mname '" must be a valid M file to run (not a mex or built-in file.)' ], 1, bug_report );
        e = 1;
        return;
    end

    e = 0;
