function filemenufcn(hfig, cmd)
%FILEMENUFCN Implements part of the figure file menu.
%  FILEMENUFCN(H, CMD) invokes file menu command CMD in figure H.
%
%  CMD can be one of the following:
%
%    FilePost
%    FileOpen
%    FileSave
%    FileSaveAs
%    FileExport
%    FilePreferences (PC only)
%    FilePrintSetup (PC only)

%  Damian T. Packer, 11 June 1998
%  Copyright (c) 1984-98 by The MathWorks, Inc.
%  $Revision: 1.5 $  $Date: 1998/07/01 23:14:43 $

LASTEXPORTEDASTYPE='FileMenuFcnLastExportedAsType';
LASTEXPORTEDASNAME='FileMenuFcnLastExportedAsName';

error(nargchk(2,2,nargin));

ispc = strcmp(computer, 'PCWIN');

if strcmp(cmd, 'FilePost')
   %
   % The first time the FilePost callback is called, hide any
   % non-functional items on Unix, and then deinstall the callback,
   % since it need happen only once.
   %
   if ~ispc
      % hide non-functional unix items
      file = findall(allchild(hfig),'type','uimenu','label','&File');
      set(findall(file,'label','Pre&ferences...'),'visible','off');
      drawnow;
   end

else
   %
   % All other callbacks happen to be implemented built-in on the
   % PC, so just pass the input arguments through if we're on the
   % PC.  If we're on Unix, we need to implement the ones we can in
   % M.
   
   if ispc   
      uimenufcn(hfig, cmd);
      
   else % we're on UNIX:
      
      switch cmd
         
      case 'FileOpen'
         
         % bring up the selection dialog
         [filename, pathname] = uigetfile('*.fig', 'Open Figure');
         
         if filename~=0
            try
               loaded=hgload(fullfile(pathname,filename));
            catch
               errordlg(lasterr,'Error Loading Figure','modal');
               uiwait;
            end;
         end;
         
         
      case 'FileSave'
         fullfilename=get(hfig,'filename');
         if isempty(fullfilename)
            % If the figure doesn't have a filename, jump to FileSaveAs
            filemenufcn(hfig,'FileSaveAs');
         else
            try
               hgsave(hfig,fullfilename);
            catch
               errordlg(lasterr,'Error Saving Figure','modal');
               uiwait;
            end
         end       
         
         
      case 'FileSaveAs'
         filename=get(hfig,'filename');
         if isempty(filename)
            filename='*.fig';
         end;
         
         %pull the filename with extension out of the full path listing
         [PATH,FILENAME,EXT,VER] = fileparts(filename);
         filename=[FILENAME EXT];
                  
         % Bring up user selection dialog
         % if no file name is entered, repeat
         newfile='';
         while isempty(newfile)
            [newfile, newpath] = uiputfile(filename, 'Save As');
         end;
         
         if newfile~=0
            % if cancel button was not pressed            
            % save the figure
            fullfilename=fullfile(newpath,newfile);
            try
               hgsave(hfig,fullfilename);
            catch
               errordlg(lasterr,'Error Saving Figure','modal');
               uiwait;
            end
            set(hfig,'filename',fullfilename);
         end;
         
                  
      case 'FileExport'
         % Remember the last export filename
         if isappdata(0,LASTEXPORTEDASNAME)
            filename=getappdata(0,LASTEXPORTEDASNAME);
         else
            % Check the figure's filename
            figfilename=get(hfig,'filename');
            if isempty(figfilename)
               filename=fullfile(pwd,'*');
            else
               filename=figfilename;
            end;
         end;
                  
         % Remember last type exported
         if isappdata(0,LASTEXPORTEDASTYPE)
            startingtype=getappdata(0,LASTEXPORTEDASTYPE);
         else
            startingtype=1;
         end;
         
         
         % Get list of supported types, a cell array where each row has
         % the type's NAME, it's EXTENSION, and the PRINT OPTION that creates it
         typelist=exportTypes;
         
         % build the window (in character units)
         
         exportwindow=figure('Name','Export Figure',...
            'numbertitle','off',...
            'menubar','none',...
            'windowstyle','normal',...
            'resize','off',...
            'color',get(0,'defaultuicontrolbackgroundcolor'),...
            'units','characters');
         p=get(exportwindow,'position');
         set(exportwindow,'position',[p(1) p(2) 80 15]);
         
         uicontrol('string','File name:',...
            'style','text',...
            'units','character',...
            'horizontalalignment','left',...
            'position',[2 13 49 1]);
         
         filenameeditbox=uicontrol('String',filename,...
            'units','character',...
            'style','edit',...
            'backgroundColor','w',...
            'horizontalAlignment','left',...
            'position',[2 11 59 2]);
         uicontrol('String','Browse...',...
            'units','characters',...
            'position',[63 11 15 2],...
            'callback', 'setappdata(gcbf,''action'',''browse'');uiresume;' );
         
         uicontrol('string','Save as type:',...
            'style','text',...
            'units','character',...
            'horizontalalignment','left',...
            'position',[2 9 68 1]);
         
         popuplisting=uicontrol('string',typelist(:,1),...
            'style','popup',...
            'units','character',...
            'position',[2 7 59 2],...
            'value',startingtype,...
            'HorizontalAlignment','left',...
            'callback','setappdata(gcbf,''action'',''changetype'');uiresume;');
         
         uicontrol('style','frame',...
            'units','character',...
            'position',[-1 -1 82 6]);
         
         uicontrol('String','Save',...
            'units','characters',...
            'position',[46 1 15 2],...
            'callback','setappdata(gcbf,''action'',''save'');uiresume;');
         uicontrol('String','Cancel',...
            'units','characters',...
            'position',[63 1 15 2],...
            'callback','setappdata(gcbf,''action'',''cancel'');uiresume;');
         
         % make sure the filename has the right extension to start
         setappdata(exportwindow,'action','changetype');
         
         finished=0;
         while ~finished
            switch getappdata(exportwindow,'action')   
            case 'changetype'
               % Set the filename to have the right extension
               typevalue=get(popuplisting,'value');
               
               typename=typelist{typevalue,1};
               typeextension=typelist{typevalue,2};
               typeoption=typelist{typevalue,3};
               
               [path,name,ext]=fileparts(get(filenameeditbox,'string'));
               set(filenameeditbox,'string',fullfile(path,[name typelist{typevalue,2}]));
               
            case 'browse'
               % Bring up Export window to set the filename
               filename=get(filenameeditbox,'string');
               [path,name,ext]=fileparts(filename);
               [newfile, newpath] = uiputfile([name ext],['Export ' typename]);
               if ~isempty(newfile) & newfile~=0
                  set(filenameeditbox,'string',fullfile(newpath,newfile));
               end;
               
            case 'cancel'
               % Cancel the save
               delete(exportwindow);
               finished=1;
               
            case 'save'
               % Save the file
               filename=get(filenameeditbox,'string');
               [path,name,ext]=fileparts(filename);
               if isequal(name,'*')
                  errordlg('Enter a name for the file.','File name missing','modal');
                  uiwait;
               else
                  try
                     print(hfig,['-d' typeoption],filename);
                     delete(exportwindow);
                     % Remember the type for future exports
                     setappdata(0,LASTEXPORTEDASTYPE,typevalue);
                     setappdata(0,LASTEXPORTEDASNAME,filename);
                     finished=1;
                     % If the figure doesn't have a filename, give it this one
                     % if isempty(get(hfig,'filename'))
                     %   set(hfig,'filename',fullfile(path,[name '.fig']));
                     % end;
                  catch
                     errordlg(lasterr,'Error Saving Figure','modal');
                     uiwait;
                  end;  
               end;
            end;
            

            % wait for another action from the user
            if ishandle(exportwindow) & ~finished 
               uiwait;
            end;
            
            % stop if the close button was pressed
            if ~ishandle(exportwindow), 
               finished=1; 
            end
         end
         
      case 'FilePreferences'
         % do prefs stuff
         
      case 'FilePrintSetup'
         printdlg -setup;
      end
   end
end

%==========================================================

function list=exportTypes;

% build the list dynamically from @printjob/tables.m
[a,opt,ext,d,e,output,name]=tables(printjob);

% only use those marked as export types (rather than print types)
% and also have a descriptive name
valid=strcmp(output,'X') & ~strcmp(name,'');

name=name(valid);
ext=ext(valid);
opt=opt(valid);

% put a dot in front of all the extensions
for i=1:length(ext)
   ext{i}=['.' ext{i}];
end

list=[name,ext,opt];
