function fcns = menus_cbs
%MENUS_CBS  Handles all the callbacks executed by the uimenus and
%           toolbar pushbuttons and togglebuttons.
%
%   Inputs:
%     fcn    - local function to be executed
%     h_gcbo - handle to current callback object       

%   Author(s): R. Losada, P. Pacheco, P. Costa
%   Copyright 1988-2000 The MathWorks, Inc.
%   $Revision: 1.29 $  $Date: 2000/07/24 20:59:34 $ 


%persistent fcns;
%if isempty(fcns),
% "Export" the handles to all local functions via a structure.
% The caller will get this, and grab the handles they need.
% This will allow callers to gain direct access to local functions.
%
fcns.new_cb           = @new_cb;
fcns.open_cb          = @open_cb;
fcns.save_cb          = @save_cb;
fcns.saveas_cb        = @saveas_cb;
fcns.export_cb        = @export_cb;
fcns.print_cb         = @print_cb;
fcns.exit_cb          = @exit_cb;
fcns.undochanges_cb   = @undochanges_cb;
fcns.type_menu        = @type_menu;
fcns.method_menu      = @method_menu;
fcns.zoomin_oncb      = @zoomin_oncb;
fcns.zoomout_oncb     = @zoomout_oncb;
fcns.zoomout_offcb    = @zoomout_offcb;
fcns.zoomin_offcb     = @zoomin_offcb;
fcns.zoom_clickedcb   = @zoom_clickedcb;
fcns.filterspecs_cb   = @filterspecs_cb;
fcns.magresp_cb       = @magresp_cb;
fcns.phaseresp_cb     = @phaseresp_cb;
fcns.magnphaseresp_cb = @magnphaseresp_cb;
fcns.groupdelay_cb    = @groupdelay_cb;
fcns.impresp_cb       = @impresp_cb;
fcns.stepresp_cb      = @stepresp_cb;
fcns.pzplot_cb        = @pzplot_cb;
fcns.filtercoeffs_cb  = @filtercoeffs_cb;
fcns.mcode_cb         = @mcode_cb;
fcns.savecoeffs_cb    = @savecoeffs_cb;
fcns.savespecs_cb     = @savespecs_cb;
%end

%---------------------------------------------------------------------
function savecoeffs_cb(hcbo,eventStruct)

warning('savecoeffs_cb not yet implemented');

%---------------------------------------------------------------------
function savespecs_cb(hcbo,eventStruct)

warning('savespecs_cb not yet implemented');

%---------------------------------------------------------------------
function new_cb(hcbo,eventStruct)
%NEW_CB Callback for the New menu item and pushbutton.
%
% Inputs:
%   hcbo - handle of callback object (not being used)
%   hFig - handle of fdatool figure.

% Launch a completely new tool
fdatool;

%---------------------------------------------------------------------
function open_cb(hcbo,eventStruct)
%OPEN_CB Callback for the Open menu item and pushbutton.
%
% Inputs:
%   hcbo - handle of callback object (not being used)
%   hFig - handle of fdatool figure.

hFig = gcbf;
ud = get(hFig,'userdata');

% Don't load if GUI is dirty.
if save_if_dirty(hFig,'loading'),  
   
   % Change to the directory where the current session lives.
   old_pwd = pwd;
   [path,name,ext] = fileparts(ud.filename.session);
   if ~isempty(path); cd(path); end
    
   % Load the file.
   [filename,pathname] = uigetfile('*.fda','Load Filter Design Session');
   file = [pathname filename];
   cd(old_pwd);    % Return to old pwd ASAP after loading the file.
    
   % Skip loading if Cancel button is pressed on save dialog.
   if file ~= 0,
       update_status(hFig,'Loading session file...');    
       new_ud = load_exec(ud,file);   % Modifies userdata
       set(hFig,'Userdata',new_ud);
       % Populate the GUI with new specs
       update_gui(hFig);
   end
end

