function update_convertdlg(fcn, hFig)
%UPDATE_CONVERTDLG  Update the uicontrols on the "Convert" dialog. 
%
% 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.13 $  $Date: 2000/06/15 20:04:54 $ 

ud = get(hFig,'UserData');

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

%-------------------------------------------------------------------------
function update_all(hFig,hConvertdlg);
%UPDATE_ALL Calls all the update (local) functions to update the Convert
%            dialog.

update_convertToFr(hFig, hConvertdlg); % Update the "Convert To" frame.
update_sosFr(hFig, hConvertdlg);       % Update the "Second-order sections" frame.
update_soschk(hFig, hConvertdlg);      % Update the SOS checkbox.
update_visibility(hConvertdlg);        % Update the "Convert" dialog visibility
                                       % called last to minimize flickering.

                                       
%-------------------------------------------------------------------------
function update_convertToFr(hFig,hConvertdlg)
%UPDATE_CONVERTTTOFR Update the "Convert To" frame and Listbox.
%
% Inputs:
%    hFig        - Handle to the Filter Design GUI figure.
%    hConvertdlg - Handle to the Convert dialog (figure).

fdatoolud = get(hFig,'Userdata');
convertud  = get(hConvertdlg,'Userdata');

% Turn on the visiblity of the frame and listbox.
h_listbox = convertud.h.convertto.listbox;
h_convertToFr = [convertud.h.convertto.frame, h_listbox];
set(h_convertToFr,'Visible','On');

% Get the "Convert To" listbox strings
convertToStrs = getconvertstructchoices(hFig);

% Cache the current "Quantized" or "Double" convert to option 
if fdatoolud.flags.fdqexists & fdatoolud.flags.quantizationswitch,
    currentConvertTo = fdatoolud.specs.convert.qconvertto;
else    
    currentConvertTo = fdatoolud.specs.convert.dconvertto;
end

% Setting the "Convert To" listbox current selection 
indx = find(strcmpi(currentConvertTo,convertToStrs));

% Set a default filter structure if the current "Convert To" 
% structure no longer exists in the listbox.
if isempty(indx),
    indx = setconvertlistboxindx(hFig);
end

set(h_listbox,'String',convertToStrs,...
    'Value',indx);


%-------------------------------------------------------------------------
function update_sosFr(hFig,hConvertdlg)
%UPDATE_SOSFR Update the "Second-order sections" frame and uicontrol.
%
% Inputs:
%    hFig        - Handle to the Filter Design GUI figure.
%    hConvertdlg - Handle to the Convert dialog (figure).

fdatoolud = get(hFig,'UserData');
convertud  = get(hConvertdlg,'UserData');

% Turn on the visiblity of the "Scaling" frame
h_sosFr = convertud.h.sosscale.frame;
set(h_sosFr,'Visible','On');

% Cache the handles to the label and popupmenu.
h_lblNpopup = convertud.h.sosscale.lblNpopup;

% Cache "Scale:" option (from the popup)
scaleStrs = get(h_lblNpopup(2),'String');

% Cache "Scale" option from FDATool's UserData
currentScale = fdatoolud.specs.convert.sosScale;

% Setting the Scale popupmenu selection (based on ud) 
indx = find(strcmpi(currentScale,scaleStrs));
set(h_lblNpopup(2),'Value',indx);

% Enable the SOS scale popupmenu based SOS checkbox.
enableSosfromChk(convertud);


%-------------------------------------------------------------------------
function update_soschk(hFig,hConvertdlg)
%UPDATE_SOSCHK Update the "Use second-order sections" checkbox.
%
% Inputs:
%    hFig        - Handle to the Filter Design GUI figure.
%    hConvertdlg - Handle to the Convert dialog (figure).

fdatoolud = get(hFig,'UserData');
convertdlgud  = get(hConvertdlg,'UserData');

% Handle to the SOS checkbox.
h_soschk = convertdlgud.h.convertto.soschkbox;
soschkPos = get(h_soschk,'Position');

% Get the listbox position so the checkbox can follow its X position.
h_listbox = convertdlgud.h.convertto.listbox;
listboxPos = get(h_listbox,'Position');

% Set the checkbox based value and visiblity.
chkBoxVal = fdatoolud.specs.convert.soschkbox;
set(h_soschk,'Value',chkBoxVal,...
    'Visible','On',...
    'Position',[listboxPos(1) soschkPos(2) soschkPos(3) soschkPos(4)]);

% Enable the SOS scale popupmenu based on the checkbox.
enableSosfromChk(convertdlgud);


%-------------------------------------------------------------------------
function update_ctrlbtns(hFig, hConvertdlg)
%UPDATE_CTRLBTNS Update the "Control" buttons.
%
% Input:
%   hFig        - Not used.
%   hConvertdlg - Handle to the Convert filter structure dialog (figure).
%
% Currently NOT used.

