function Fig = printdlg(fig,pos1,pos2,hideme)
%PRINTDLG  Dialog box for printing hardcopy of figures.
%	DLG = PRINTDLG(FIG) creates a dialog box from which the figure
%	window, FIG, can be printed.  Note that uicontrols and 
%	uimenus do not print.  PRINTDLG by itself prints the gcf.
%	DLG is the handle to the print dialog figure.
%
%	PRINTDLG(FIG,POS1,POS2) maps the figure from POS1 to POS2
% 	for printing, and then maps it back when done.  POS1 and POS2 are
%	rectangle position vectors in normalized coordinates.  (See
%	REMAPFIG for details.)  This allows for excluding the empty space 
%	taken up by uicontrols.
%	    Example: 
%	        printdlg(1,[.13 .11 .62 .815],get(gcf,'defaultaxesposition'))
%	
%	PRINTDLG(FIG,POS1,POS2,HIDEME) turns all the objects with handles
%	in HIDEME invisible for printing, and turns them visible again when
%	done (if they are visible originally).
%
%	PRINTDLG turns the figure background color to [0 0 0] for
%	printing, and all axes colors to 'none' (unless the figure's
%	'InvertHardcopy' property is 'off').

%	Author(s): T. Krauss, 8/29/94
%	Copyright (c) 1995 by The MathWorks, Inc.
%	$Revision: 1.14 $  $Date: 1995/10/19 14:18:26 $

if nargin == 0
    fig = gcf;
end

if ~isstr(fig)     % initialization - open figure 

    if size(fig)~=[1 1], error('FIG input must be a scalar'), end
    ret = 0;     % return if fig is not a figure
    eval(['ret=~strcmp(get(' num2str(fig) ',''type''),''figure'');'],...
       'ret=1;');
    if ret, return; end

    figname = get(fig,'name');
    if strcmp(get(fig,'numbertitle'),'on') 
        if (length(figname)>0)
            figname = [': ' figname];
        end
        figname = ['Figure ' num2str(fig) figname];
    end
    if isempty(figname)   % no name, number title off
        figname = ['Figure ' num2str(fig)];
    end

    dlgname = [figname ': Print'];
    [flag,dlg] = figflag(dlgname,0);   % bring to front if it's alive
    if ~flag                           % else, create it
         %create figure
        dlg = figure(...
            'color',get(0,'defaultuicontrolbackgroundcolor'),...
            'colormap',[],...
            'menubar',menubar,...
            'resize','off',...
            'visible','off',...
            'Name',dlgname, ...
            'NumberTitle','off');

        pos = get(dlg,'position');
        set(dlg,'position',[pos(1:2) 420 130]);

        uicontrol('style','frame',...
             'position',[0 36 420 121])

        uicontrol('style','frame',...
             'position',[0 0 420 35])

        uicontrol('style','pushbutton',...
             'tag','pbutton',...
             'String','Print',...
             'position', [280 6 120 22],...
             'callback','printdlg(''print'')');

        uicontrol('style','pushbutton',...
             'String','Cancel',...
             'position', [150 6 120 22],...
             'callback','printdlg(''dismiss'')');

        uicontrol('style','pushbutton',...
             'String','Help...',...
             'position', [20 6 120 22],...
             'callback','printdlg(''help'')');


        uicontrol('style','text',...
              'string','Device Option:',...
              'horizontalalignment','right',...
              'position', [20 105 170 22]);

        uicontrol('style','edit',...
              'tag','device',...
              'backgroundcolor','w',...
              'horizontalalignment','left',...
              'position', [200 105 210 22]);

        uicontrol('style','text',...
              'string','Paper Orientation:',...
              'horizontalalignment','right',...
              'position', [20 74 170 22]);

        uicontrol('style','popup',...
              'tag','orient',...
              'string','landscape|portrait|tall',...
              'position', [200 74 210 22]);

        uicontrol('style','radio',...
              'tag','toprinter',...
              'string','Send to Printer',...
              'value',1,...
              'callback',['set(findobj(gcf,''tag'',''tofile''),''value'',0);'...
               'set(findobj(gcf,''tag'',''toprinter''),''value'',1);' ...
           'set(findobj(gcf,''tag'',''pbutton''),''string'',''Print'')'],...
              'position', [10 42 195 22]);
        uicontrol('style','radio',...
              'tag','tofile',...
              'string','Send to File',...
              'value',0,...
              'callback',['set(findobj(gcf,''tag'',''tofile''),''value'',1);'...
               'set(findobj(gcf,''tag'',''toprinter''),''value'',0);' ...
           'set(findobj(gcf,''tag'',''pbutton''),''string'',''Save...'')'],...
              'position', [215 42 195 22]);
    end

    [pcmd,device] = printopt;
    set(findobj(dlg,'tag','device'),'string',device)

    % o = orient;   % in-line code for 'orient' here
    o = lower(get(fig,'PaperOrientation'));
    if strcmp(o,'portrait')
       pp = get(fig,'PaperPosition');
       ps = get(fig,'PaperSize');
       if all(pp([3,4]) == ps) & ps(1) < ps(2)
          o = 'tall';
       end
    end

    if strcmp(o,'landscape')
        set(findobj(dlg,'tag','orient'),'value',1)
    elseif strcmp(o,'portrait')
        set(findobj(dlg,'tag','orient'),'value',2)
    else
        set(findobj(dlg,'tag','orient'),'value',3)
    end

    set(dlg,'visible','on')

    if nargin < 2
        pos1 = [0 0 1 1];
    end
    if nargin < 3
        pos2 = [0 0 1 1];
    end
    if nargin < 4
        hideme = [];
    end
    
    % (re)store parameters in userdata
    set(dlg,'userdata',[fig; pos1(:); pos2(:); hideme(:)]);

    if nargout,
        Fig = dlg;
    end

