function update_exportdlg(fcn, hFig)
% UPDATE_EXPORTDLG  Update the uicontrols on the "Export" dialog (figure). 
%
% Inputs:
%   fcn  - Local update function 
%   hFig - Handle to the Filter Design GUI figure.

%   Author(s): P. Costa 
%   Copyright 1988-2000 The MathWorks, Inc.
%   $Revision: 1.15 $  $Date: 2000/06/13 21:41:00 $ 

ud = get(hFig,'UserData');

% Check that the "Export" dialog exists.
if isfield(ud.h,'dlgs') & isfield(ud.h.dlgs,'export') & ...
        ishandle(ud.h.dlgs.export),  
    hExportdlg = ud.h.dlgs.export;
    feval(fcn, hFig, hExportdlg);
end


%-------------------------------------------------------------------------
function update_all(hFig,hExportdlg);
% UPDATE_ALL Calls all the update (local) functions to update the Export
%            dialog.
%
% Inputs:
%    hFig       - Handle to the Filter Design GUI figure.
%    hExportdlg - Handle to the Export Coefficients dialog.
%

update_exportToFr(hFig, hExportdlg);      % Update the "Export To" frame.
update_exportcoeffFr(hFig, hExportdlg);   % Update the "Variable Names" frame.
update_overwriteVarChk(hFig, hExportdlg); % Update the Variable collision checkbox.
update_ctrlbtns(hExportdlg);              % Update the "Control" buttons.
update_visibility(hExportdlg);            % Update the "Export" dialog (figure)
                                          % called last to minimize flickering.

                                          
%-------------------------------------------------------------------------
function update_exportToFr(hFig,hExportdlg)
%UPDATE_EXPORTTOFR Update the "Export To" frame and popupmenu.
%
% Inputs:
%    hFig       - Handle to the Filter Design GUI figure.
%    hExportdlg - Handle to the Export Coefficients dialog.

fdatoolud = get(hFig,'Userdata');
exportud  = get(hExportdlg,'Userdata');

% Turn on the visiblity of the frame and popup.
h_popup = exportud.h.exportto.popup;
h_exportToFr = [exportud.h.exportto.frame, h_popup];
set(h_exportToFr,'Visible','On');

% Cache "Export To" options (from the popupmenu)
exportToStrs = get(h_popup,'String');

% Cache "Export To" option from FDATool's UserData
currentExportTo = fdatoolud.specs.export.exportto;

% Setting the Export To popupmenu 'String' (based on 
% the ud structure)
indx = find(strcmpi(currentExportTo,exportToStrs));
set(h_popup,'Value',indx);

% Set the appropriate UI Enable/BackgroundColor within this frame.
setExportUisEnable(hFig, hExportdlg)


%-------------------------------------------------------------------------
function update_exportcoeffFr(hFig,hExportdlg)
%UPDATE_EXPORTCOEFFFR Update the "Variable Names" frame and uicontrols.
%
% Inputs:
%    hFig       - Handle to the Filter Design GUI figure.
%    hExportdlg - Handle to the Export Coefficients dialog.
%
% Updates the frame, labels and number of edit boxes in the "Variable
% Names" frame.

% Export dialog UserData structure
fdatoolud = get(hFig,'UserData');
exportud  = get(hExportdlg,'UserData');

% Turn on the visiblity of the "Variable Names" frame
h_varNameFr = exportud.h.exportcoeffuis.frame;
set(h_varNameFr,'Visible','On');

% Cache the handles to all the coefficient labels and edit boxes.
h_coeffLbls = exportud.h.exportcoeffuis.lbls;

h_varNamesUis = exportud.h.exportcoeffuis.editboxes;

% Cache current Filter Structure string.
filtstruct = getfilterstructure(fdatoolud.filter);

% Get the edit box labels.
switch filtstruct,
case {'df1','df2','df1t','df2t','dffir','dftfir','dfsymfir','dfasymfir'},  
    lblStrs = getTflblStrs(fdatoolud.filter);
    
case 'ssd',                 lblStrs = {'A matrix:','B matrix:','C vector:','D vector:'};
case 'latcallpass',         lblStrs = {'Lattice coeff:'};
case 'latcma',              lblStrs = {'Lattice coeff:'};
case 'latcmax',             lblStrs = {'Lattice coeff:'};
case 'latcarma',            lblStrs = {'Lattice coeff:','Ladder coeff:'};
case {'latcca','latccapc'}, lblStrs = {'Numerator:','Denominator:'};
case 'Quantized filter (Qfilt object)',  lblStrs = {'Quantized filter:'};
otherwise
    lblStrs = {'Numerator:','Denominator:'};