convertud  = get(hConvertdlg,'UserData');


%-------------------------------------------------------------------------
function update_visibility(hConvertdlg)
%UPDATE_VISIBILITY  Update the "Convert" dialog visibility.
%
% Input:
%   hConvertdlg - Handle to the Convert filter structure dialog (figure).

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


%-------------------------------------------------------------------------
function convertFilter(hFig,hConvertdlg)
%CONVERTFILTER Convert the current filter's structure.
%
% Inputs:
%   hFig        - Handle to the Filter Design GUI figure.
%   hConvertdlg - Handle to the Convert filter structure dialog (figure).
%

w = warning;    % Current warning state
warning('off');
lasterr('');
lastwarn('');

% Convert the filter structure and store it back in FDATool's UD
try
    convertFilterStructure(hConvertdlg, hFig);
catch
    fdatoolerror(hFig);
    return; % Avoid further processing
end

if ~isempty(lastwarn),
    fdatoolwarning(hFig);
    return;
end

warning(w); % Reset the warning state

% Update the Analysis plot and the current filter information frame.
update_analysisframe(hFig);
update_currentfilterinfo('update_all',hFig);

% Keep convert dialog box on top.
figure(hConvertdlg);  

% Update the export dialog, if it exists.
update_exportdlg('update_all',hFig);

%-------------------------------------------------------------------
%                       Utility Functions
%-------------------------------------------------------------------
function enableSosfromChk(convertdlgud);
% ENABLESOSFROMCHK Enable the SOS scale label and popupmenu
%                  based on the "Use second-order sections checkbox.
%                
% Input:
%   convertdlgud - Convert dialog UserData structure 

chkVal = get(convertdlgud.h.convertto.soschkbox,'Value');
bgc = get(convertdlgud.h.fig.convertdlg,'Color');

if chkVal,
    set(convertdlgud.h.sosscale.lblNpopup,'Enable','On');
    set(convertdlgud.h.sosscale.lblNpopup(2),'BackgroundColor','White');
else
    set(convertdlgud.h.sosscale.lblNpopup,'Enable','Off');
    set(convertdlgud.h.sosscale.lblNpopup,'BackgroundColor',bgc);
end


%-------------------------------------------------------------------
function convertFilterStructure(hConvertdlg, hFig)
% CONVERTFILTERSTRUCTURE Convert the filter structure of the filter object
%                        found in fdatoolud.filter.
%                      
% Inputs:
%   hConvertdlg - Handle to the Convert dialog (figure).
%   hFig        - Handle to the Filter Design GUI figure.
%

convertdlgud = get(hConvertdlg,'UserData');
fdatoolud = get(hFig,'UserData');

% Get the new filter structure (string).
struct2bconverted = fdatoolud.specs.convert.dconvertto; 

% If the Quantization switch is on,
if fdatoolud.flags.fdqexists & fdatoolud.flags.quantizationswitch,
    struct2bconverted = fdatoolud.specs.convert.qconvertto; 
end

% Get the new filter structure name for the filter object.
newfilterStr = getFiltStructStr(struct2bconverted, fdatoolud.filter);

% Get the "Use second-order sections" checkbox value.
sosChecked = fdatoolud.specs.convert.soschkbox;

% Always use the reference filter to convert to a new structure.
convertreffilter(hFig);

% Convert ud.filter to a new filter object with the new filter structure.
% Returns early if converting to the same structure.
if ~strcmpi(newfilterStr,filterstructure(fdatoolud.filter)),
        fdatoolud.filter = convert(fdatoolud.filter,newfilterStr);
end
% Convert dfilt or qfilt to SOS form.
if sosChecked,
    fdatoolud.filter = convert2SOS(fdatoolud.filter,convertdlgud);
end
set(hFig,'UserData',fdatoolud);

% update_quantizeparams changes fdatoolud.
if sosChecked & isa(fdatoolud.filter,'qfilt')
    % Update the scalevalues
    update_quantizeparams('scalevalues',hFig);
end

fdatoolud = get(hFig,'UserData');
% Log the session as dirty and save FDATool's UserData structure.
fdatoolud.flags.file_dirty = 1;
update_titlebar(hFig);
set(hFig,'UserData',fdatoolud);


%-------------------------------------------------------------------------
function convertreffilter(hFig)
% Convert the reference filter stored in the figure's userdata to a 
% quantized or un-quantized filter depending on the quantization switch.

ud = get(hFig,'Userdata');

if ud.flags.fdqexists & ud.flags.quantizationswitch,
    update_status(hFig,'Quantizing filter...');
    % Quantize the dfilt object. Returns early if it's a qfilt object.
    ud.filter = dfilt2qfilt(ud.reffilter,ud.specs.quantize.refqfilt);
else
    % Convert to a dfilt object and assigns ud.reffilt to ud.filter.
    % Returns early if it's a dfilt object.
   ud.filter = qfilt2dfilt(ud.reffilter);