%---------------------------------------------------------------------
function save_cb(hcbo,eventStruct)
%SAVE_CB Callback for the Save menu item and pushbutton.
%
% Inputs:
%   hcbo - handle of callback object (not being used)
%   hFig - handle of fdatool figure.

hFig = gcbf;
ud = get(hFig,'userdata');
file = ud.filename.session;

file_exists = exist(file,'file');

if ~file_exists | ~ud.flags.overwrite,
   % If never saved, ask for a file name as in save as.
   saveas_cb(hcbo,hFig);             % Modifies the userdata.
   return
end

if file ~=0,
    save2file(file,hFig);
end    

%---------------------------------------------------------------------
function saveas_cb(hcbo,eventStruct)
%SAVEAS_CB Callback for the Save as menu item.
%
% Inputs:
%   hcbo - handle of callback object (not being used)
%   hFig - handle of fdatool figure.

hFig = gcbf;
ud = get(hFig,'userdata');
file = ud.filename.session;
[filename,pathname] = fduiputfile(file,'Save Filter Design Session');
file = [pathname filename];

if filename ~= 0       
   save2file(file,hFig);
end

%---------------------------------------------------------------------
function export_cb(hcbo,eventStruct)
%EXPORT_CB Callback for the "Export" menu item.
%
% Inputs:
%   hcbo - Handle of callback object 
%   hFig - Handle of fdatool figure.

hFig = gcbf;
ud = get(hFig,'UserData');

% Ensure that only ONE "Export" dialog is ever launched.
if isfield(ud.h,'dlgs') & isfield(ud.h.dlgs,'export') ...
        & ishandle(ud.h.dlgs.export),
    figure(ud.h.dlgs.export); % Makes the dialog the current figure
else
    % Render the Export dialog (figure).
    hExportdlg = render_exportdlg(hFig);
    
    % Update the state of the dialog (turn it on)
    update_exportdlg('update_all', hFig);
end


%---------------------------------------------------------------------
function print_cb(hcbo,eventStruct)
%NEW_CB Callback for the New menu item and pushbutton.
%
% Inputs:
%   hcbo - handle of callback object (not being used)
%   eventStruct - not being used.

% Cache figure's handle and userdata structure.
hFig = gcbf;
ud = get(hFig,'Userdata');

if strcmpi(ud.toolbar.analysis,'filtercoeffs'),
    % Export the coeffs to the MATLAB editor for printing.
    printCoeffViewer(ud.filter);
    return;
end

% Create a "print preview" figure and copy FDATool's analysis axis.
hFig_printprev = figure('Number','off','Name','FDATool Print Preview');
copyobj(ud.h.analysis.ax,hFig_printprev);

% Get handle to the axes of print preview figure.
hax_printprev = findobj(hFig_printprev,'Type','axes');

% Delete invisible axis.
hax_printprev = delInvisibleax(hax_printprev);

% Set print preview's axis position to the default size in normalized units.
ax_pos = [0.1300 0.1100 0.7750 0.8150];  
set(hax_printprev,'Position',ax_pos);

% Put up print dialog box.
setptr(hFig_printprev,'watch');        % Set mouse cursor to watch.
printdlg(hFig_printprev);
setptr(hFig_printprev,'arrow');        % Reset mouse pointer.

%---------------------------------------------------------------------
function printCoeffViewer(filterObj)
% PRINTCOEFFVIEWER Exports the contents of the Coefficient Viewer to 
%                  the MATLAB editor so that users can then print it.
% Input:
%   filterObj - a DFILT or QFILT filter object.

tname = [tempname '.m'];  % Temporary file name.
fid = fopen(tname,'wt');
coeffStr = dispstr(filterObj);
for i=1:size(coeffStr,1),
    fprintf(fid,'%s\n',coeffStr(i,:));
end
fclose(fid);
edit(tname);    