end

% Get the coefficient variable names
coeffStrs = getCoeffStrs(hFig);

% Set the visibity of the coefficient labels and edit boxes.
setLblStrNVis(h_coeffLbls,lblStrs,h_varNamesUis); 
setVarStrsNVis(h_varNamesUis,coeffStrs); 


%-------------------------------------------------------------------------
function update_overwriteVarChk(hFig,hExportdlg)
%UPDATE_VARIABLECHK Update the "Variable Names" frame and uicontrols.
%
% Inputs:
%    hFig       - Handle to the Filter Design GUI figure.
%    hExportdlg - Handle to the Export Coefficients dialog.

fdatoolud = get(hFig,'Userdata');
exportud  = get(hExportdlg,'UserData');

% Turn on the visiblity of the checkbox.
h_chkBox = exportud.h.overwritechk;
set(h_chkBox,'Enable','On',...
    'Visible','On');

% Cache checkbox value from FDATool's UserData
chkBoxVal = fdatoolud.specs.export.overwritechk;

% Setting the checkbox value (based on fdatoolud)
set(h_chkBox,'Value',chkBoxVal);

% Checkbox only enabled for "Workspace" option from
% the "Export To" popupmenu
popupVal = get(exportud.h.exportto.popup,'Value');
if ~(popupVal == 1),
    set(h_chkBox,'Enable','Off');    
end


%-------------------------------------------------------------------------
function update_ctrlbtns(hExportdlg)
%UPDATE_CTRLBTNS Update the "Control" buttons.
%
% Input:
%    hExportdlg - Handle to the Export Coefficients dialog.
%
% Used only to set the 'Enable' property of the "Apply" 
% control button. 

exportud  = get(hExportdlg,'UserData');

% exportud.h.ctrlbtns contains handles to the three control 
% buttons (i.e., OK, Cancel, and Apply)
set(exportud.h.ctrlbtns(3),'Enable','On');


%-------------------------------------------------------------------------
function update_visibility(hExportdlg)
%UPDATE_VISIBILITY Update the "Export" dialog visibility.
%
% Input:
%    hExportdlg - Handle to the Export Coefficients dialog (figure).

set(hExportdlg,'Visible','On');


%-------------------------------------------------------------------------
function exportFilter(hFig, hExportdlg)
%EXPORTFILTER - Exports the filter coefficients from FDATool.
%
% Inputs:
%   hFig       - Handle to the Filter Design GUI figure.
%   hExportdlg - Not used.
%

% FDATool's UserData structure (used for coeffStrs)
fdatoolud = get(hFig,'UserData');

% String with the current "Export To" target (e.g. workkspace)
exportToOption = fdatoolud.specs.export.exportto;

switch exportToOption,
case 'Workspace',  export2wkspace(hFig,hExportdlg);
case 'Text-file',  export2file(hFig, 'text');
case 'MAT-file',   export2file(hFig, 'mat');
end


%-------------------------------------------------------------------
%                       Utility Functions
%-------------------------------------------------------------------
function lblStrs = getTflblStrs(fdatoolud_filter);
% GETTFLBLSTRS Get Transfer function Label strings.
%
% Input:
%   fdatoolud_filter - Filter object stored in FDATool's UD.


% If filter is in SOS form, export the SOS matrix
if issos(fdatoolud_filter) & nsections(fdatoolud_filter) > 1,
    lblStrs = {'SOS matrix:','Gain:'};
else
    lblStrs = {'Numerator:','Denominator:'};     
end

    
%-------------------------------------------------------------------
function setLblStrNVis(h_coeffLbls,lblStrs,h_varNamesUis)
%SETLBLSTRNVIS Set label strings and visibility (coefficient labels).
%
% Inputs:
%   h_coeffLbls - Handles to the coefficient labels (Text uicontrols).
%   lblStrs     - Cell array of strings for the coefficient labels.
%   varStrs     - Cell array of variable strings (for the edit boxes).

% Turn off the 'Visibility' of all applicable uicontrols.
set(h_coeffLbls,'Visible','Off');