elseif strcmp(fig,'print')
%-------------------------------------------------------------------------
% printdlg('print')
%   Print the figure and then close the dialog.
%   The dialog is the gcf on input.
%   The figure is left as the gcf on output.
%

    dlg = gcf;
    ht = get(dlg,'userdata');

    if get(findobj(dlg,'tag','tofile'),'value')==1
        set(dlg,'visible','off')
        [fname, pname] = uiputfile('*','Save As');
        if fname==0
            close(dlg)
            return
        end
    else
        fname = '';
        pname = '';
    end

    fig = ht(1);
    figure(fig)

    fpoint = get(fig,'pointer');  % save pointer
    set([fig dlg],'pointer','watch')
    drawnow

    o = get(findobj(dlg,'tag','orient'),'value');
    if o == 1
        orient landscape
    elseif o == 2
        orient portrait
    else
        orient tall
    end

    device = get(findobj(dlg,'tag','device'),'string');

    % Need to use parentheses for of print command
    % Re: The Mac will otherwise error for files of paths with spaces
    if ~isempty(fname) & ~isempty(pname)
        pstr = ['print(''-f' num2str(fig) ''',''' device ''',''' pname fname ''')'];
    elseif ~isempty(fname) 
        pstr = ['print(''-f' num2str(fig) ''',''' device ''',''' fname ''')']
    else
        pstr = ['print -f' num2str(fig) ' ' device];
    end

    pos1 = ht(2:5);  pos2 = ht(6:9);
    hideme = ht(10:length(ht));
    hidemeax = findobj(hideme,'type','axes');   % make all axes children
                 % invisible too
    for i = 1:length(hidemeax)
        temp = get(hidemeax(i),'children');
        hideme = [hideme(:); temp(:)];
    end

    hidemevis = [];   % store which of the hidden objects are visible
    for i = 1:length(hideme)
        if strcmp(get(hideme(i),'visible'),'on')
            hidemevis = [hidemevis i];
        end
    end

    set(hideme,'visible','off')   % vectorized set

    if strcmp(get(fig,'InvertHardcopy'),'on'),
        fcolor = get(fig,'color');   % save figure color
        ax = findobj(fig,'type','axes');
        acolor = [];
        for i=1:length(ax)     % save axes colors
            temp = get(ax(i),'color');
            if isstr(temp)
               axcolor = [axcolor; -1 -1 -1];
            else
               axcolor = [axcolor; temp];
            end
        end
       set(fig,'color','k')         % temporarily set figure color to black
       set(ax,'color','none');  % vectorized set  - set axes colors to none
    end

    remapfig(pos1,pos2,fig,findobj(fig,'type','axes'))
    drawnow discard    % don't redraw on screen

    % NOW EVAL THE PRINT STATEMENT:
    error = 0;
    eval(pstr,'error = 1;')   % print causes uicontrols to flash - sigh...

    if error
        disp('An error occurred when I tried to print.  Here was the print command:')
        disp(pstr)
        disp('and here was the error:')
        disp(lasterr)
    end

    remapfig(pos2,pos1,fig,findobj(fig,'type','axes'))

    if strcmp(get(fig,'InvertHardcopy'),'on'),
        for i=1:length(ax)   % restore axes colors
            if axcolor(i,1) == -1
                set(ax(i),'color','none');  
            else
                set(ax(i),'color',axcolor(i,:));  
            end
        end
        set(fig,'color',fcolor)  % restore figure color
    end

    set(hideme(hidemevis),'visible','on')   % vectorized set

    close(dlg)
    set(fig,'pointer',fpoint)