%---------------------------------------------------------------------
function hax_printprev = delInvisibleax(hax_printprev)
% DELINVISIBLEAX Deletes the invisble axis.
%
% Input:
%   hax_printprev - handle to the print preview axes.
% Output:
%   hax_printprev - handle to the print preview axis that's visible.

% Delete the invisible axis.
visStates = get(hax_printprev,'Visible');
indx = find(strcmpi(visStates,'off'));
delete(hax_printprev(indx));
hax_printprev(indx) = [];

%---------------------------------------------------------------------
function exit_cb(hcbo,eventStruct)
%EXIT_CB Callback for the Exit menu item or the "X" at top-right corner.
%
% Inputs:
%   hcbo - Handle of callback object (not being used)
%   hFig - Handle of fdatool figure.

hFig = gcbf;
ud = get(hFig,'UserData');

% Skip closing if Cancel button is pressed on save dialog.
if save_if_dirty(hFig,'closing'),
    delete(hFig);
   
    % Delete any existing dialogs as well
    if isfield(ud.h,'dlgs')
        dialogNames = fieldnames(ud.h.dlgs);
        for n = 1:length(dialogNames)
            if ishandle(getfield(ud.h.dlgs,dialogNames{n})),
                % Make sure the dialog box still exists.
                delete(getfield(ud.h.dlgs,dialogNames{n}));
            end
        end
    end
    
end

%---------------------------------------------------------------------
function undochanges_cb(hcbo,eventStruct)
%UNDOCHANGES_CB Callback for the Undo Changes option under the Filter 
%              menu.
% Inputs:
%   hcbo - Handle of callback object
%   eventStruct - (not being used)

% Get the data structure stored in the figure.
hFig = gcbf;
ud = get(hFig,'Userdata');
mode = ud.mode.current;
switch mode,
case 1, % Design tab
    ud.specs.design = ud.revert.design; % Restore old values.
    ud.flags.undochanges.design = 0;    % Disable the Undo Changes option.
    set(hFig,'Userdata',ud);

    % Update other relevant parts of the GUI.  Call this first since
    % filter type and filter method frames need the updated menus.
    update_menus('update_all',hFig); 

    % Update the tab.
    update_designparams('update_all',hFig);
    update_specs('update_all',hFig);
    
case 2, % Import tab
    ud.specs.import = ud.revert.import; % Restore old values.
    ud.flags.undochanges.import = 0;    % Disable the Undo Changes option.
    set(hFig,'Userdata',ud);
    
    % Update the menus and the tab.
    update_menus('update_all',hFig); 
    update_importparams('update_all',hFig);
    
case 3, % Quantize tab
    ud.specs.quantize = ud.revert.quantize; % Restore old values.
    ud.flags.undochanges.quantize = 0;      % Disable the Undo Changes option.
    
    % This is a workaround because quantize parameters are stored in ud 
    % only when APPLY is selected.
    % By setting filter_quantized flag to true it forces the quantize 
    % tab to update itself with the new refqfilt.
    ud.flags.filter_quantized = 1; 
    set(hFig,'Userdata',ud);

    % Update the menus and the tab.
    update_menus('update_all',hFig); 
    update_quantizeparams('update_all',hFig);
    
end

% Update analysis area ONLY when Filter Specifications plot is displayed.
staticresp_only = 1;  
update_analysisframe(hFig,staticresp_only);

%----------------------------------------------------------------------
function type_menu(hcbo,eventStruct)
%TYPE_MENU   Type menu callback.
%
%   Inputs:
%     hcbo - handle to current callback object       
%     hFig - handle to the main gui figure

hFig = gcbf;
% Get user data
ud = get(hFig,'userdata');

% Get old type from ud
prev_type = ud.specs.design.type;

% Get new_type from gcbo
new_type = get(hcbo,'tag');

% If new type is same as previous type do nothing
if strcmp(prev_type,new_type),
    return
end

% Update the data structure (ud)  w/ new filter type.
ud.specs.design.type = new_type;
set(hFig,'UserData',ud);