% Set the label String, Position and Visiblity.
for n = 1:length(lblStrs),
    setStrNPos(h_coeffLbls(n), lblStrs{n},h_varNamesUis);
    set(h_coeffLbls(n),'Visible','On');
end


%-------------------------------------------------------------------------
function setVarStrsNVis(h_varNamesUis,varStrs); 
%SETVARSTRNVIS Set variable strings and visiblity (coefficient edit boxes).
%
% Inputs:
%   h_varNamesUis  - Handles to the coefficient edit boxes.
%   varStrs        - Cell array of default variable strings.

sz = gui_sizes;

% Turn off the 'Visibility' of all applicable uicontrols.
set(h_varNamesUis,'Visible','Off');

% Set the default coefficient variable strings.
for n = 1:length(varStrs),
    set(h_varNamesUis(n),'String',varStrs{n},...
    'Visible','On');
end


%-------------------------------------------------------------------------
function setStrNPos(h_coeffLbls,newStr,h_varNamesUis)
% SETSTRNPOS Set String and Position of the cofficient labels.
%
% Inputs:
%  h_coeffLbls   - Handles to the coefficient labels (Text uicontrols).
%  newStr        - New strings for the text uicontrols.
%  h_varNamesUis - Handles to the coefficient edit boxes.

sz = gui_sizes;
width = largestuiwidth({newStr},'text');
originalUiPos = get(h_coeffLbls,'Position');

% Set new string and position of the labels.
set(h_coeffLbls,'String',newStr,...
    'Position',...
    [originalUiPos(1) originalUiPos(2) width originalUiPos(4)]);


%-------------------------------------------------------------------------
function export_variables2wksp(hFig,ws)
% EXPORT_VARIABLES2WKSP Export the variables to the MATLAB workspace.
%
% Inputs:
%    hFig  - Handle to the Filter Design GUI figure.
%    ws    - Workspace to assign variables.

fdatoolud = get(hFig,'UserData');

% Get the current (TF) filter coefficient strings
coeffStrs = getCoeffStrs(hFig);

filtStruct = getfilterstructure(fdatoolud.filter);
switch filtStruct,
case {'df1','df2','df1t','df2t','dffir','dftfir','dfsymfir','dfasymfir'},    
    
    % Get the coeffs. from the object in ud
    coeffVals = extractTFcoeffs(fdatoolud.filter);
    
case 'ssd',
    [coeffVals{1},coeffVals{2}, coeffVals{3},...
            coeffVals{4}] = ss(fdatoolud.filter);
    
case 'latcallpass',    
    % Only K (Lattice coeff.) is valid.
    coeffStrs = coeffStrs(1);
    coeffVals{1} = lattice(fdatoolud.filter); 
    
case 'latcma'
    coeffStrs = coeffStrs(1);
    coeffVals{1} = lattice(fdatoolud.filter);
    
case 'latcmax'
    coeffStrs = coeffStrs(1);
    coeffVals{1} = lattice(fdatoolud.filter);
    
case 'latcarma',
    [coeffVals{1},coeffVals{2}] = lattice(fdatoolud.filter);
    
case {'latcca','latcapc'},
    % Currently exporting b & a for lattice coupled-allpass structures 
    [coeffVals{1},coeffVals{2}] = tf(fdatoolud.filter); 
    
case 'Quantized filter (Qfilt object)', 
    coeffVals = fdatoolud.filter;
otherwise
    % For example: "Parallel Filter"
    [coeffVals{1},coeffVals{2}] = tf(fdatoolud.filter); 
end    

% Assign the Filter coefficients into the MATLAB workspace.
try,
    if isa(fdatoolud.filter,'qfilt')
        assignin(ws,char(coeffStrs), coeffVals)
    else        
        for n = 1:length(coeffStrs),
            assignin(ws,char(coeffStrs{n}), coeffVals{n});
        end
    end
catch,
    fdatoolerror(hFig);
end


%-------------------------------------------------------------------
function coeffVals = extractTFcoeffs(fdatoolud_filter)
% EXTRACTTFCOEFFS Extract Transfer Function Coefficients
%
% Input:
%   fdatoolud_filter - Filter object stored in FDATool's UD.
%
% Output:
%   coeffVals - Filter coefficients from the dfilt object .