end

set(hFig,'UserData',ud);

%-------------------------------------------------------------------
function str = getFiltStructStr(struct2bconverted, fdatoolud_filter)
% GETFILTSTRUCTSTR Get the constructor name for the new Filter Structure.
%                      
% Inputs:
%   struct2bconverted - Spelled out filter structure (string) to be converted,
%                       e.g. Transposed direct form II or Lattice MA (min. phase).
%   fdatoolud_filter  - Current filter stored in the fdatoolud.filter
%
% Output:
%   str - Valid filter string for converting either a dfilt or qfilt object. 


if isa(fdatoolud_filter,'qfilt'),
    switch struct2bconverted,
    case 'Direct form I',                 str = 'df1';
    case 'Direct form II',                str = 'df2';
    case 'Direct form I transposed',      str = 'df1t';
    case 'Direct form II transposed',     str = 'df2t';
    case 'Direct form FIR',               str = 'fir';
    case 'Direct form FIR transposed',    str = 'firt';
    case 'Direct form symmetric FIR',     str = 'symmetricfir';
    case 'Direct form antisymmetric FIR', str = 'antisymmetricfir';
    case 'Lattice allpass',               str = 'latcallpass';    
    case 'Lattice AR',                    str = 'latticear'; 
    case 'Lattice MA max. phase',         str = 'latticema';
    case 'Lattice MA min. phase',         str = 'latcmax';  
    case 'Lattice ARMA',                  str = 'latticearma';
    case 'Lattice coupled-allpass',       str = 'latticeca';
    case 'Lattice coupled-allpass power-complementary',  str = 'latticecapc';
    case 'State-space',                   str = 'statespace';
    end    
else
    switch struct2bconverted,
    case 'Direct form I',                 str = 'df1';
    case 'Direct form II',                str = 'df2';
    case 'Direct form I transposed',      str = 'df1t';
    case 'Direct form II transposed',     str = 'df2t';
    case 'Direct form FIR',               str = 'dffir';
    case 'Direct form FIR transposed',    str = 'dftfir';
    case 'Direct form symmetric FIR',     str = 'dfsymfir';
    case 'Direct form antisymmetric FIR', str = 'dfasymfir';
    case 'Lattice allpass',               str = 'latcallpass';
    case 'Lattice MA min. phase',         str = 'latcma';
    case 'Lattice MA max. phase',         str = 'latcmax';
    case 'Lattice ARMA',                  str = 'latcarma';
    case 'Lattice coupled-allpass',       str = 'latcca';    
    case 'Lattice coupled-allpass power-complementary',  str = 'latccapc';    
    case 'State-space',                   str = 'ssd';
    end
end


%-------------------------------------------------------------------
function filterObject = convert2SOS(filterObject, convertdlgud)
% CONVERT2SOS Convert to Second-order sections form.
%
% Inputs:
%   filterObject - Current filter object stored in fdatoolud.filter
%   convertdlgud - Convert dialog UserData structure
%
% Output:
%   filterOjbect - Second-order section version of ud.filter

% Get the current scaling option (from the popupmenu).
popStr = get(convertdlgud.h.sosscale.lblNpopup(2),'String');
popVal = get(convertdlgud.h.sosscale.lblNpopup(2),'Value');
currentScaleOpt = popStr{popVal};

% Map proper SOS scaling strings 
switch currentScaleOpt
case 'None', 
    scalingFlag  = 'NONE';
    dirFlag      = 'UP';
case 'L-2',  
    scalingFlag  = 'TWO';
    dirFlag      = 'DOWN';    
case 'L-infinity',  
    scalingFlag  = 'INF';
    dirFlag      = 'UP';
end

% Convert dfilt or qfilt objects to second-order section form.
filterObject = sos(filterObject,dirFlag,scalingFlag); 


%-------------------------------------------------------------------
function indx = setconvertlistboxindx(hFig)
% SETCONVERTLISTBOXINDX Set a default filter structure index for the 
%                       case where the current "Convert To" structure 
%                       no longer exists in the listbox.
%
% Input:
%   indx - Index into the list of filter structures as seen in the Convert
%          Dialog list box.
%
% Output:
%    hFig - Handle to the Filter Design GUI figure.


fdatoolud = get(hFig,'UserData');

% Get a default structure index from the getconvertstructchoices.m: 
% commonstrs = {'Direct form I',...
%         'Direct form II',...
%         'Direct form I transposed',...
%         'Direct form II transposed',...
%         'State-space',...
%         'Lattice ARMA'};
indx = 4; 

fdatoolud.specs.convert.qconvertto = 'Direct form II transposed';
fdatoolud.specs.convert.dconvertto = 'Direct form II transposed';
set(hFig,'UserData',fdatoolud);

% [EOF] update_convertdlg.m