% Set appropriate flags dirty.
set_flagsdirty(hFig);

% Update all relevant parts of the gui
update_filtertype(hFig);

%----------------------------------------------------------------------
function method_menu(hcbo,eventStruct)
%METHOD_MENU   Method menu callback.
%
%   Inputs:
%     hcbo - handle to current callback object       
%     hFig - handle to the main gui figure

% Get user data
hFig = gcbf;
ud = get(hFig,'userdata');

% Get old method from ud
prev_method = ud.specs.design.method;

% Get new_method from gcbo
new_method = get(hcbo,'tag');

% If new method is same as previous method or new method is
% window, do nothing.
if strcmp(prev_method,new_method),
    return
end

% If new method is a window, set method to fir1 and save window type
if any(strcmp(new_method,{'chebwin','kaiser','bartlett',...
            'blackman','boxcar','hamming','hann','triang'})),
    
    ud.specs.design.window = new_method;
    new_method = 'fir1';
end

% Save new method in ud.
ud.specs.design.method = new_method;
set(hFig,'userdata',ud);

% Set appropriate flags dirty.
set_flagsdirty(hFig);

% Update all relevant parts of the gui
update_filtermethod(hFig);

%-------------------------------------------------------------------------
function zoomin_oncb(hcbo,eventStruct)
%ZOOMIN_ONCB Callback for the "Zoom in" button whenever the
%            state is changed to 'On'.
%
% Inputs:
%   hcbo - handle of callback object (not being used)
%   hFig - handle of fdatool figure.

% Get the userdata stored in the figure
hFig = gcbf;
ud = get(hFig,'Userdata');

ud.toolbar.zoom = 'zoomin';
zoom(hFig,'inmode');

% Save current Zoom to UD
set(hFig,'UserData',ud);

% Set zoom to appropriate mode (zoomin or off), 
% depending on what the previous zoom mode was.
%switch zoom(hFig,'getmode')
%case {'off' 'out'},
%    zoom(hFig,'inmode');
%case {'in' 'on'},
%    zoom(hFig,'off');
%end

%-------------------------------------------------------------------------
function zoomout_oncb(hcbo,eventStruct)
%ZOOMOUT_ONCB Callback for the "Zoom out" button whenever the
%             state is changed to 'On'.
%
% Inputs:
%   hcbo - handle of callback object (not being used)
%   hFig - handle of fdatool figure.

% Get the userdata stored in the figure
hFig = gcbf;
ud = get(hFig,'Userdata');

ud.toolbar.zoom = 'zoomout';
zoom(hFig,'outmode');

% Save current Zoom to UD
set(hFig,'UserData',ud);

% Set zoom to appropriate mode (zoomout or off),
% depending on what the previous zoom mode was.
%switch zoom(hFig,'getmode')
%case {'on' 'off' 'in'},
%    zoom(hFig,'outmode');
%case 'out',
%    zoom(hFig,'off');
%end

%-------------------------------------------------------------------------
function zoomout_offcb(hcbo,eventStruct)
%ZOOMOUT_OFFCB Callback for the "Zoom out" button whenever the
%              state is changed to 'Off'.
%
% Inputs:
%   hcbo - handle of callback object (not being used)
%   hFig - handle of fdatool figure.

% Get the userdata stored in the figure
hFig = gcbf;
ud = get(hFig,'Userdata');

ud.toolbar.zoom = 'none';
zoom(hFig,'off');

% h_toolbar is a vector of handles to all toolbar icons.
% The handle to the "Zoom in" icon is the fifth in the array.  
h_toolbar = ud.h.toolbar; 
h_zoomin = h_toolbar(5);

% Because the 'OffCallBack' function is called after 
% 'OnCallBack' and 'ClickedCallBack', we are setting UD
% here to avoid the case where ud.toolbar.zoom is set 
% to 'none' if a user toggles between "Zoom in" and "Zoom out."
zoominState = get(h_zoomin,'State');
if strcmp(zoominState,'on'),
    ud.toolbar.zoom = 'zoomin';
    zoom(hFig,'inmode');