if issos(fdatoolud_filter) & nsections(fdatoolud_filter) > 1,
    c = coefficients(fdatoolud_filter);
    [coeffVals{1}, coeffVals{2}] = cell2sos(c);
else
    [coeffVals{1}, coeffVals{2}] = tf(fdatoolud_filter); 
end


%-------------------------------------------------------------------
function [varsExist, existMsg] = chkIfVarExistInWksp(coeffStrs);
% CHKIFVAREXISTINWKSP Check if the variables exist in the workspace.
%
% Input:
%   coeffStrs - Filter Structure specific coefficient strings stored
%               in FDATool's UserData.
%
% Ouptuts:
%   varsExist - Boolean flag to indicate if variables exist in the
%               MATLAB workspace.
%   existMsg  - Warning dialog string to let the user know that their
%               variable(s) already exists.             

varsExist = 0;
existMsg = '';

for n = 1:length(coeffStrs),
    % Using the evaluatevars function since the "exist" function cannot be made
    % to look in the base MATLAB workspace.  
    [vals, errStr] = evaluatevars(coeffStrs{n}); 
    
    % Put up a message if the variables exist
    if ~isempty(vals),
        varsExist = 1;
        existMsg = ['The variable ' coeffStrs{n} ' already exists in the MATLAB workspace.'];
        return; % Return immediately after finding the first existing variable
    end
end


%-------------------------------------------------------------------
function coeffStrs = getCoeffStrs(hFig);
% GETCOEFFSTRS Get the Filter Structure specific coefficient variable names
%
% Input:
%   hFig  - Handle to the Filter Design GUI figure.
%
% Output:
%   coeffStrs - A cell arrary of user defined variable names (strings)
%               for the coefficient stored in FDATool's UserData.

fdatoolud = get(hFig,'UserData');

filtStruct = getfilterstructure(fdatoolud.filter);
switch filtStruct,
case {'df1','df2','df1t','df2t','dffir','dftfir','dfsymfir','dfasymfir'}, 
    % If filter is in SOS form, export the SOS matrix
    if issos(fdatoolud.filter)  & nsections(fdatoolud.filter) > 1,
        fsStrs = 'sosVarStrs';
    else
        fsStrs = 'tfVarStrs';
    end
case 'ssd',                             fsStrs = 'ssVarStrs';
case 'latcallpass',                     fsStrs = 'latcapsVarStrs';
case 'latcma',                          fsStrs = 'latcmaminVarStrs';
case 'latcmax',                         fsStrs = 'latcmamaxVarStrs';
case 'latcarma',                        fsStrs = 'latcarmaVarStrs';
case {'latcca','latccapc'},             fsStrs = 'tfVarStrs';
case 'Quantized filter (Qfilt object)', fsStrs = 'quantizedVarStrs';
otherwise
    fsStrs = 'tfVarStrs';
end

% Build the filter structure leg name in fdatoolud 
buildUDStr= ['fdatoolud.specs.export.' fsStrs];

% Get the variable names (cell array)
coeffStrs = eval(buildUDStr);


%---------------------------------------------------------------------
function export2wkspace(hFig, hExportdlg)
%EXPORT2WKSPACE Export Coefficients to the MATLAB Workspace.  
%
% Inputs:
%   hFig       - Handle to the Filter Design GUI figure.
%   hExportdlg - Handle to the Export Coefficients dialog (figure).

fdatoolud = get(hFig,'UserData');

% Reset the "Export Warning Occurred" flag.
fdatoolud.flags = ...
    setfield(fdatoolud.flags,'exportwarnoccurred',0);

% Get the Filter Structure specific coefficient variable names.
coeffStrs = getCoeffStrs(hFig);

% Message to be displayed in the command window. 
exportMsg = 'Filter coefficients have been exported to the workspace.';

% Boolean flag indicating whether or not to overwrite existing variables
overwriteVars = fdatoolud.specs.export.overwritechk;

% Check if the variables exist in the workspace.
[varsExist, existMsg] = chkIfVarExistInWksp(coeffStrs);

set(hFig,'UserData',fdatoolud);

if ~overwriteVars & varsExist,
    % Variables exist, put up a warning dialog and set the
    % flag to not close the dialog.
    lastwarn(existMsg);
    
    % fdatoolwarning adds the dialog handle to ud.h.dlgs
    fdatoolwarning(hFig);
    fdatoolud = get(hFig,'UserData');
    fdatoolud.flags = ...
        setfield(fdatoolud.flags,'exportwarnoccurred',1);
    set(hFig,'UserData',fdatoolud);