elseif strcmp(fig,'dismiss')
%-------------------------------------------------------------------------
% printdlg('dismiss')
%   Dismiss the dialog (print aborted).
%   The dialog is the gcf on input.
%
    close

elseif strcmp(fig,'help')
%-------------------------------------------------------------------------
% printdlg('help')
%   Open the help on printing with the print dialog.
%   Uses xppage.
%   The dialog is the gcf on input.
%

    ttlStr = 'Print Dialog Help';


   hlpStr1= ...                                               
        ['                                                     '  
         '   To send the designated figure window to           '  
         '   the default printer, select the "To Printer" radio'  
         '   button and press the "Print" button.              '  
         '                                                     '  
         '   To send the figure to a file, select the          '  
         '   "To File" radio button and press the "Save..."    '  
         '   button.  A dialog box will appear, in which       '  
         '   you can enter a filename for the file.            '  
         '   Once you specify a filename and press the         '  
         '   "Done" or "Save" button, the output is            '  
         '   written to the designated file, overwriting       '  
         '   it if it already exists. If the specified         '  
         '   filename does not include an extension,           '  
         '   an appropriate one is appended.                   '  
         '                                                     '  
         '   If you change your mind about printing at any     '  
         '   time, press the "Cancel" button to cancel the     '  
         '   operation.                                        '];


    hlpStr2= ...                                             
        ['                                               '  
         '    DEVICES                                    '  
         '    -------                                    '  
         '                                               '  
         '    Specify a device and other options in the  '  
         '    Device Option field.                       '  
         '                                               '  
         '    Type "help print" in the command window for'  
         '    a complete list of supported devices.      '  
         '                                               '  
         '                                               '  
         '                                               '];

    hlpStr3= ...                                           
        ['                                             '  
         '    PAPER ORIENTATION                        '  
         '    ----------------                         '  
         '                                             '  
         '    LANDSCAPE generates output in full-page  '  
         '    landscape orientation on the paper.      '  
         '                                             '  
         '    PORTRAIT prints the figure window        '  
         '    occupying a rectangle with aspect ratio  '  
         '    4/3 in the middle of the page.           '  
         '                                             '  
         '    TALL causes the figure window to map to  '  
         '    the whole page in portrait orientation.  '  
         '                                             '  
         '    This popup sets the PaperOrientation and '  
         '    PaperPosition properties of the printed  '  
         '    figure window.                           '  
         '                                             '];


    xppage(ttlStr,hlpStr1,hlpStr2,hlpStr3);

% see hlpmaker to edit these strings


end