end

% Save current Zoom to UD
set(hFig,'UserData',ud);

%-------------------------------------------------------------------------
function zoomin_offcb(hcbo,eventStruct)
%ZOOMIN_OFFCB Callback for the "Zoom in" button whenever the 
%             state is changed to 'Off'.
%
% Inputs:
%   hcbo - handle of callback object (not being used)
%   hFig - handle of fdatool figure.

% Get the userdata stored in the figure
hFig = gcbf;
ud = get(hFig,'Userdata');

ud.toolbar.zoom = 'none';
zoom(hFig,'off');

% h_toolbar is a vector of handles to all toolbar icons.
% The handle to the "Zoom out" icon is the sixth 
% in the array.  
h_toolbar = ud.h.toolbar; 
h_zoomout = h_toolbar(6);

zoomoutState = get(h_zoomout,'State');
if strcmp(zoomoutState,'on'),
    ud.toolbar.zoom = 'zoomout';
    zoom(hFig,'outmode');
end

% Save current Zoom to UD
set(hFig,'UserData',ud);

%-------------------------------------------------------------------------
function zoom_clickedcb(hcbo, eventStruct)
%ZOOM_CLICKEDCB Callback for both the "Zoom in" and "Zoom out" buttons
%               every time the mouse is pressed and released.
%
% Inputs:
%   hcbo - handle of callback object (not being used)
%   hFig - handle of fdatool figure.

% Update the state of the zoom togglebuttons. 
hFig = gcbf;
update_toolbar('update_zoomtbstate',hFig);

%-------------------------------------------------------------------------
function filterspecs_cb(hcbo,eventStruct)
%FILTERSPECS_CB Callback for the Filter Specifications menu item
%               and pushbutton.
%
% Inputs:
%   hcbo - handle of callback object (not being used)
%   hFig - handle of fdatool figure.

% Get the userdata stored in the figure
hFig = gcbf;
ud = get(hFig,'Userdata');

% Cache current Analysis from UD
currentAnalysis = ud.toolbar.analysis;

% Update UD if Analysis has changed
if ~strcmp(currentAnalysis,'filterresponsespecs'),
    ud.toolbar.analysis = 'filterresponsespecs';
    set(hFig,'UserData',ud);
end

% Update the analysis plotting and the analysis menu
update_analysisframe(hFig);
update_menus('update_analysis',hFig);

% Enable the Zoom togglebuttons based on current analysis
update_toolbar('update_zoomenable',hFig);

%-------------------------------------------------------------------------
function magresp_cb(hcbo,eventStruct)
%MAGRESP_CB Callback for the Magnitude Response menu item 
%           and pushbutton.
%
% Inputs:
%   hcbo - handle of callback object (not being used)
%   hFig - handle of fdatool figure.

% Get the userdata stored in the figure
hFig = gcbf;
ud = get(hFig,'Userdata');

% Cache current Analysis from UD
currentAnalysis = ud.toolbar.analysis;

% Update UD if Analysis has changed
if ~strcmp(currentAnalysis,'magresp'),
    ud.toolbar.analysis = 'magresp';
    set(hFig,'UserData',ud);
end

% Update the analysis area and the analysis menu
update_analysisframe(hFig);
update_menus('update_analysis',hFig);

% Enable the Zoom togglebuttons based on current analysis
update_toolbar('update_zoomenable',hFig);

%-------------------------------------------------------------------------
function phaseresp_cb(hcbo,eventStruct)
%PHASERESP_CB Callback for the Phase Response menu item and pushbutton.
%
% Inputs:
%   hcbo - handle of callback object (not being used)
%   hFig - handle of fdatool figure.

% Get the userdata stored in the figure
hFig = gcbf;
ud = get(hFig,'Userdata');