else
    export_variables2wksp(hFig,'base');
    disp(exportMsg);
end



%---------------------------------------------------------------------
function export2file(hFig, fileType)
%EXPORT2FILE Export filter coefficients to a file (MAT or Text).
%
% Inputs:
%   hFig      - Handle to the Filter Design GUI figure.
%   fileType  - String describing the file type to export (MAT or Text).

switch fileType,
case 'text',
    file = 'untitled.txt';
    dlgStr = 'Export Filter Coefficients to a Text-file';
case 'mat',
    file = 'untitled.mat';
    dlgStr = 'Export Filter Coefficients to a MAT-file';
end

% Put up the file selection dialog
[filename, pathname] = fduiputfile(file,dlgStr);
file = [pathname filename];

% filename is 0 if "Cancel" was clicked.
if filename ~= 0,
    if strcmpi(fileType,'mat'),
        save2matfile(file,hFig);
    else
        save2textfile(file,hFig);
    end
end


%------------------------------------------------------------------------
function save2matfile(f_i_l_e, hFig)
%SAVE2MATFILE Save filter coefficients to a MAT-file
%
% Inputs:
%   f_i_l_e - String containing the MAT-file name.
%   hFig    - Handle to the Filter Design GUI figure.


fdatoolud = get(hFig,'UserData');

% 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(f_i_l_e,[filesep,filesep]);
if ~isempty(indx)
    f_i_l_e = f_i_l_e(indx+1:end);
end

% Export the cofficients (Names and Values) to this function's
% (save2matfile) workspace
export_variables2wksp(hFig,'caller');

% Get the user defined variable names. NOTE: since the variable
% names and values where exported to this function's workspace, we 
% made the local variable names obscure (c_O_f_F_n_M_e & f_i_l_e) 
% to avoid a potential collision.
c_O_f_F_n_M_e = getCoeffStrs(hFig); 

% Create the MAT-file
save(f_i_l_e,c_O_f_F_n_M_e{:});


%------------------------------------------------------------------------
function save2textfile(file, hFig)
%SAVE2TEXTFILE Save filter coefficients to a Text-file
%
% Inputs:
%   file  - String containing the Text-file name.
%   hFig  - Handle to the Filter Design GUI figure.


fdatoolud = get(hFig,'UserData');

% 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

% Get the filter coefficients for display
coeffStr = dispstr(fdatoolud.filter);

% Write the coefficients out to a -file.
[m,n] = size(coeffStr);
fid = fopen(file,'w');
for p = 1:m,
    fprintf(fid, '%s\n', coeffStr(p,:));
end
fclose(fid);

% Launch the MATLAB editor (to display the coefficients)
edit(file);


%------------------------------------------------------------------------
function [f,p] = fduiputfile(initFile,dlgboxTitle)   
% FDUIPUTFILE FDATOOL's version of the uiputfile function
% 
%  The function is a workaround for uiputfile's behavior which is
%  different 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.
%
% Outputs: 
%    f - file name with extension .mat.
%    p - path to file.

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

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


%-------------------------------------------------------------------------
function setExportUisEnable(hFig, hExportdlg)
% SETEXPORTUISENABLE Set the Enable/BackgroundColor properties for the
%                    uicontrols within the Export To frame.
%
% Inputs:
%   hFig       - Handle to the Filter Design GUI figure.
%   hExportdlg - Handle to the Export Coefficients dialog (figure).

fdatoolud = get(hFig,'UserData');
exportdlgud  = get(hExportdlg,'UserData');

% Current Export To selection
exportToOption = fdatoolud.specs.export.exportto;

hchkbox = exportdlgud.h.overwritechk;
heboxes = exportdlgud.h.exportcoeffuis.editboxes;

switch exportToOption,
case 'Workspace',
    set(hchkbox,'Enable','On');
    set(heboxes,'Enable','On','BackgroundColor','White');
case 'Text-file',
    set([hchkbox heboxes],'Enable','Off','BackgroundColor',[.8 .8 .8]);
case 'MAT-file',
    set(hchkbox,'Enable','Off');
    set(heboxes,'Enable','On','BackgroundColor','White');
end


% [EOF] update_exportdlg.m