% Cache current Analysis from UD
currentAnalysis = ud.toolbar.analysis;

% Update UD if Analysis has changed
if ~strcmp(currentAnalysis,'phaseresp'),
    ud.toolbar.analysis = 'phaseresp';
    set(hFig,'UserData',ud);
end
% Update the analysis area
update_analysisframe(hFig);
update_menus('update_analysis',hFig);

% Enable the Zoom togglebuttons based on current analysis
update_toolbar('update_zoomenable',hFig);

%-------------------------------------------------------------------------
function magnphaseresp_cb(hcbo,eventStruct)
%MAGNPHASERESP_CB Callback for the Magnitude and Phase Response 
%                 menu item and pushbutton.
%
% Inputs:
%   hcbo - handle of callback object (not being used)
%   hFig - handle of fdatool figure.

% Get the userdata stored in the figure
hFig = gcbf;
ud = get(hFig,'Userdata');

% Cache current Analysis from UD
currentAnalysis = ud.toolbar.analysis;

% Update UD if Analysis has changed
if ~strcmp(currentAnalysis,'magnphaseresp'),
    ud.toolbar.analysis = 'magnphaseresp';
    set(hFig,'UserData',ud);
end

% Update the analysis area
update_analysisframe(hFig);
update_menus('update_analysis',hFig);

% Enable the Zoom togglebuttons based on current analysis
update_toolbar('update_zoomenable',hFig);

%-------------------------------------------------------------------------
function groupdelay_cb(hcbo,eventStruct)
%GROUPDELAY_CB Callback for the Group Delay menu item and pushbutton.
%
% Inputs:
%   hcbo - handle of callback object (not being used)
%   hFig - handle of fdatool figure.

% Get the userdata stored in the figure
hFig = gcbf;
ud = get(hFig,'Userdata');

% Cache current Analysis from UD
currentAnalysis = ud.toolbar.analysis;

% Update UD if Analysis has changed
if ~strcmp(currentAnalysis,'groupdelay'),
    ud.toolbar.analysis = 'groupdelay';
    set(hFig,'UserData',ud);
end

% Update the analysis area
update_analysisframe(hFig);
update_menus('update_analysis',hFig);

% Enable the Zoom togglebuttons based on current analysis
update_toolbar('update_zoomenable',hFig);

%-------------------------------------------------------------------------
function impresp_cb(hcbo,eventStruct)
%IMPRESP_CB Callback for the Impluse Response menu item and pushbutton.
%
% Inputs:
%   hcbo - handle of callback object (not being used)
%   hFig - handle of fdatool figure.

% Get the userdata stored in the figure
hFig = gcbf;
ud = get(hFig,'Userdata');

% Cache current Analysis from UD
currentAnalysis = ud.toolbar.analysis;

% Update UD if Analysis has changed
if ~strcmp(currentAnalysis,'impresp'),
    ud.toolbar.analysis = 'impresp';
    set(hFig,'UserData',ud);
end

% Update the analysis area
update_analysisframe(hFig);
update_menus('update_analysis',hFig);

% Enable the Zoom togglebuttons based on current analysis
update_toolbar('update_zoomenable',hFig);

%-------------------------------------------------------------------------
function stepresp_cb(hcbo,eventStruct)
%STEPRESP_CB Callback for the Step Response menu item and pushbutton.
%
% Inputs:
%   hcbo - handle of callback object (not being used)
%   hFig - handle of fdatool figure.

% Get the userdata stored in the figure
hFig = gcbf;
ud = get(hFig,'Userdata');

% Cache current Analysis from UD
currentAnalysis = ud.toolbar.analysis;

% Update UD if Analysis has changed
if ~strcmp(currentAnalysis,'stepresp'),
    ud.toolbar.analysis = 'stepresp';
    set(hFig,'UserData',ud);
end

% Update the analysis area
update_analysisframe(hFig);
update_menus('update_analysis',hFig);

% Enable the Zoom togglebuttons based on current analysis
update_toolbar('update_zoomenable',hFig);

%-------------------------------------------------------------------------
function pzplot_cb(hcbo,eventStruct)
%PZPLOT_CB Callback for the Pole-Zero plot menu item and pushbutton.
%
% Inputs:
%   hcbo - handle of callback object (not being used)
%   hFig - handle of fdatool figure.

% Get the userdata stored in the figure
hFig = gcbf;
ud = get(hFig,'Userdata');

% Cache current Analysis from UD
currentAnalysis = ud.toolbar.analysis;

% Update UD if Analysis has changed
if ~strcmp(currentAnalysis,'pzplot'),
    ud.toolbar.analysis = 'pzplot';
    set(hFig,'UserData',ud);
end

% Update the analysis area
update_analysisframe(hFig);
update_menus('update_analysis',hFig);

% Enable the Zoom togglebuttons based on current analysis
update_toolbar('update_zoomenable',hFig);

%-------------------------------------------------------------------------
function filtercoeffs_cb(hcbo,eventStruct)
%FILTERCOEFFS_CB Callback for the Filter Coefficients menu item
%                and pushbutton.
%
% Inputs:
%   hcbo - handle of callback object (not being used)
%   hFig - handle of fdatool figure.

% Get the userdata stored in the figure
hFig = gcbf;
ud = get(hFig,'Userdata');

% Cache current Analysis from UD
currentAnalysis = ud.toolbar.analysis;

% Update UD if Analysis has changed
if ~strcmp(currentAnalysis,'filtercoeffs'),
    ud.toolbar.analysis = 'filtercoeffs';
    set(hFig,'UserData',ud);
end

% Update the analysis area
update_analysisframe(hFig);
update_menus('update_analysis',hFig);

% Enable the Zoom togglebuttons based on current analysis
update_toolbar('update_zoomenable',hFig);

%-------------------------------------------------------------------------
function mcode_cb(hcbo,eventStruct)
%MCODE_CB Callback for MATLAB Code Generation menu item and pushbutton.
%
% Inputs:
%   hcbo - handle of callback object (not being used)
%   hFig - handle of fdatool figure.

% Get the userdata stored in the figure
hFig = gcbf;
ud = get(hFig,'Userdata');

% Generate M-code based on the current mode.
switch ud.mode.current,
case 1, % Design
    fdcode = designmcode(hFig);
case 2, % Import
    fdcode = importmcode(hFig);
case 3, % Quantize
    fdcode = quantizemcode(hFig);
end

% Prepend the function header and footer
fdcode = addheaderNfooter(fdcode);

update_status(hFig,'Generating program...');    
tname = [tempname '.m'];  % Temporary file name.
fid = fopen(tname,'wt');
for i=1:size(fdcode,2),
    fprintf(fid,'%s\n',fdcode{:,i});
end
fclose(fid);
edit(tname);
update_status(hFig,'Ready');

%-------------------------------------------------------------------------
function fdcode = addheaderNfooter(fdcode)
% Prepend the header to the code string and append a program footer.

% M-file function name.
fcnName = 'filterdesign';

% M-file function header.
header = {['function [b,a] = ',fcnName,'(varargin)'],...
        '%FILTERDESIGN Design a filter...'};

% Time/date stampe for final portion of initial comment line:
d = {'%', ['%   Generated: ' datestr(now) '.']};

% M-file Footer.
footer ={'',['% [EOF] ',fcnName]};

fdcode = {header{:}, d{:}, fdcode{:}, footer{:}};

%-------------------------------------------------------------------------
function h = find_h(handles,tagStr)
%FIND_H Find the handle to the uicontrol with the tag tagStr.

tags = get(handles,'tag');
indx = find(strcmp(tags,tagStr));
h = handles(indx);

% ------------------------------------------------------------------------
function  status = save_if_dirty(hFig,action)
% SAVE_IF_DIRTY Query the user to save if GUI is dirty.
%
% Inputs:
%     hFig - handle to the figure.
%     action - 'closing', or 'loading' file.
% Output:
%     status = 1 if Yes, No, or UIs not dirty.
%     status = 0 if Cancel.
%

% Get userdata
ud = get(hFig,'userdata');

if ~ud.flags.file_dirty,
   status = 1;       % Proceed as normal
   return
end

% Removes the path and any extension
[path, file] = fileparts(ud.filename.session);

% If changes have not been saved, warn (prompt) user

ansBtn = questdlg({sprintf('Save %s session before %s?',file,action)},'FDATool','Cancel');

switch ansBtn,
case 'Yes',
   status = 1;
   %   save2file(ud.filename.session,hFig);  
   file = ud.filename.session;
   [filename,pathname] = fduiputfile(file,'Save Filter Design Session');
   file = [pathname filename];

if filename ~= 0       
   save2file(file,hFig);
end
case 'No'
   status = 1;
   % User didn't save, reset dirty flag so opened file is not dirty
   ud.flags.file_dirty = 0;
   set(hFig,'userdata',ud);
case 'Cancel'        
   status = 0;
end

% ------------------------------------------------------------------------
function [f,p] = fduiputfile(initFile,dlgboxTitle)   
% FDUIPUTFILE The following is a workaround for uiputfile which works
%               differently on the PC and UNIX.
%
% Inputs: 
%    initFile - determines the initial display of files in the dialog box.
%    dlgboxTitle - is a string containing the title of the dialog box.
% Ouputs: 
%    f - file name with extension .mat.
%    p - path to file.

[f,p] = uiputfile(initFile,dlgboxTitle);

if ~isequal(f,0) & isempty(findstr(f,'.fda')),
   
   % uiputfile DOES NOT automatically add 
   % extensions to file names
   if isempty(findstr(f,'.'))
      % no '.' extension, so add '.fda' to file name
      f = [f '.fda'];
   end
end   

%------------------------------------------------------------------------
function save2file(file,hFig)
%SAVE2FILE   Save all necessary session info. to a file.

% Get userdata
ud = get(hFig,'userdata');

% Unset the dirty flag
ud.flags.file_dirty = 0;
   
% Unix returns a path that sometimes includes two paths (the
% current path followed by the path to the file) seperated by '//'.
% Remove the first path.
indx = findstr(file,[filesep,filesep]);
if ~isempty(indx)
    file = file(indx+1:end);
end

ud.filename.session = file;
ud.flags.overwrite = 1;      % Allow file overwrites from now on
set(hFig,'userdata',ud);
update_titlebar(hFig);

fdspecs              = ud.specs.design;
analysis_mode        = ud.toolbar.analysis;
import_specs         = ud.specs.import;
export_specs         = ud.specs.export;
convert_specs        = ud.specs.convert;
reference_filt       = ud.reffilter;
current_filt         = ud.filter;
mode                 = ud.mode;
filter_designed      = ud.flags.filter_designed;
filter_imported      = ud.flags.filter_imported;
strs2save = {...
        'fdspecs',...
        'analysis_mode',...
        'import_specs',...
        'export_specs',...
        'convert_specs',...
        'reference_filt',...
        'current_filt',...
        'mode',...
        'filter_designed',...
        'filter_imported'};
if ud.flags.fdqexists,
    filter_quantized     = ud.flags.filter_quantized;
    quantizationswitch   = ud.flags.quantizationswitch;
    quantize_specs       = ud.specs.quantize;
    strs2save = {strs2save{:},...
            'filter_quantized',...
            'quantizationswitch',...
            'quantize_specs'};    
end

try
    save(file,...
        strs2save{:});
catch
    errStr = ['An error occurred while saving the session file.  ',...
            'Make sure the file is not Read-only and you have ',...
            'permission to write to that directory.'];
    lasterr(errStr);
    fdatoolerror(hFig);
end


% [EOF] menus_cbs.m
