%% $RCSfile: fixptdiv.tlc,v $
%% $Revision: 1.4.4.7 $
%% $Date: 2004/12/16 21:20:32 $
%%
%% This file contains tlc code for generation of fixed point division
%%
%% Copyright 1994-2003 The MathWorks, Inc.
%%

%if !ISFIELD(CTargetSpecific,"DivisionRoundModeIgnoreGiveMostEfficient")
  %addtorecord CTargetSpecific DivisionRoundModeIgnoreGiveMostEfficient 0
%endif

%if !ISFIELD(CTargetSpecific,"NoFixptDivByZeroProtection")
  %%
  %addtorecord CTargetSpecific NoFixptDivByZeroProtection -1
  %%
%endif

%if !ISFIELD(CTargetSpecific,"TargetIntDivRoundTo")
  %%
  %addtorecord CTargetSpecific TargetIntDivRoundTo ""
  %%
%endif

%function FixPt_OptimizeAwayDivisionProtection() void
    %%
    %if ISEQUAL(CTargetSpecific.NoFixptDivByZeroProtection,-1)
      %%
      %assign val = CompiledModel.ConfigSet.NoFixptDivByZeroProtection
      %%
      %assign val = ISEQUAL(val,1)
      %%
      %if ISFIELD(CTargetSpecific,"DivisionByZeroProtectionNeverWanted")
        %%
        %if (  val && !CTargetSpecific.DivisionByZeroProtectionNeverWanted ) || ...
            ( !val &&  CTargetSpecific.DivisionByZeroProtectionNeverWanted )
          %%
          %openfile warnBuffer
Conflicting optimization settings for fixed-point division exist.
   By default, code generated for fixed-point division prevents
arithmetic exceptions such as division by zero and INT_MIN/-1.
For designs that do not require this protection, Embedded Real-Time 
Workshop provides a user controlled setting that eliminates
the code to protect against exceptions.  Leaner code results.
   Prior to Release 14, this optimization could be turned on
by setting 
   CTargetSpecific.DivisionByZeroProtectionNeverWanted = 1
via the appropriate rtw hooks m-file.  This method is obsolete.
   As of Release 14, this optimization should be set via
the Configuration Parameters Dialog.  When the Real-Time Workshop
target is set to ert Embedded Coder, the optimization for
fixed-point division exception is controlled by a checkbox
on the optimization tab.
   The current model is using the legacy method and has
a conflicting setting on the Configuration Parameters dialog.
   CTargetSpecific.DivisionByZeroProtectionNeverWanted = %<CTargetSpecific.DivisionByZeroProtectionNeverWanted>
   NoFixptDivByZeroProtection = %<val>
This conflict is resolved in favor of higher optimization,
so the optimization will be turned ON.  Please modify the
rtw hooks file so that it no longer adds the field
   CTargetSpecific.DivisionByZeroProtectionNeverWanted
and enter the desired optimization setting via the Configuration
Parameters Dialog.
          %closefile warnBuffer
          %warning %<warnBuffer>
          %%
          %assign val = 1
          %%
        %endif
      %endif
      %%
      %assign ::CTargetSpecific.NoFixptDivByZeroProtection = val
      %%
    %endif
    %%
    %return CTargetSpecific.NoFixptDivByZeroProtection
    %%
%endfunction

%function FixPt_TargetIntDivRoundTo() void
    %%
    %if ISEQUAL(CTargetSpecific.TargetIntDivRoundTo,"")
      %%
      %assign val = CompiledModel.ConfigSet.TargetIntDivRoundTo
      %%
      %assign ::CTargetSpecific.TargetIntDivRoundTo = val
      %%
    %endif
    %%
    %return CTargetSpecific.TargetIntDivRoundTo
    %%
%endfunction

%%
%%
%%
%function FixPt_getDataTypeSubName(fxpDtpY0,fxpDtpU0,fxpDtpU1)
 %%
 %assign utilityName = "_"
 %%
 %if FixPt_DataTypeIsFloat(fxpDtpY0) || ...
     FixPt_DataTypeIsFloat(fxpDtpU0) || ...
     FixPt_DataTypeIsFloat(fxpDtpU1)
  %%
  %if FixPt_DataTypeIsSingle(fxpDtpY0) && ...
      FixPt_DataTypeIsSingle(fxpDtpU0) && ...
      FixPt_DataTypeIsSingle(fxpDtpU1)
    %%
    %% all singles
    %%
    %assign utilityName = utilityName + "real32"
    %%
  %elseif (FixPt_DataTypeIsDouble(fxpDtpY0) || fxpIsDataTypeScaledDouble(fxpDtpY0)) && ...
          (FixPt_DataTypeIsDouble(fxpDtpU0) || fxpIsDataTypeScaledDouble(fxpDtpU0)) && ...
          (FixPt_DataTypeIsDouble(fxpDtpU1) || fxpIsDataTypeScaledDouble(fxpDtpU1))
    %%
    %% all doubles (includes scaled doubles)
    %%
    %assign utilityName = utilityName + "real"
    %%
  %else
    %%
    %if FixPt_DataTypeIsSingle(fxpDtpY0)
      %%
      %assign utilityName = utilityName + "real32"
      %%
    %elseif (FixPt_DataTypeIsDouble(fxpDtpY0) || fxpIsDataTypeScaledDouble(fxpDtpY0))
      %%
      %assign utilityName = utilityName + "real"
      %%
    %else
      %if fxpDtpU0.IsSigned
        %assign utilityName = utilityName + "s"
      %else
        %assign utilityName = utilityName + "u"
      %endif
      %assign utilityName = utilityName + STRING(fxpDtpU0.RequiredBits)
    %endif
    %%
    %assign utilityName = utilityName + "_"
    %%
    %if FixPt_DataTypeIsSingle(fxpDtpU0)
      %%
      %assign utilityName = utilityName + "real32"
      %%
    %elseif (FixPt_DataTypeIsDouble(fxpDtpU0) || fxpIsDataTypeScaledDouble(fxpDtpU0))
      %%
      %assign utilityName = utilityName + "real"
      %%
    %else
      %if fxpDtpU0.IsSigned
        %assign utilityName = utilityName + "s"
      %else
        %assign utilityName = utilityName + "u"
      %endif
      %assign utilityName = utilityName + STRING(fxpDtpU0.RequiredBits)
    %endif
    %%
    %assign utilityName = utilityName + "_"
    %%
    %if FixPt_DataTypeIsSingle(fxpDtpU1)
      %%
      %assign utilityName = utilityName + "real32"
      %%
    %elseif (FixPt_DataTypeIsDouble(fxpDtpU1) || fxpIsDataTypeScaledDouble(fxpDtpU1))
      %%
      %assign utilityName = utilityName + "real"
      %%
    %else
      %if fxpDtpU0.IsSigned
        %assign utilityName = utilityName + "s"
      %else
        %assign utilityName = utilityName + "u"
      %endif
      %assign utilityName = utilityName + STRING(fxpDtpU0.RequiredBits)
    %endif
  %endif
 %else
  %%   
  %if ( fxpDtpU0.RequiredBits == fxpDtpU1.RequiredBits )
    %%
    %if ( fxpDtpU0.RequiredBits == fxpDtpY0.RequiredBits )
      %%
      %% both inputs and output have same container size
      %% Name will only contain one word length
      %% 
      %if ( fxpDtpU0.IsSigned == fxpDtpU1.IsSigned )
        %%
        %if ( fxpDtpU0.IsSigned == fxpDtpY0.IsSigned )
          %%
          %% both inputs and output have same signedness
          %%
          %if fxpDtpU0.IsSigned
            %assign utilityName = utilityName + "s"
          %else
            %assign utilityName = utilityName + "u"
          %endif
          %assign utilityName = utilityName + STRING(fxpDtpU0.RequiredBits)
          %%
        %else
          %%
          %% output has different signedness
          %%
          %if fxpDtpY0.IsSigned
            %assign utilityName = utilityName + "s"
          %else
            %assign utilityName = utilityName + "u"
          %endif
          %if fxpDtpU0.IsSigned
            %assign utilityName = utilityName + "s"
          %else
            %assign utilityName = utilityName + "u"
          %endif
          %assign utilityName = utilityName + STRING(fxpDtpU0.RequiredBits)
          %%
        %endif
        %%
      %else
        %%
        %% treat signedness as fully homogeneous
        %%
        %if fxpDtpY0.IsSigned
          %assign utilityName = utilityName + "s"
        %else
          %assign utilityName = utilityName + "u"
        %endif
        %if fxpDtpU0.IsSigned
          %assign utilityName = utilityName + "s"
        %else
          %assign utilityName = utilityName + "u"
        %endif
        %if fxpDtpU1.IsSigned
          %assign utilityName = utilityName + "s"
        %else
          %assign utilityName = utilityName + "u"
        %endif
        %assign utilityName = utilityName + STRING(fxpDtpU0.RequiredBits)
        %%
      %endif
      %%
    %else
      %%
      %% inputs have common container size, 
      * but output has different size
      * Name contain two word lengths
      %%
      %if ( fxpDtpU0.IsSigned == fxpDtpU1.IsSigned )
        %%
        %% inputs have same signedness
        %%
        %if fxpDtpY0.IsSigned
          %assign utilityName = utilityName + "s"
        %else
          %assign utilityName = utilityName + "u"
        %endif

	%assign utilityName = utilityName + STRING(fxpDtpY0.RequiredBits)
        %if fxpDtpU0.IsSigned
          %assign utilityName = utilityName + "s"
        %else
          %assign utilityName = utilityName + "u"
        %endif
        %assign utilityName = utilityName + STRING(fxpDtpU0.RequiredBits)
        %%
      %else
        %%
        %% treat signedness as fully homogeneous
        %%
        %if fxpDtpY0.IsSigned
          %assign utilityName = utilityName + "s"
        %else
          %assign utilityName = utilityName + "u"
        %endif
        %assign utilityName = utilityName + STRING(fxpDtpY0.RequiredBits)
        %if fxpDtpU0.IsSigned
          %assign utilityName = utilityName + "s"
        %else
          %assign utilityName = utilityName + "u"
        %endif
        %if fxpDtpU1.IsSigned
          %assign utilityName = utilityName + "s"
        %else
          %assign utilityName = utilityName + "u"
        %endif
        %assign utilityName = utilityName + STRING(fxpDtpU0.RequiredBits)
        %%
      %endif
      %%
    %endif
    %%
  %else
    %%
    %% inputs have different container sizes 
    %% treat as fully heterogenous
    %% Name contain three word lengths
    %%
    %if fxpDtpY0.IsSigned
      %assign utilityName = utilityName + "s"
    %else
      %assign utilityName = utilityName + "u"
    %endif
    %assign utilityName = utilityName + STRING(fxpDtpY0.RequiredBits)
    %if fxpDtpU0.IsSigned
      %assign utilityName = utilityName + "s"
    %else
      %assign utilityName = utilityName + "u"
    %endif
    %assign utilityName = utilityName + STRING(fxpDtpU0.RequiredBits)
    %if fxpDtpU1.IsSigned
      %assign utilityName = utilityName + "s"
    %else
      %assign utilityName = utilityName + "u"
    %endif
    %assign utilityName = utilityName + STRING(fxpDtpU1.RequiredBits)
    %%
  %endif
 %endif
 %%
 %return utilityName
 %%
%endfunction





%% Function: FixPt_Division ==========================================
%%
%% Abstract:
%%  Radix Only Division
%%
%%  Vc = Va / Vb
%%
%%  Note the Stored Integers are denoted by A, B, and C
%%
%%  C = 2^(Ea-Eb-Ec) * A / B
%%
%%  The records C, A, and B must contain
%%  all the fixed point data type and scaling fields.
%%  They must also contain a field called "Label"
%%  In C_Language terms cLabel must be an l-value.
%%  aLabel and bLabel are treated as read only and
%%  they must provide the values (stored integers) for
%%  A and B.  Please note none of the Labels can be addresses.
%%
%% Synopsis:
%%      FixPt_Division(cLabel,cDT,aLabel,aDT,bLabel,bDT,roundMode,satMode)
%%
%%      cLabel,cDT = record describing output
%%      aLabel,aDT = record describing input 1
%%      bLabel,bDT = record describing input 2
%%      roundMode  = string specifying round to "Zero", "Nearest", etc.
%%      satMode    = string specifying "Wrap" or "Saturate" on overflow
%%
%function FixPt_Division(cLabel,cDT,aLabel,aDT,bLabel,bDT,roundMode,satMode) Output
    %%
    %if FixPt_OptimizeAwayDivisionProtection()
      %assign protectZero = 0
    %else
      %assign protectZero = 1
    %endif
    %<FixPt_Division_protectZeroOpt(cLabel,cDT,aLabel,aDT,bLabel,bDT,roundMode,satMode,protectZero)>\
    %%
%endfunction

%function FixPt_Division_protectZeroOpt(cLabel,cDT,aLabel,aDT,bLabel,bDT,roundMode,satMode,protectZero) Output
  %%
  %% force FLOOR to act like EASIEST
  %%   this should be removed when EASIEST is added as an option on fixpt dialogs
  %%
%%  %if roundMode == "Floor"
      %%
%%      %assign roundMode = "Easiest"
      %%
%%  %endif
  %%
  %if EXISTS("FixPtProtectDivideByZeroEvenIfImpossible")
    %%
    %if FixPtProtectDivideByZeroEvenIfImpossible
      %%
      %assign protectZero = 1
    %endif
  %else
    %% If Flag does not exist, default is to always
    %% protect division by zero, this could make
    %% lookup tables a bit slower.  However, if
    %% the model uses division anywhere else then
    %% the overall code size should decrease
    %%
    %assign protectZero = 1
  %endif
  %%
  %% override by user request
  %%
  %if FixPt_OptimizeAwayDivisionProtection()
    %assign protectZero = 0
  %endif
  %%
  %% handle floating point cases
  %%
  %if FixPt_DataTypeIsFloat(cDT) || FixPt_DataTypeIsFloat(aDT) || FixPt_DataTypeIsFloat(bDT)
    %%
    %<FixPt_Division_Float(cLabel,cDT,aLabel,aDT,bLabel,bDT,roundMode,satMode)>\
  %else
        %assign nonZeroBiasFound = !ISEQUAL(aDT.Bias,0.0) || ...
                                   !ISEQUAL(bDT.Bias,0.0) || ...
                                   !ISEQUAL(cDT.Bias,0.0)
        %%          
        %if nonZeroBiasFound || ...
            !ISEQUAL(aDT.FracSlope,1.0) || ...
            !ISEQUAL(bDT.FracSlope,1.0) || ...
            !ISEQUAL(cDT.FracSlope,1.0)
          %%
          %assign cLabel_BinPt = cLabel
          %assign aLabel_BinPt = aLabel
          %assign bLabel_BinPt = bLabel
          %%
          %assign cDT_Final = cDT
          %assign cDT_BinPt = cDT
          %assign aDT_BinPt = aDT
          %assign bDT_BinPt = bDT
          %%
          %assign needConvertA = 0
          %assign needConvertB = 0
          %assign needConvertC = 0
          %%
          %if nonZeroBiasFound
            %%
            %assign needConvertA = !ISEQUAL(aDT.Bias,0.0) || !ISEQUAL(aDT.FracSlope,1.0)
            %assign needConvertB = !ISEQUAL(bDT.Bias,0.0) || !ISEQUAL(bDT.FracSlope,1.0)
            %assign needConvertC = !ISEQUAL(cDT.Bias,0.0) || !ISEQUAL(cDT.FracSlope,1.0)
            %%
            %if needConvertA
              %%
              %assign aDT_BinPt = FixPt_SensorDT_2_BinPointDT(aDT)
              %%
            %endif
            %%
            %if needConvertB
              %%
              %assign bDT_BinPt = FixPt_SensorDT_2_BinPointDT(bDT)
              %%
            %endif
            %%
            %if needConvertC
              %%
              %assign cDT_BinPt = FixPt_SensorDT_2_BinPointDT(cDT)
              %%
            %endif
            %%
          %else
            %%
            %copyrecord cDT_Final cDT
            %copyrecord cDT_BinPt cDT
            %copyrecord aDT_BinPt aDT
            %copyrecord bDT_BinPt bDT
            %%
            %assign cDT_BinPt.FracSlope = 1.0
            %assign aDT_BinPt.FracSlope = 1.0
            %assign bDT_BinPt.FracSlope = 1.0
            %%
            %assign fracCorrection = ( cDT.FracSlope  * bDT.FracSlope ) / aDT.FracSlope
            %%
            %assign slopeFixExp = FEVAL("fixptPrivate",...
                                        "fhpBestPrecisionQuantizeParts",...
                                        fracCorrection,...
                                        cDT_Final.RequiredBits,...
                                        cDT_Final.IsSigned)
            %%
            %assign slope  = CAST("Real",slopeFixExp[0])
            %%
            %assign fixExp = CAST("Number",slopeFixExp[1])
            %%
            %assign cDT_Final.FracSlope = slope
            %%
            %assign aDT_BinPt.FixedExp = aDT_BinPt.FixedExp - fixExp
            %%
            %assign needConvertC = !ISEQUAL(slope,1.0)
            %%
          %endif
          %%
          %assign needConvertAny = needConvertA || needConvertB || needConvertC
          %%
          %if needConvertAny
            {            
          %endif 
          %%
          %if needConvertA
            %%
            %assign aLabel_BinPt = "aTempMulNiceScaling"
            %%
            %<aDT_BinPt.NativeType> %<aLabel_BinPt>;
            %%
          %endif
          %%
          %if needConvertB
            %%
            %assign bLabel_BinPt = "bTempMulNiceScaling"
            %%
            %<bDT_BinPt.NativeType> %<bLabel_BinPt>;
            %%
          %endif
          %%
          %if needConvertC
            %%
            %assign cLabel_BinPt = "cTempMulNiceScaling"
            %%
            %<cDT_BinPt.NativeType> %<cLabel_BinPt>;
            %%
          %endif
          %%
          %if needConvertA
            %%
            %<FixPt_Fix2FixAlwaysOutput(aLabel_BinPt,aDT_BinPt,...
                                        aLabel,      aDT,...
                                        roundMode,"Wrap")>\
                                      
            %%
          %endif
          %%
          %if needConvertB
            %%
            %<FixPt_Fix2FixAlwaysOutput(bLabel_BinPt,bDT_BinPt,...
                                        bLabel,      bDT,...
                                        roundMode,"Wrap")>\
           
            %%
          %endif
          %%
          %% call recursively, depth should be no more than 1
          %%
          %<FixPt_Division_protectZeroOpt(cLabel_BinPt,cDT_BinPt,...
                                          aLabel_BinPt,aDT_BinPt,...
                                          bLabel_BinPt,bDT_BinPt,...
                                          roundMode,satMode,...
                                          protectZero)>\

          %%
          %if needConvertC
           
            %<FixPt_Fix2FixAlwaysOutput(cLabel,      cDT_Final,...
                                        cLabel_BinPt,cDT_BinPt,...
                                        FixPtRoundingMode,FixPtSaturationMode)>\
            %%
          %endif
          %%
          %if needConvertAny
            }
          %endif
          %%
          %return ""
          %%
        %else
          %%
          %<FixPt_Division_BinPt(cLabel,cDT,aLabel,aDT,bLabel,bDT,roundMode,satMode,protectZero)>\
        %endif
  %endif    
%endfunction  %% FixPt_Division


%function fixpt_div_overflow_possible(cDT,aDT,bDT,rndMeth,assumePrecisionReductionRange) void
  %%
  %assign ExPrec = aDT.FixedExp - bDT.FixedExp - cDT.FixedExp
  %%
  %if ( ExPrec < 0 && assumePrecisionReductionRange )
    %% /* The caller has indicated that precision reduction
    %%  * should be treated as a range, 
    %%  * at least bit of reduction up to infinite.
    %%  * Worst case overflow analysis comes with just one bit
    %%  */
    %assign ExPrec = -1
  %endif
  %%
  %assign canHaveIdealNegQuot = aDT.IsSigned || bDT.IsSigned
  %assign outputCanNotStoreNegQuot = !cDT.IsSigned
  %%
  %%  /* The HiExp roughly specify the largest positive value.
  %%   *
  %%   *     maxValue = 2^HiExp - LSB
  %%   *
  %%   *  If signed
  %%   *     minValue = -1 * 2^HiExp;
  %%   *  else 
  %%   *     minValue = 0
  %%   *
  %%   * For the input and output, these values are accurate aside from
  %%   * the details of LSB value.
  %%   * 
  %%   * For the quotient, 
  %%   *    the largest positive value could be bigger
  %%   *    by plus one LSB, if the numerator and denominator are both signed.
  %%   *       Ex   -128/-1  = +128
  %%   *
  %%   *    the minimum value is one LSB closer to zero if the the
  %%   *    numerator is unsigned, but the denominator is signed.
  %%   *       Ex   +255/-1  = -255
  %%   */
  %assign cHiExp = cDT.RequiredBits - cDT.IsSigned
  %assign aHiExp = aDT.RequiredBits - aDT.IsSigned
  %assign quotHiExp = aHiExp + ExPrec
  %%  
  %assign sufficientPositiveRange = 1
  %%
  %assign overflowPossible = 0
  %%
  %assign overflowOnlyToZero = 0
  %%
  %if (cHiExp < quotHiExp)
    %% /* output positive range is clearly less than 
    %%  * positive range of ideal quotient
    %%  */
    %assign overflowPossible = 1
    %assign sufficientPositiveRange = 0
    %%
  %elseif (cHiExp == quotHiExp)
    %%
    %if ( aDT.IsSigned && bDT.IsSigned ) 
      %%
      %% /* The positive ranges are nearly matched,
      %%  * except for the most negative numerator divided
      %%  * by minus one, causes overflow
      %%  *       Ex   -128/-1  = +128
      %%  */
      %assign overflowPossible = 1
      %assign sufficientPositiveRange = 0
      %%
    %elseif ( ExPrec < 0 )
      %%
      %% /* rounding of the ideal quotient is necessary
      %%  * 
      %%  * For negative quotients, minValue is an
      %%  * exact power of 2 so rounding should never
      %%  * unless the number of shifts right is extreme.
      %%  * In the extreme case, the negative value
      %%  * could always represented provided the output
      %%  * has the minimum of 2 bits.
      %%  *
      %%  * For positive quotients, 
      %%  *     maxValue = 2^HiExp - LSB
      %%  * could round UP to 
      %%  *     maxValue = 2^HiExp
      %%  * for this case of nearly match range overflow
      %%  * would occur.
      %%  *
      %%  * Rounding up of positive value is possible for only two modes
      %%  * 
      %%  * Suppose
      %%  *
      %%  *     U8 = ( U16 * 2^-8 ) / U8  with round to ceiling
      %%  *
      %%  * cHiExp    =  8
      %%  * aHiExp    = 16
      %%  * quotHiExp =  8
      %%  *
      %%  * The following says overflow can NOT occur.  
      %%  * However, consider the example
      %%  *
      %%  *   Qnumerator   = 0xFFFF
      %%  *   Qdenominator = 1
      %%  *   rawQuotient  = 0xFFFF
      %%  *
      %%  *   Shifting Right 8 bits gives 0x00FF which is in the outputs
      %%  *   range, however at least one of the bits shifted off was non-zero
      %%  *   so round to ceiling increments the result to
      %%  *   0x0100, which oveflows a U8 container.
      %%  */
      %switch rndMeth 
        %case "Nearest"
        %case "Ceiling"
          %%
          %assign overflowPossible = 1
          %assign sufficientPositiveRange = 0
      %endswitch
    %endif  
  %endif
  %%
  %if ( canHaveIdealNegQuot && outputCanNotStoreNegQuot )
    %%
    %% /* overflow of negative values to zero occurs
    %%  */
    %assign overflowPossible = 1
    %%
    %if ( sufficientPositiveRange )
      %%
      %assign overflowOnlyToZero = 1
      %%
    %endif
  %endif
  %%
  %assign res = [%<overflowPossible>, %<overflowOnlyToZero>]
  %return res
  %%
%endfunction
    


%function fixpt_div_greater_pos_range(aDT, bDT)
  %%
  %assign aHiExp = aDT.RequiredBits - aDT.IsSigned + aDT.FixedExp
  %assign bHiExp = bDT.RequiredBits - bDT.IsSigned + bDT.FixedExp
  %%
  %return aHiExp > bHiExp
%endfunction
  


%function FixPt_Division_BinPt(cLabel,cDT,aLabel,aDT,bLabel,bDT,roundMode,satMode,protectZero) Output
    %%
    %assign repeatedSubtractionsNeeded = 0
    %%
    %assign numRepeatedSubtractions = 0
    %%
    %assign anyInSigned = aDT.IsSigned || bDT.IsSigned
    %%
    %assign bitsForDivInputArgs = 0
    %%
    %assign bitsPerInt  = IntegerSizes.IntNumBits
    %assign bitsPerLong = IntegerSizes.LongNumBits
    %%
    %assign nLeftShiftNum = 0
    %assign bitsUsedInU0PreCastOut = aDT.RequiredBits
    %%
    %assign adjustedSaturate = "Wrap"
    %%
    %assign overflowOnlyToZero = 0
    %%
    %assign adjustedRndMeth = roundMode
    %%
    %% The data types should already have zero bias and trivial FracSlope 
    %% so it is not necessary to deal with that.
    %%
    %copyrecord cDT_Net cDT
    %assign cDT_Net.FixedExp = cDT.FixedExp + bDT.FixedExp - aDT.FixedExp
    %%
    %copyrecord aDT_Net aDT
    %assign aDT_Net.FixedExp = 0
    %%
    %copyrecord bDT_Net bDT
    %assign bDT_Net.FixedExp = 0
    %%
    %if satMode == "Saturate"
      %%
      %assign two_tuple = fixpt_div_overflow_possible(cDT_Net,aDT_Net,bDT_Net,roundMode,0)
      %%
      %if two_tuple[0]
        %assign adjustedSaturate = "Saturate"
      %endif
      %%
      %assign overflowOnlyToZero = two_tuple[1]
    %endif
    %%
    %assign includeToZeroSaturationCode  = (adjustedSaturate == "Saturate") && anyInSigned && !cDT.IsSigned
    %%
    %assign canHaveUnSaturatedNegQuot = anyInSigned && !includeToZeroSaturationCode
    %%
    %assign adjustedRndMeth = FixPt_get_net_round_method_for_division(roundMode,canHaveUnSaturatedNegQuot)
    %%
    %% /* Adjust the Initial Net Data Types
    %%  */ 
    %if ( cDT_Net.FixedExp < 0)
      %%
      %% /* Straight division does not provide enough precision
      %% * so binary point adjustment will be put on the net input,
      %% * code generated for the division step will then produce the 
      %% * additional required precision.
      %% */
      %assign aDT_Net.FixedExp = -cDT_Net.FixedExp
      %%
      %assign cDT_Net.FixedExp = 0
    %endif
    %%
    %% /* For the step Pre-cast U0, 
    %%  *    determine the data type cast to U0PreCastOut
    %%  *
    %%  *    One goal of this pre-cast is to simplify the division
    %%  *    step.  For example, reducing of eliminating the need
    %%  *    for repeated subtractions.   Another goal of this
    %%  *    pre-cast step is to reduce the combinations of 
    %%  *    division utilities.  For example, instead of
    %%  *    creating 8 division utilities to handle 
    %%  *                short / short
    %%  *       unsigned short / short
    %%  *                short / unsigned short
    %%  *                  int / short
    %%  *                  int / unsigned short
    %%  *                short / int
    %%  *       unsigned short / int
    %%  *                  int / int
    %%  *    just cast short inputs to int and only generate
    %%  *    1 division utility
    %%  *                  int / int
    %%  */
    %assign bitsForDivInputArgs = bitsPerInt
    %%
    %if ( aDT.RequiredBits > bitsForDivInputArgs )
      %%
      %assign bitsForDivInputArgs = aDT.RequiredBits
    %endif
    %%
    %if ( bDT.RequiredBits > bitsForDivInputArgs )
      %%
      %assign bitsForDivInputArgs = bDT.RequiredBits
    %endif
    %%
    %copyrecord aDT_PreCastOut aDT_Net
    %%
    %if (aDT_PreCastOut.FixedExp > 0) 
      %%
      %% /* Straight division does not provide enough precision.
      %%  * One way to get extra precision is to put the numerator into a
      %%  * bigger container and to shift left prior to the division.  
      %%  * Each bit shifted left produces an extra bit of precision.  
      %%  * The maximum number of left shifts without possible overflow
      %%  * is determined by the extra room in the bigger container (if any).
      %%  */
      %assign bitsAvailLeftShiftNum = 0
      %%
      %if ( bitsPerLong > aDT.RequiredBits )
        %%
        %% /* numerator is less than a long so it
        %%  *   can be shifted left inside an int or
        %%  *   long prior to division in order to get 
        %%  *   extra bits of precision in the quotient.
        %%  *   This pre division shift left can reduce
        %%  *   or eliminate the need for repeated subtractions.
        %%  */
        %assign bitsAvailLeftShiftNum = bitsForDivInputArgs - aDT.RequiredBits
        %%
        %if ( !aDT.IsSigned &&  bDT.IsSigned )
          %%
          %% /* the ideal quotient in signed but the numerator is 
          %%  * unsigned so one of the available bits must be reserved 
          %%  * for adding a sign bit
          %%  */
          %assign bitsAvailLeftShiftNum = bitsAvailLeftShiftNum - 1
        %endif
        %%
        %if ( bitsAvailLeftShiftNum < aDT_Net.FixedExp )
          %%
          %% /* The required amount of left shifts and/or
          %%  * addition of a sign bit won't fit in 
          %%  * smaller container so bump up to long sized
          %%  * container.  It is judge to be better to
          %%  * let the C Compiler implement division on
          %%  * longs than it is to do repeated subtractions
          %%  * or other advanced divisions steps on an int.
          %%  */
          %assign bitsForDivInputArgs = bitsPerLong
          %%
          %assign bitsAvailLeftShiftNum = bitsAvailLeftShiftNum + bitsPerLong - bitsPerInt
        %endif
      %endif
      %%
      %if ( bitsAvailLeftShiftNum >= aDT_PreCastOut.FixedExp )
        %%
        %assign nLeftShiftNum = aDT_PreCastOut.FixedExp
        %%
        %assign aDT_PreCastOut.FixedExp = 0
      %else
        %%
        %assign nLeftShiftNum = bitsAvailLeftShiftNum
        %%
        %assign aDT_PreCastOut.FixedExp = aDT_PreCastOut.FixedExp - bitsAvailLeftShiftNum
      %endif
    %endif
    %%
    %assign bitsUsedInU0PreCastOut = bitsUsedInU0PreCastOut + nLeftShiftNum
    %%
    %if ( aDT_PreCastOut.FixedExp > 0 )
      %%
      %% /* 
      %%  * repeated subtractions needed
      %%  */
      %assign repeatedSubtractionsNeeded = 1
    %endif
    %%
    %if (  cDT.RequiredBits > bitsForDivInputArgs && ...
          (aDT.RequiredBits+bDT.IsSigned) > bitsForDivInputArgs  )
      %%
      %% /* If output has more bits, than inputs then use
      %%  * that larger size if it helps prevent overflow
      %%  * Not counting division by zero
      %%  *
      %%  * Example 1, 
      %%  *    min( U8 / S8 ) =  255/-1 = -255    
      %%  *    max( U8 / S8 ) =  255/+1 = +255
      %%  *    bumping up to at least 9 bits signed prevents overflow
      %%  *
      %%  * Example 2, 
      %%  *    min( S8 / S8 ) = -128/+1 = -128
      %%  *    max( S8 / S8 ) = -128/+1 = +128
      %%  *    bumping up to at least 9 bits signed prevents overflow
      %%  *
      %%  * Example 3, 
      %%  *    min( S8 / U8 ) = -128/+1 = -128
      %%  *    max( S8 / U8 ) = +127/+1 = +127
      %%  *    staying with 8 bits signed is sufficient
      %%  *
      %%  * Example 4, 
      %%  *    min( U8 / U8 ) =    0/+1 =    0
      %%  *    max( U8 / U8 ) = +255/+1 = +255
      %%  *    staying with 8 bits unsigned is sufficient
      %%  *
      %%  * Note that the number of bits in the numerator and 
      %%  * the signedness of the denominator determine the max 
      %%  * and min
      %%  */
      %assign bitsForDivInputArgs = cDT.RequiredBits
    %endif
    %%
    %if ( aDT_PreCastOut.RequiredBits < bitsForDivInputArgs )
      %%
      %assign aDT_PreCastOut.IsSigned = anyInSigned
      %%
      %assign aDT_PreCastOut.RequiredBits = bitsForDivInputArgs
    %endif
    %%
    %% /* For the step Pre-cast U1, 
    %%  *    determine the data type cast to U1PreCastOut
    %%  *
    %%  *    The goal of this pre-cast step is just to reduce the 
    %%  *    combinations of division utilities.  For example, casting
    %%  *    shorts up to int prior to division.   
    %%  *       For rounding to nearest, the number of division utilities
    %%  *    can also be reduced by preventing excess precision.
    %%  */
    %%
    %copyrecord bDT_PreCastOut bDT_Net
    %%
    %if ( bDT_PreCastOut.RequiredBits < bitsForDivInputArgs ) 
      %%
      %assign bDT_PreCastOut.IsSigned = anyInSigned
      %%
      %assign bDT_PreCastOut.RequiredBits = bitsForDivInputArgs
    %endif
    %%
    %% /* For the division step, 
    %%  *    determine the data type for the quotient Y0PostCastIn
    %%  *
    %%  * One of the goals in selecting the data type is to reduce the
    %%  * combinations of division utilities that are created.  For example,
    %%  * suppose the final output is a short.  In many cases, the quotient
    %%  * can be computed as an int.  In separate code, the int is down cast 
    %%  * to a short.  The division routine that produced an int can be
    %%  * shared in other places. 
    %%  *
    %%  * There are limitations to this sort of sharing based on the
    %%  * specifics of the math such as scaling, rounding mode, and 
    %%  * saturation mode.
    %%  */
    %% /* initial guess is same as final output but with trivial scaling 
    %%  *
    %%  * slope correction is always handled in post cast 
    %%  *
    %%  * precision reduction was already moved to the input if necessary
    %%  */
    %copyrecord cDT_PostCastIn cDT_Net
    %assign cDT_PostCastIn.FixedExp = 0
    %assign cDT_PostCastIn.FracSlope = 1.0
    %%
    %if ( !cDT_Net.IsSigned || satMode == "Saturate" )
      %%
      %if ( !anyInSigned )
        %%
        %% /* The ideal quotient can only be non-negative
        %%  * so making the output of the division op unsigned
        %%  * simplifies things, conversion to signed can 
        %%  * be handled after the division without problem
        %%  */
        %assign cDT_PostCastIn.IsSigned = 0
      %endif
      %%  
      %if ( cDT_PostCastIn.RequiredBits < bitsForDivInputArgs )
        %%
        %% /* The final output has fewer bits than used for
        %%  * the input arguments.  To reduce variety of utilities,
        %%  * it makes sense to increase the number of bits in the 
        %%  * output of the division.  One of the extra bits
        %%  * can be used to hold a sign bit, if any of the
        %%  * inputs are signed.  The output of the division 
        %%  * will have positive and negative range that at
        %%  * least equals and usually exceeds that of the 
        %%  * final output.  Overflows and saturations
        %%  * can be handled in the post cast without loss
        %%  * of accuracy.
        %%  */
        %assign cDT_PostCastIn.IsSigned = anyInSigned
        %%
        %assign cDT_PostCastIn.RequiredBits = bitsForDivInputArgs
      %endif
    %endif
    %%
    %if ( cDT_Net.FixedExp > 0 )
      %%
      %assign makeDivUtilDoPrecisionReduction = 0
      %%
      %assign two_tuple = fixpt_div_overflow_possible(cDT_PostCastIn,aDT_Net,bDT_Net,adjustedRndMeth,0)
      %%
      %assign overflowCanOccurInProposedDivOp = two_tuple[0]
      %%
      %if ( overflowCanOccurInProposedDivOp )
        %%
        %assign makeDivUtilDoPrecisionReduction = 1
      %endif
      %%
      %% /* The final output has less precision than would be
      %%  * directly provided by the division instruction.
      %%  * To deal with, this the precision must be reduced.
      %%  * One option is to cast to lower precision in a 
      %%  * seperate conversion operation after the division
      %%  * utility has been called.  This is the preferred 
      %%  * approach because it can reduce the number of division
      %%  * utilities required.  However, some difficulties CAN arise:
      %%  * 
      %%  *   1) division by zero CAN
      %%  *         produce a smaller value than the Simulink standard
      %%  *
      %%  *   2) overflow in the raw quotient 
      %%  *         CAN lead to a different answer than Simulink
      %%  *
      %%  *   3) the final answer CAN be rounded twice 
      %%  *         leading to answer off by one LSB.
      %%  *
      %%  * The following analysis attempts to identify these situations.
      %%  * In these cases, a division utility must be generated that can directly 
      %%  * handle the precision reduction. 
      %%  */
      %%
      %if (( adjustedRndMeth == "Nearest" ) || ...
        ( adjustedRndMeth == "Ceiling" ) )
        %%
        %% /* For rounding to floor or zero, the excess precision can 
        %%  * be removed after the division step.  There will be two rounding
        %%  * steps, one in the division routine, and one in the post cast.
        %%  * Rounding twice to floor, or twice to zero,
        %%  * produces the same answer as a one direct round to the final
        %%  * precision.  For these cases, let precision reduction be handled
        %%  * in the post-cast.
        %%  *
        %%  * Note: With rounding to nearest (or ceiling), rounding twice to 
        %%  * nearest (or ceiling) can produce a different answer than a single 
        %%  * direct round to nearest (or ceiling).
        %%  *  
        %%  * For rounding to nearest, there are two approaches
        %%  *
        %%  *    1) In one step, 
        %%  *         apply Nearest Rounding all the way to the final precision 
        %%  * 
        %%  *    2) In two steps,
        %%  *         apply FLOOR Rounding to get to an intermediate precision
        %%  *            that is STRICTLY more precise than the final precision
        %%  *         apply NEAREST Rounding to go to the final precision.
        %%  *
        %%  *         NOTE: the key step in rounding to nearest is to look at
        %%  *         the most significant bit being dropped.  None of the 
        %%  *         other dropped bits matter.  Rounding to FLOOR in the 
        %%  *         first step just shifts off some of the bits that don't
        %%  *         matter.  The key bit is preserved.  Reminder, if the value 
        %%  *         being rounded is unsigned, then ZERO Rounding is equivalent 
        %%  *         FLOOR.
        %%  *
        %%
        %% xxx Approach 2 is currently not be exploited.  It could potentially
        %% simplify the generated code.
        %%
        %%  * For rounding to ceiling, it seems that a one step cast is
        %%  * the only accurate approach.
        %%  */
        %assign makeDivUtilDoPrecisionReduction = 1
        %%
      %elseif ( fixpt_div_greater_pos_range(cDT_Net, cDT_PostCastIn) )
        %%
        %% /* The positive range of the final output exceeds
        %%  * that of the proposed raw quotient.
        %%  * Some difficulties can arise:
        %%  * 
        %%  *   1) division by zero will 
        %%  *         produce a smaller value than the Simulink standard
        %%  *         
        %%  *         Under the current design, when non-negative is  
        %%  *         divided by zero, the final output is set to its
        %%  *         maximum possible value.  when negative is divided by
        %%  *         zero, the final output is set to its minimum possible
        %%  *         value.
        %%  *            Here is an example of how numerical differences could
        %%  *         occur.  Inputs are both U32 with trivial scaling 2^0.
        %%  *         The output is U32 with scaling 2^+16.  Round to floor.
        %%  *         Aside from division by zero it would be fine to do
        %%  *               y = div_u32u32u32(u0,u1) >> 16;
        %%  *         But consider case u0 = 1, u1 = 0, the div utility would
        %%  *         detect division by zero an output its maximum.
        %%  *               0xFFFFFFFF
        %%  *         the subsequent shift right would reduce this to                  
        %%  *               0x0000FFFF
        %%  *         which is drastically less than the maximum U32.
        %%  *
        %%  *   NOTE: In the future we could optimize away the divide by zero,
        %%  *         by permanently or optionally changing Simulink's divide
        %%  *         by zero design.  The new design would be that division by
        %%  *         zero always outputs zero.  Subsequent shifts of zero
        %%  *         still give zero so the problem goes away.  Division by
        %%  *         zero for signed cases would also be simplified.
        %%  *
        %%  *   2) overflow in the raw quotient 
        %%  *         will lead to a different answer than Simulink
        %%  *            Here is an example of how numerical differences could
        %%  *         occur.  Inputs are both S32 with trivial scaling 2^0.
        %%  *         The output is U16 with scaling 2^17.  Round to floor.
        %%  *
        %%  *       Case 1) assume overflow wrap.
        %%  *         Aside from division by zero and overflow, it would be fine to do
        %%  *               y = (uint16)(div_s32s32s32(u0,u1) >> 17);
        %%  *         But consider case u0 is the minimum possible value -1*2^31, and
        %%  *         u1 = -1, the ideal quotient is positive 2^31 which can not be 
        %%  *         represented in S32, so an overflow occurs.  With modulo 2 wrapping
        %%  *         the division utility would return -1*2^31
        %%  *               0x80000000
        %%  *         The arithmetic shift right would reproduce the sign bit 17 times
        %%  *               0xFFFFC000
        %%  *         The down cast to 16 bit unsigned would give
        %%  *               0xC000
        %%  *         The real world value for this (2^15+2^14)*2^17 = 3 * 2^31
        %%  *         This is three times bigger than the ideal quotient 2^31.
        %%  *         Because the final output data type could hold the ideal quotient,
        %%  *         that is the answer Simulink would have produced for these inputs.
        %%  *
        %%  *       Case 2) Consider the exact same situation as case 1 except 
        %%  *               assume overflows are configured to saturate.  Saturation
        %%  *               does NOT solve the problem
        %%  *         For u0 = -1*2^32, u1 = -1,
        %%  *               y = (uint16)(div_s32s32s32_sat(u0,u1) >> 17);
        %%  *         the division utility would saturate to (2^31)-1
        %%  *               0x7FFFFFFF
        %%  *         The arithmetic shift right 17 times gives
        %%  *               0x00003FFF
        %%  *         The down cast to 16 bit unsigned would give
        %%  *               0x3FFF
        %%  *         The real world value for this ((2^14)-1)*2^17 = (2^31)-(2^17) 
        %%  *         Again, this output does not equal the ideal quotient which is
        %%  *         what Simulink would output.
        %%  */
        %assign makeDivUtilDoPrecisionReduction = 1
        %%
        %% /* Could try a bigger container
        %%         xxx andyb 
        %%         Currently not sure that using a bigger container is a good solution.
        %%         Is it really more efficient to replace int division with shifts handling
        %%         by long division?  A 16 bit microprocessor may have an ASM instruction for 16 bit 
        %%         division but none for 32 bit division.  The compiler would have to output many ASM 
        %%         instruction to effect a 32 bit division.
        %%  */
      %endif    
      %%    
      %if ( makeDivUtilDoPrecisionReduction )
        %%
        %% /* Straight division provides excess precision.  For rounding
        %%  * to floor, zero, or ceiling, the excess precision can be
        %%  * removed after the division step.  PROVIDED there is NO OVERFLOW!
        %%  * There will be two rounding
        %%  * steps, one in the division routine, and one in the post cast.
        %%  * Rounding twice to floor, or twice to zero, or twice to ceiling,
        %%  * produces the same answer as a one direct round to the final
        %%  * precision.  With rounding to nearest, rounding twice can
        %%  * produce a different answer than a single direct round.  For
        %%  * rounding to nearest, all the rounding must be in one place.
        %%  * Potentially based on scaling many different varieties of round 
        %%  * to nearest could be required.  
        %%  *
        %%  * One way to reduce the varieties is to prevent the excess precision 
        %%  * in the quotient is to put the denominator into a
        %%  * bigger container and to shift left prior to the division.  
        %%  * Each bit shifted left produces an one less bit of precision.  
        %%  * The maximum number of left shifts without possible overflow
        %%  * is determined by the extra room in the bigger container (if any).
        %%  */
        %assign bitsAvailLeftShiftDen = 0
        %%
        %if ( bitsForDivInputArgs > bDT.RequiredBits )
          %%
          %% /* denominator is less than size used in division so it
          %%  *   can be shifted left inside an int or
          %%  *   long prior to division in order to get 
          %%  *   reduced bits of precision in the quotient.
          %%  */
          %assign bitsAvailLeftShiftDen = bitsForDivInputArgs - bDT.RequiredBits
          %%
          %if ( aDT.IsSigned &&  !bDT.IsSigned )
            %%
            %% /* the ideal quotient in signed but the denominator is 
            %%  * unsigned so one of the available bits must be reserved 
            %%  * for adding a sign bit
            %%  */
            %assign bitsAvailLeftShiftDen = bitsAvailLeftShiftDen - 1
          %endif
          %%        
          %% /* When shifting left the numerator to get extra
          %%  * precision, the number of bits was bumped up to a long
          %%  * if necessary.  Preventing repeated subtractions was
          %%  * worth this cost.  For the case of excess precision
          %%  * when rounding to nearest, the cost of bumping up to a 
          %%  * long is not deem worthwhile. 
          %%  */
        %endif
        %%
        %if ( bitsAvailLeftShiftDen >= cDT_Net.FixedExp )
          %%
          %% /* all the excess precision can be removed by
          %%  * shifting the denominator left
          %%  */
          %assign bDT_Net.FixedExp = cDT_Net.FixedExp
          %assign cDT_Net.FixedExp = 0
          %%
        %else
          %%
          %% /* a version of the division utility is needed 
          %%  * that can handle precision reduction.
          %%  */
          %assign aDT_Net.FixedExp        = aDT_Net.FixedExp        - cDT_Net.FixedExp
          %assign aDT_PreCastOut.FixedExp = aDT_PreCastOut.FixedExp - cDT_Net.FixedExp
          %assign cDT_Net.FixedExp        = 0
        %endif
      %endif
      %%
      %if ( fixpt_div_greater_pos_range(cDT_Net, cDT_PostCastIn) )
        %%
        %% /* The positive range of the final output STILL exceeds
        %%  * that of the proposed raw quotient.
        %%  * The signedness must be the difference
        %%  */
        %assign cDT_PostCastIn.IsSigned = cDT_Net.IsSigned
      %endif
    %endif
    %%
    %assign numRepeatedSubtractions = aDT_PreCastOut.FixedExp - bDT_PreCastOut.FixedExp - cDT_PostCastIn.FixedExp
    %%
    %assign cDT_Net.DataTypeName = LibFixPointFormDataTypeName(cDT_Net.IsSigned,cDT_Net.RequiredBits,cDT_Net.FixedExp)
    %assign cDT_Net.ActualBits   = cDT_Net.RequiredBits
    %assign cDT_Net.NativeType   = "#error x"
    %<FixPt_DefineDataType(cDT_Net)>\
    %%
    %assign aDT_Net.DataTypeName = LibFixPointFormDataTypeName(aDT_Net.IsSigned,aDT_Net.RequiredBits,aDT_Net.FixedExp)
    %assign aDT_Net.ActualBits   = aDT_Net.RequiredBits
    %assign aDT_Net.NativeType   = "#error x"
    %<FixPt_DefineDataType(aDT_Net)>\
    %%
    %assign bDT_Net.DataTypeName = LibFixPointFormDataTypeName(bDT_Net.IsSigned,bDT_Net.RequiredBits,bDT_Net.FixedExp)
    %assign bDT_Net.ActualBits   = bDT_Net.RequiredBits
    %assign bDT_Net.NativeType   = "#error x"
    %<FixPt_DefineDataType(bDT_Net)>\
    %%
    %assign cDT_PostCastIn.DataTypeName = LibFixPointFormDataTypeName(cDT_PostCastIn.IsSigned,cDT_PostCastIn.RequiredBits,cDT_PostCastIn.FixedExp)
    %assign cDT_PostCastIn.ActualBits   = cDT_PostCastIn.RequiredBits
    %assign cDT_PostCastIn.NativeType   = "#error x"
    %<FixPt_DefineDataType(cDT_PostCastIn)>\
    %%
    %assign aDT_PreCastOut.DataTypeName = LibFixPointFormDataTypeName(aDT_PreCastOut.IsSigned,aDT_PreCastOut.RequiredBits,aDT_PreCastOut.FixedExp)
    %assign aDT_PreCastOut.ActualBits   = aDT_PreCastOut.RequiredBits
    %assign aDT_PreCastOut.NativeType   = "#error x"
    %<FixPt_DefineDataType(aDT_PreCastOut)>\
    %%
    %assign bDT_PreCastOut.DataTypeName = LibFixPointFormDataTypeName(bDT_PreCastOut.IsSigned,bDT_PreCastOut.RequiredBits,bDT_PreCastOut.FixedExp)
    %assign bDT_PreCastOut.ActualBits   = bDT_PreCastOut.RequiredBits
    %assign bDT_PreCastOut.NativeType   = "#error x"
    %<FixPt_DefineDataType(bDT_PreCastOut)>\
    %%
    %assign aPreCastOutLabel = FixPt_Fix2Fix_Expr(aDT_PreCastOut,aLabel,aDT_Net,roundMode,satMode)
    %%    
    %assign bPreCastOutLabel = FixPt_Fix2Fix_Expr(bDT_PreCastOut,bLabel,bDT_Net,roundMode,satMode)
    %%    
    %if cDT_Net.RequiredBits != cDT_PostCastIn.RequiredBits || ...
        cDT_Net.FixedExp     != cDT_PostCastIn.FixedExp     || ...
        cDT_Net.IsSigned     != cDT_PostCastIn.IsSigned
      %%
      %assign postCastRequired = 1
      %%
      %assign cLabelCur = "fixpt_temp_quotient"
      %%
    %else
      %assign postCastRequired = 0
      %%
      %assign cLabelCur = cLabel
      %%
    %endif
    %%  
    %if postCastRequired
    {
      %<cDT_PostCastIn.NativeType> %<cLabelCur>;
      
    %endif
    %%
    %if numRepeatedSubtractions > 0
      %<FixPt_Division_RepeatSubtraction(cLabelCur,cDT_PostCastIn,aPreCastOutLabel,aDT_PreCastOut,bPreCastOutLabel,bDT_PreCastOut,adjustedRndMeth,adjustedSaturate,protectZero)>\
    %else
      %<FixPt_Division_StraightShot(     cLabelCur,cDT_PostCastIn,aPreCastOutLabel,aDT_PreCastOut,bPreCastOutLabel,bDT_PreCastOut,adjustedRndMeth,adjustedSaturate,protectZero)>\
    %endif
    %%
    %if postCastRequired
      
      %<FixPt_Fix2FixAlwaysOutput(cLabel,   cDT_Net,...
                                  cLabelCur,cDT_PostCastIn,...
                                  roundMode,satMode)>\
    }
    %endif
    %%    
%endfunction %% FixPt_Division_BinPt
      


%function FixPt_Division_Float(cLabel,cDT,aLabel,aDT,bLabel,bDT,roundMode,satMode) Output
  %%
  %assign cIsFloat = FixPt_DataTypeIsFloat(cDT)
  %assign aIsFloat = FixPt_DataTypeIsFloat(aDT)
  %assign bIsFloat = FixPt_DataTypeIsFloat(bDT)
  %%
  {
    %if cDT.NativeType != "real32_T" || aDT.NativeType != "real32_T" || bDT.NativeType != "real32_T"
      %%
      %assign tempType = "real_T"
      %%
      %assign intermediateDT = FixPt_GetDataTypeFromIndex(0)
    %else
      %assign tempType = "real32_T"
      %%
      %assign intermediateDT = FixPt_GetDataTypeFromIndex(1)
    %endif
    %%
    %assign tempLabela = "tempFloatPt1"
    %assign tempLabelb = "tempFloatPt2"
    %%            
    %openfile captureConvertMul
    %assign retVecStr_a = FixPt_Fix2Fix(tempLabela,intermediateDT,aLabel,aDT,roundMode,satMode)
    %assign retVecStr_b = FixPt_Fix2Fix(tempLabelb,intermediateDT,bLabel,bDT,roundMode,satMode)
    %closefile captureConvertMul
    %%
    %if SIZE(retVecStr_a,1) == 3
      %%
      %assign intermediateLabel = "(%<retVecStr_a[1]>/"
    %else
      %<tempType> %<tempLabela>;
      %%
      %assign intermediateLabel = "(%<tempLabela>/"
    %endif
    %%
    %if SIZE(retVecStr_b,1) == 3
      %%
      %assign intermediateLabel = intermediateLabel + "%<retVecStr_b[1]>)"
    %else
      %<tempType> %<tempLabelb>;
      %%
      %assign intermediateLabel = intermediateLabel + "%<tempLabelb>)"
    %endif
    %%
    %if SIZE(retVecStr_a,1) != 3 || SIZE(retVecStr_b,1) != 3
      %%
      %<captureConvertMul>\
    %endif
    %%            
    %if cIsFloat
      %<FixPt_Fix2FixAlwaysOutput(cLabel,cDT,intermediateLabel,intermediateDT,roundMode,satMode)>\
    %else
      {
	%assign tempLabelc = "tempFloatPt3"
	%<tempType> %<tempLabelc>;
	%<tempLabelc> = %<intermediateLabel>;
	%<FixPt_Fix2FixAlwaysOutput(cLabel,cDT,tempLabelc,intermediateDT,roundMode,satMode)>\
      }
    %endif
  }
%endfunction  %% FixPt_Division_Float



%function FixPt_get_net_round_method_for_division(origRndMeth,negativeCanBeRounded) void
  %%
  %if CTargetSpecific.DivisionRoundModeIgnoreGiveMostEfficient
    %%
    %assign TargetIntDivRoundTo = FixPt_TargetIntDivRoundTo()
    %%
    %% Definitely need to filter out the "Undefined" case
    %% As of Nov 7, 2003, "Ceiling" could also be returned by this not 
    %%  a usable choice.  For this reason, only allow known case to 
    %%  get thru now
    %%
    %if ISEQUAL(TargetIntDivRoundTo,"Floor") || ...
        ISEQUAL(TargetIntDivRoundTo,"Zero" )
      %%
      %assign netRndMode = TargetIntDivRoundTo
    %else
      %assign netRndMode = "Zero"
    %endif
  %else
    %assign netRndMeth = origRndMeth
  %endif
  %%
  %if origRndMeth == "Floor" && !negativeCanBeRounded
    %%
    %assign netRndMeth = "Zero"
  %endif
  %%
  %return netRndMeth
  %%
%endfunction



%function fixpt_div_repeat_unsigned_guts(...
  cDT,...
  numerator,...
  denominator,...
  retVal,...
  nRepeatSubLabel,...
  includeNonZeroSaturationCode,...
  rndMeth,...
  needNegation ) Output  
  %%
  %% declare loop control variable for repeated subtractions
  %%
  %%
  %% useful bit mask
  %%
  %assign mask_ULONG_MS_BIT_SET = SetMSNBitsStr(1,IntegerSizes.LongNumBits,0)
  %%
  %assign bitsPerLong = IntegerSizes.LongNumBits
  %assign bitsPerInt  = IntegerSizes.IntNumBits
  %%
  %assign uLongName = "uint%<bitsPerLong>_T"
  %assign sLongName = "int%<bitsPerLong>_T"
  %%
  %assign uIntName = "uint%<bitsPerInt>_T"
  %assign sIntName = "int%<bitsPerInt>_T"
  %%
  { %% /* start guts */
    %<uIntName> iRepeatSub;
    %%
    %% /* Since B is a long, the numerator must be represented
    %%  * with one more bit than a long.
    %%  * an int will be used to hold the extra bit
    %%  */
    %<sIntName> numeratorExtraBit;
	    
    %%
    %if includeNonZeroSaturationCode
      %%
      %% declare temporary quotient if one is needed
      %%
      %assign tempQuotVar = "tempQuotient"
      %<uLongName> %<tempQuotVar>;
      %% 
      %% /* because overflows could occur during anyone of several
      %%  * operations, a variable will be used to track overflow
      %%  */
      %<uIntName> overflow = 0;

    %else
      %assign tempQuotVar = retVal      
    %endif
    %%
    %% get as many bits as possible using standard
    %% divide and remainder
    %%
    %% /* First batch of quotient bits from normal division */
    %%
    %<tempQuotVar> =  %<numerator> / %<denominator>;
    %%
    %% /* Remainder serves as numerator for subsequent steps */
    %<numerator> %= %<denominator>;

    %% /* get the nRepeatSub remaining quotient bits via repeated subtractions */
    %%
    for ( iRepeatSub = 0; iRepeatSub < %<nRepeatSubLabel>; iRepeatSub++ )
    {
      %% /* multiply current numerator by two, keeping track of extra bit */
      numeratorExtraBit = (%<numerator> >= %<mask_ULONG_MS_BIT_SET>);
      %<numerator> <<= 1;
      %%
      %if includeNonZeroSaturationCode
        %% /* multiply running quotient by two, forcing least significant bit to zero
        %%  * if MS bit of quotient was one then (new or additional) overflow occurs
        %%  */
        overflow = overflow || (%<tempQuotVar> >= %<mask_ULONG_MS_BIT_SET>);
      %else
        %% /* multiply running quotient by two, forcing least significant bit to zero */
      %endif
      %<tempQuotVar> <<= 1;

      %% /* when numerator including extra bit is >= denominator */
      if ( numeratorExtraBit || ( %<numerator> >= %<denominator> ) )
      {
        %% /* set least significant bit of running quotient to one */
        %<tempQuotVar>++;
        %%
        %% /* Get current remainder
        %%  * subtract denominator from current numerator, the extra bit
        %%  * will always be zero after subtraction, but it is not
        %%  * necessary to actually implement that step because
        %%  * the extra bit will be re-calculated before it is used again
        %%  */
        %<numerator> -= %<denominator>;
      }
    } %% for i nRepeatSub
    %%
    %% saturate or store temporary quotient in output
    %%
    %if includeNonZeroSaturationCode
      %%
      %assign outMaxStoreInt = FixPt_GetMaxStr(cDT)
      %%
      %switch rndMeth
        %case "Nearest"
        %case "Ceiling"
          %%
          if ( overflow || (%<tempQuotVar> >= %<outMaxStoreInt>) )
          %%
          %break
        %default
          %%
          if ( overflow )
          %%
          %break
      %endswitch
      {
        %% /* saturate to maximum */
        %<retVal> = (%<cDT.NativeType>)%<outMaxStoreInt>;
      }
      else
      {
        %% /* cast quotient to output */
        %<retVal> = (%<cDT.NativeType>)%<tempQuotVar>;

    %endif
    %%
    %switch rndMeth
      %case "Nearest"
        %%
        %% /* determine if round to %<adjustedRndMeth> adjustment may be needed */
        
        %% /* multiply current numerator by two, keeping track of extra bit */
        numeratorExtraBit = (%<numerator> >= %<mask_ULONG_MS_BIT_SET>);
        %<numerator> <<= 1;
		
        %if needNegation != ""
          %%
          if ( numeratorExtraBit || ( %<needNegation> ? ( %<numerator> > %<denominator> ) : ( %<numerator> >= %<denominator> ) ) )
        %else
          if ( numeratorExtraBit || ( %<numerator> >= %<denominator> ) )
        %endif
        %%
        {
          %<retVal>++;
        }
        %%
        %break
      %case "Ceiling"
        %%
        if ( %<numerator> > 0 )
        {
          %<retVal>++;
        }
        %break
      %default
        %%
        %% do nothing
        %%
        %break
    %endswitch
    %%
    %if includeNonZeroSaturationCode
      }
    %endif
    %%
  } %% /* end guts */
%endfunction %% fixpt_div_repeat_unsigned_guts



%% This function is design to do the same thing as FIXPT CGIR function
%%    get_div_repeat_fcn
%% Do not change this function without coordinating changes in both.
%%
%% This version of the function requires the input arguments to be
%% prepared.  Namely, they have already been upcast to integer
%% sized used by the generated function
%%
%function FixPt_Division_RepeatSub_prep(cLabel,cDT,aArg,aDT,bArg,bDT,roundMode,satMode,protectZero,nRepeatSub) Output
    %<LibPushEmptyStackSharedUtils()>\
    %%
    %assign bitsPerLong = IntegerSizes.LongNumBits
    %assign bitsPerInt  = IntegerSizes.IntNumBits
    %%
    %% the ideal "IsSigned-ness" of the quotient
    %%  effects many parts of the code generation
    %%  so use a variable to make treatment of this condition more readable
    %%
    %assign anyInSigned = aDT.IsSigned || bDT.IsSigned
    %assign anySigned   = cDT.IsSigned || anyInSigned
    %%
    %if satMode == "Saturate"
      %assign includeSaturationCode = 1
    %else
      %assign includeSaturationCode = 0
    %endif	  
    %%
    %assign includeToZeroSaturationCode  = includeSaturationCode    && ...
                                           anyInSigned      && ...
                                           !cDT.IsSigned
    %%
    %assign canHaveUnSaturatedNegQuot    = anyInSigned  && ...
                                           !includeToZeroSaturationCode
    %%
    %assign adjustedRndMeth = FixPt_get_net_round_method_for_division(roundMode,canHaveUnSaturatedNegQuot)
    %%
    %assign noDivByZeroProtect = !protectZero
    %%
    %assign yesDivByZeroProtect = !noDivByZeroProtect 
    %%
    %assign utilityName = FixPt_UtilityMakeName("div")
    %%
    %if !protectZero
      %%
      %% identify that no division by zero protection is included
      %%
      %assign utilityName = utilityName + "_nzp"
    %endif
    %%
    %assign utilityName = utilityName + "_repeat"
    %%
    %assign appendDtName = FixPt_getDataTypeSubName(cDT,aDT,bDT)
    %%
    %assign utilityName = utilityName + appendDtName
    %%
    %% identify how overflows will be handled
    %%   the default "do nothing" mode is "WRAP".
    %%   This default mode will be
    %%   left off the utility name for brevity.
    %%
    %% when creating a general routine to do an arbitrary
    %% number of repeated subtractions it will be assumbed
    %% that saturation is always possible
    %%
    %if satMode == "Saturate"
      %assign utilityName = utilityName + "_sat"
    %endif	  
    %%
    %assign includeNonZeroSaturationCode = includeSaturationCode
    %%
    %% identify how rounding will be handled
    %%   If the mode leads to a "do nothing" then
    %%   the mode will be left off the utility name.
    %%
    %%   Round to zero is what is used by div and ldiv from C's
    %%   stdlib.h gives.  If division is always done on absolute
    %%   values with "post-restoration" of sign, then round to
    %%   zero is the no code rounding mode.
    %%     Perhaps this should be the default for division.  However,
    %%   in a product block with mixed multiplication and division
    %%   there can be only one rounding mode so both can't be "no code."
    %%   Of course, if all numbers are non-negative, then round to
    %%   zero is identical to round to floor.
    %%
    %assign includeRoundingCode = 0
    %%
    %if adjustedRndMeth == "Zero"
      %%
      %% do not append name
      %%
    %elseif adjustedRndMeth == "Nearest"
      %assign utilityName = utilityName + "_near"
      %%
      %assign includeRoundingCode = 1
      %%
    %elseif adjustedRndMeth == "Ceiling"
      %assign utilityName = utilityName + "_ceiling"
      %%
      %assign includeRoundingCode = 1
      %%
    %elseif adjustedRndMeth == "Floor"
      %assign utilityName = utilityName + "_floor"
      %%
      %assign includeRoundingCode = 1
      %%
    %else
      %assign utilityName = utilityName + "_ROUNDERROR"
      %%
    %endif
    %%
    %% END: Create a string to represent the division utility
    %%
    %% repeated subtractions will always use a function call
    %% never a macro
    %%
    %<cLabel> = %<utilityName>(%<aArg>,%<bArg>,%<nRepeatSub>);
    %%
    %% determine if the required utility has already been defined
    %%   If it has not, then create the definition.
    %%
    %if !(ISFIELD(FixPtUtils,utilityName))
      %%
      %% register that utility is being defined
      %%
      %assign tmpRet = SETFIELD(FixPtUtils,utilityName,1)
      %%
      %assign uLongName = "uint%<bitsPerLong>_T"
      %assign sLongName = "int%<bitsPerLong>_T"
      %%
      %assign uIntName = "uint%<bitsPerInt>_T"
      %assign sIntName = "int%<bitsPerInt>_T"
      %%
      %if !aDT.IsSigned
        %assign aArgType = uLongName
      %else
        %assign aArgType = sLongName
      %endif
      %%
      %if !bDT.IsSigned
        %assign bArgType = uLongName
      %else
        %assign bArgType = sLongName
      %endif
      %%
      %copyrecord cDT_abs cDT
      %%
      %if cDT_abs.IsSigned
        %%
        %assign cDT_abs.IsSigned = 0
        %assign cDT_abs.DataTypeName = LibFixPointFormDataTypeName(0,IntegerSizes.LongNumBits,0)
        %assign cDT_abs.NativeType   = "#error x"
        %%
        %<FixPt_DefineDataType(cDT_abs)>\
      %endif
      %%
      %copyrecord aDT_abs aDT
      %%
      %if aDT_abs.IsSigned
        %%
        %assign aDT_abs.IsSigned = 0
        %assign aDT_abs.DataTypeName = LibFixPointFormDataTypeName(0,IntegerSizes.LongNumBits,0)
        %assign aDT_abs.NativeType   = "#error x"
        %%
        %<FixPt_DefineDataType(aDT_abs)>\
      %endif
      %%
      %copyrecord bDT_abs bDT
      %%
      %if bDT_abs.IsSigned
        %%
        %assign bDT_abs.IsSigned = 0
        %assign bDT_abs.DataTypeName = LibFixPointFormDataTypeName(0,IntegerSizes.LongNumBits,0)
        %assign bDT_abs.NativeType   = "#error x"
        %%
        %<FixPt_DefineDataType(bDT_abs)>\
      %endif
      %%
      %assign needTwoUnsignedHelperFcn = 0
      %%
      %if anyInSigned
        %%
        %switch adjustedRndMeth
          %case "Floor"
          %case "Ceiling"
            %%
            %assign needTwoUnsignedHelperFcn = 1
            %break
        %endswitch
      %endif
      %%
      %assign Atag = "numerator"
      %%
      %assign Btag = "denominator"
      %%
      %assign Ctag = "quotient"
      %%
      %assign nRepeatLabel = "nRepeatSub"
      %%
      %% open a buffer to hold the utility header comments
      %%
      %openfile utilityHeaderComment
      %%
      %%  Produce header comment for utility
      %%
      
      /*********************************************************************
      * Fixed Point Division Utility %<utilityName>
      *   Values
      *      Vc = Va / Vb
      *   The implementation uses repeated subtractions
      *   to compute the division in fixed point
      *   integer math.
      *
      %%
      %% generate comments related to overflow
      %%
      *
      %%
      %% mention treatment of division by zero
      %%
      %%
      %if protectZero
        * Division By Zero
        *         0/0  will saturate to the output maximum
        *  positive/0  will saturate to the output maximum
        %%
        %if ( aDT.IsSigned )
          *  negative/0  will saturate to the output minimum
        %endif
      %else
        * Division By Zero
        *   is NOT protected
      %endif
      *
      %%
      %% note saturation/wrap status
      %%
      %if satMode == "Saturate"
        * overflows will SATURATE
        *    in addition to code for division by zero
        *    code specific to overflow management is included
      %else
        * overflows will WRAP (modulo 2)
        *    aside from code for division by zero
        *    no code specific to overflow management is required
      %endif
      %%
      %% generate comments related to rounding
      %%
      *
      %if adjustedRndMeth == "Zero"
        %%
        %% division uses absolute values so
        %% round to ZERO is the "do nothing mode"
        %%
        %if canHaveUnSaturatedNegQuot
          * round to ZERO
          *    no code specific to rounding is required
        %else
          %% ZERO like FLOOR because rounding of negatives
          %% never arises
          * round to ZERO  equivalent to
          * round to FLOOR because rounding of negatives does NOT arise
          *    no code specific to rounding is required
        %endif
      %elseif adjustedRndMeth == "Nearest"
        * round to NEAREST
        *    code specific to rounding is included
      %elseif adjustedRndMeth == "Ceiling"
        * round to CEILING
        *    code specific to rounding is included
      %elseif adjustedRndMeth == "Floor"
        %%
        %% division uses absolute values so
        %% round to FLOOR is a "do nothing mode" if
        %% rounding of negatives doesn't arise
        %%
        %if canHaveUnSaturatedNegQuot
          * round to FLOOR
          *    code specific to rounding is included
        %else
          %% ZERO like FLOOR because rounding of negatives
          %% never arises
          * round to ZERO  equivalent to
          * round to FLOOR because rounding of negatives does NOT arise
          *    no code specific to rounding is required
        %endif
      %else  %%if adjustedRndMeth == "Easiest"
        %%
        %if !canHaveUnSaturatedNegQuot
          * because rounding of negatives does NOT arise
          * round to ZERO  equivalent to 
          * round to FLOOR equivalent to
        %endif
        * round to EASIEST
        *    no code specific to rounding is included
      %endif
      %%
      %% Get output min and max in terms of stored integer
      %%
      %assign outMinStoreInt = FixPt_GetMinStr(cDT)
      %assign outMaxStoreInt = FixPt_GetMaxStr(cDT)
      %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
      %% open a buffer to hold the utility definition
      %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
      %openfile utilityDef
      %%
      %% create first line of utility macro or function
      %%
      %openfile funcProto
      %<cDT.NativeType> %<utilityName>(%<aArgType> %<Atag>, %<bArgType> %<Btag>, %<uIntName> %<nRepeatLabel>);
      %closefile funcProto
      %selectfile utilityDef
      %<cDT.NativeType> %<utilityName>(%<aArgType> %<Atag>, %<bArgType> %<Btag>, %<uIntName> %<nRepeatLabel>)
      { %% /* start fcn body */
        %<cDT.NativeType> %<Ctag>;
        %%
        %if anySigned 
          %<uLongName> tempAbsQuotient;
        %endif
        %%
        %% Handle division by zero
        %%  should we do this for WRAP or should we just
        %%  let happen what happens????
        %%
        %%  The argument in favor of handling this is the
        %%  prevention of undesired interrupts on processors
        %%  that hardware trap odd events like division by zero
        %%
        %if yesDivByZeroProtect
            if ( %<Btag> == 0)
            {
                %if !aDT.IsSigned
                    %%
                    %% /* division by zero, saturate to maximum */
                    %<Ctag> = (%<cDT.NativeType>)(%<outMaxStoreInt>);
                    %%
                %else
                    %%
                    %% /* division by zero, saturate to maximum or minimum */
                    %<Ctag> = (%<cDT.NativeType>)( %<Atag> >= 0 ? (%<outMaxStoreInt>) : (%<outMinStoreInt>) );
                    %%
                %endif
            }
            else
            { %% /* start divide by zero else */
        %endif
        %%
        %% the heart of division will work on absolute values of
        %% numbers.  The tags for the absolute values are initially
        %% set the same as the tags for the original numbers
        %% if the numbers are unsigned then these tags will remain unchanged
        %% but if the numbers are signed the tags will be replaced at a
        %% later point in this code
        %%
        %assign absAtag = Atag
        %assign absBtag = Btag
        %%
        %% if applicable determine sign of result
        %% and form absolute values of num and den
        %%
        %if anyInSigned
          %%
          %% declare variable to keep track of whether or not
          %% output C should be positive or negative
          %%   note the heart of the division uses absolute values
          %% so the intermediate quotient is always non-negative
          %% but the final quotient may need to be negative
          %%
          %% /* division is computed with absolute values,
          %%  * must track need to negate final result
          %%  */
          %if ( aDT.IsSigned )
            %%
            %assign absAtag = "absNumerator"
            %%
            %assign absAType = uLongName
            %%
          %endif
          %%
          %if ( bDT.IsSigned )
            %%
            %assign absBtag = "absDenominator"
            %%
            %assign absBType = uLongName
            %%
          %endif
          %%
          %% /* determine sign of quotient */
          %%
          %if ( aDT.IsSigned && bDT.IsSigned )
            %%
            %<sIntName> quotientNeedsNegation = %<Atag> < 0 != %<Btag> < 0;
            %%
          %elseif ( aDT.IsSigned )
            %%
            %% note don't need to check B
            %% because that would be division by zero
            %%
            %<sIntName> quotientNeedsNegation = %<Atag> < 0;
            %%
          %else
            %%
            %<sIntName> quotientNeedsNegation = %<Btag> < 0;
            %%
          %endif
          %%
          %% handle case of saturating negative number to zero
          %%   when the output is unsigned
          %%
%%          %if includeToZeroSaturationCode
%%            %%
%%            
%%            %% /* for unsigned output, saturate negative quotient to zero */
%%            if (quotientNeedsNegation)
%%            {
%%              %<Ctag> = 0;
%%            }
%%            else
%%            { %% /* start to zero saturation else case */
%%            %%
%%          %endif
          %%
          %if ( aDT.IsSigned )
            %%
            
            %<absAType> %<absAtag> = (%<absAType>)( %<Atag> < 0 ? -%<Atag> : %<Atag> );
          %endif
          %%
          %if ( bDT.IsSigned )
            %%
            
            %<absBType> %<absBtag> = (%<absBType>)( %<Btag> < 0 ? -%<Btag> : %<Btag> );
          %endif
          %%
          %if (!includeToZeroSaturationCode && !needTwoUnsignedHelperFcn)
            %%
            %if (adjustedRndMeth != "Nearest")
              %%
              %<FixPt_Division_RepeatSub_prep("tempAbsQuotient",cDT_abs,absAtag,aDT_abs,absBtag,bDT_abs,adjustedRndMeth,satMode,protectZero,nRepeatLabel)>\
              %%
            %else
              %<fixpt_div_repeat_unsigned_guts(cDT_abs,absAtag,...
                absBtag,...
                "tempAbsQuotient",...
                nRepeatLabel,...
                includeNonZeroSaturationCode,...
                adjustedRndMeth,...
                "quotientNeedsNegation" )>\
            %endif
            %%
            %if includeSaturationCode && cDT.IsSigned
              %%
              if ( quotientNeedsNegation )
              {
                %<Ctag> = (tempAbsQuotient <= ((%<uLongName>)(%<outMaxStoreInt>))) ? ((%<cDT.NativeType>)(-((%<sLongName>)tempAbsQuotient))) : (%<outMinStoreInt>);
              }
              else
              {
                %<Ctag> = (tempAbsQuotient <= ((%<uLongName>)(%<outMaxStoreInt>))) ? ((%<cDT.NativeType>)tempAbsQuotient) : (%<outMaxStoreInt>);
              }
            %else
              %<Ctag> = quotientNeedsNegation ? ((%<cDT.NativeType>)(-((%<sLongName>)tempAbsQuotient))) : ((%<cDT.NativeType>)tempAbsQuotient);
            %endif
          %else
            if ( quotientNeedsNegation )
            {
              %if cDT.IsSigned || !includeSaturationCode
                %%              
                %if needTwoUnsignedHelperFcn
                  %% 
                  %assign requiredRndMeth = 0
                  %%
                  %switch adjustedRndMeth
                      %%                
                    %case "Ceiling"
                      %%
                      %assign requiredRndMeth = "Zero"
                      %break
                    %case "Floor"
                      %assign requiredRndMeth = "Ceiling"
                      %break
                  %endswitch
                  %%
                  %<FixPt_Division_RepeatSub_prep("tempAbsQuotient",cDT_abs,absAtag,aDT_abs,absBtag,bDT_abs,requiredRndMeth,satMode,protectZero,nRepeatLabel)>\
                  %%
                %endif
                %%
                %if includeSaturationCode && cDT.IsSigned
                  %%              
                  %<Ctag> = (tempAbsQuotient <= ((%<uLongName>)(%<outMaxStoreInt>))) ? ((%<cDT.NativeType>)(-((%<sLongName>)tempAbsQuotient))) : (%<outMinStoreInt>);
                %else
                  %<Ctag> = ((%<cDT.NativeType>)(-((%<sLongName>)tempAbsQuotient)));
                %endif
              %else  
                %<Ctag> = 0;
              %endif
            }
            else
            {
              %if includeToZeroSaturationCode || needTwoUnsignedHelperFcn
                %%
                %<FixPt_Division_RepeatSub_prep("tempAbsQuotient",cDT_abs,absAtag,aDT_abs,absBtag,bDT_abs,adjustedRndMeth,satMode,protectZero,nRepeatLabel)>\
                %%
                %if includeSaturationCode && cDT.IsSigned
                  %%
                  %<Ctag> = (tempAbsQuotient <= ((%<uLongName>)(%<outMaxStoreInt>))) ? ((%<cDT.NativeType>)tempAbsQuotient) : (%<outMaxStoreInt>);
                  %%
                %else
                  %%
                  %<Ctag> = ((%<cDT.NativeType>)tempAbsQuotient);
                  %%
                %endif
              %endif
            }
          %endif
          %%
        %elseif anySigned 
          %%
          %% Both inputs are unsigned, 
          %% output is signed 
          %%
          %<FixPt_Division_RepeatSub_prep("tempAbsQuotient",cDT_abs,absAtag,aDT_abs,absBtag,bDT_abs,adjustedRndMeth,satMode,protectZero,nRepeatLabel)>\
          %%
          %if includeSaturationCode
            %%
            %<Ctag> = (tempAbsQuotient <= ((%<uLongName>)(%<outMaxStoreInt>))) ? ((%<cDT.NativeType>)tempAbsQuotient) : (%<outMaxStoreInt>);
            %%
          %else
            %%
            %<Ctag> = ((%<cDT.NativeType>)tempAbsQuotient);
            %%
          %endif
        %else
          %%
          %% Both inputs and output are unsigned 
          %%
          %<fixpt_div_repeat_unsigned_guts(cDT_abs,absAtag,...
            absBtag,...
            Ctag,...
            nRepeatLabel,...
            includeNonZeroSaturationCode,...
            adjustedRndMeth,...
            "" )>\
        %endif
      %%
      %% if emulating a smaller data type then force extra bits
      %% to sign value
      %%
      %<FixPt_EmulationSignExt(Ctag,cDT)>\
      %%
      %if yesDivByZeroProtect
        }  %% /* end divide by zero else */
      %endif
      
      return %<Ctag>;
      %%
      %% finish header comment
      %%
      %selectfile utilityHeaderComment
      */
      %closefile utilityHeaderComment
      %%
      %% finish off utility define
      %%
      %selectfile utilityDef
      } %% /* end fcn body */
      %closefile utilityDef
      %%
      %% create utility trailer comment
      %%
      %openfile utilityTrailerComment
      
      /* end function %<utilityName>
      *********************************************************************/
      %closefile utilityTrailerComment
      %%
      %% cause utility define to be included in generated code
      %%
      %assign utilityDef = utilityHeaderComment + utilityDef + utilityTrailerComment
      %%
      %<SLibDumpUtilsSourceCode(utilityName,funcProto,utilityDef)>\
      %<LibCacheFunctionPrototype(funcProto)>\
      %%  
    %endif  %% definition of div utility
    %%
    %assign GSUStackBuf = LibPopStackSharedUtilsIncludes()
%endfunction  %% FixPt_Division_RepeatSub_prep



%% This function is design to do the same thing as FIXPT CGIR function
%%    get_div_repeat_fcn
%% Do not change this function without coordinating changes in both.
%%
%function FixPt_Division_RepeatSubtraction(cLabel,cDT,aLabel,aDT,bLabel,bDT,roundMode,satMode,protectZero) Output
    %%
    %assign bitsPerLong = IntegerSizes.LongNumBits
    %assign bitsPerInt  = IntegerSizes.IntNumBits
    %%
    %%
    %% if output is less than a long, 
    %% then create an alternate output data type
    %% A long version of will be used in the division function
    %% A cast will then be used after the division to keep the number
    %% of generated division functions small
    %%
    %copyrecord cDT_Div cDT
    %copyrecord cDT_Fin cDT
    %%
    %if cDT.RequiredBits < IntegerSizes.LongNumBits
      %%
      %assign postCastRequired = 1
      %%
      %assign cDT_Div.DataTypeName = LibFixPointFormDataTypeName(cDT.IsSigned,IntegerSizes.LongNumBits,0)
      %assign cDT_Div.ActualBits   = IntegerSizes.LongNumBits
      %assign cDT_Div.RequiredBits = IntegerSizes.LongNumBits
      %assign cDT_Div.FixedExp     = 0
      %assign cDT_Div.FracSlope    = 1.0
      %assign cDT_Div.Bias         = 0.0
      %assign cDT_Div.NativeType   = "#error x"
      %%
      %<FixPt_DefineDataType(cDT_Div)>\
      %%
      %assign cDT_Fin.DataTypeName = LibFixPointFormDataTypeName(cDT.IsSigned,cDT.RequiredBits,        0)
      %assign cDT_Fin.FixedExp     = 0
      %assign cDT_Fin.FracSlope    = 1.0
      %assign cDT_Fin.Bias         = 0.0
      %assign cDT_Fin.NativeType   = "#error x"
      %%
      %<FixPt_DefineDataType(cDT_Fin)>\
      %%
    %else
      %%
      %assign postCastRequired = 0
      %%
    %endif
    %%
    %copyrecord aDT_Div aDT
    %%
    %if aDT.RequiredBits < IntegerSizes.LongNumBits
      %%
      %assign aDT_Div.DataTypeName = LibFixPointFormDataTypeName(aDT.IsSigned,IntegerSizes.LongNumBits,0)
      %assign aDT_Div.ActualBits   = IntegerSizes.LongNumBits
      %assign aDT_Div.RequiredBits = IntegerSizes.LongNumBits
      %assign aDT_Div.FixedExp     = 0
      %assign aDT_Div.FracSlope    = 1.0
      %assign aDT_Div.Bias         = 0.0
      %assign aDT_Div.NativeType   = "#error x"
      %%
      %<FixPt_DefineDataType(aDT_Div)>\
    %endif
    %%
    %copyrecord bDT_Div bDT
    %%
    %if bDT.RequiredBits < IntegerSizes.LongNumBits
      %%
      %assign bDT_Div.DataTypeName = LibFixPointFormDataTypeName(bDT.IsSigned,IntegerSizes.LongNumBits,0)
      %assign bDT_Div.ActualBits   = IntegerSizes.LongNumBits
      %assign bDT_Div.RequiredBits = IntegerSizes.LongNumBits
      %assign bDT_Div.FixedExp     = 0
      %assign bDT_Div.FracSlope    = 1.0
      %assign bDT_Div.Bias         = 0.0
      %assign bDT_Div.NativeType   = "#error x"
      %%
      %<FixPt_DefineDataType(bDT_Div)>\
    %endif
    %%
    %assign uLongName = "uint%<bitsPerLong>_T"
    %assign sLongName = "int%<bitsPerLong>_T"
    %%
    %assign uIntName = "uint%<bitsPerInt>_T"
    %assign sIntName = "int%<bitsPerInt>_T"
    %%
    %if !aDT.IsSigned
      %assign aArgType = uLongName
    %else
      %assign aArgType = sLongName
    %endif
    %%
    %if !bDT.IsSigned
      %assign bArgType = uLongName
    %else
      %assign bArgType = sLongName
    %endif
    %%
    %if (aDT.ActualBits < IntegerSizes.LongNumBits) 
      %assign aArg = "((%<aArgType>)(%<aLabel>))"
    %else
      %assign aArg = "(%<aLabel>)"
    %endif
    %%
    %% Calculate the extra precision bits in the output
    %% compared to the "natural" precision of A / B
    %% Positive means overall shift left
    %% Negative means overall shift right
    %%
    %assign ExPrec = (%<aDT.FixedExp> - %<bDT.FixedExp> - %<cDT.FixedExp>)
    %%
    %% compute values that help determine the form by which the
    %% quotient is computed.
    %%
    %assign PrecShiftULong = ( IntegerSizes.LongNumBits - aDT.RequiredBits )
    %%
    %% determine number of repeated subtractions that are necessary
    %%
    %assign nRepeatSub  = ( ExPrec - PrecShiftULong )
    %%
    %if PrecShiftULong > 0
      %assign aArg = "(%<aArg><<%<PrecShiftULong>)"
    %endif
    %%
    %if (bDT.ActualBits < IntegerSizes.LongNumBits) 
      %assign bArg = "((%<bArgType>)(%<bLabel>))"
    %else
      %assign bArg = "(%<bLabel>)"
    %endif
    %%
    %if postCastRequired
    {
      %assign cLabel_long = "quot_repeat_sub_long"
      %<cDT_Div.NativeType> %<cLabel_long>;
      
      %<FixPt_Division_RepeatSub_prep(cLabel_long,cDT_Div,...
                                          aArg,       aDT_Div,...
                                          bArg,       bDT_Div,...
                                          roundMode,satMode,...
                                          protectZero,...
                                          nRepeatSub)>\
      
      %<FixPt_Fix2FixAlwaysOutput(cLabel,     cDT_Fin,...
                                  cLabel_long,cDT_Div,...
                                  roundMode,satMode)>\
    }
    %else
      %<FixPt_Division_RepeatSub_prep(cLabel,cDT_Div,...
                                          aArg,  aDT_Div,...
                                          bArg,  bDT_Div,...
                                          roundMode,satMode,...
                                          protectZero,...
                                          nRepeatSub)>\
    %endif
    %%
    %%
%endfunction  %% FixPt_Division_RepeatSubtraction



%function FixPt_Division_TargetSpecific(cLabel,cDT,aLabel,aDT,bLabel,bDT,roundMode,includeSaturationCode,justCheck) Output
    %%
    %if cDT.RequiredBits != cDT.ActualBits
      %%
      %% don't bother with optimization if emulating smaller container
      %% in bigger container
      %%
      %return 0
    %endif
    %%
    %if includeSaturationCode
      %%
      %% Saturation case is not yet supported for this optimization
      %% handling -128/-1 overflowing from ideal of +128 back to -128
      %% significantly complicates things
      %%
      %return 0
    %endif
    %%
    %if !cDT.IsSigned || ...
        !aDT.IsSigned || ...
        !bDT.IsSigned 
      %%
      %% target specific division optimization only needed for 
      %% signed division and only attempted if homogenously signed
      %%
      %return 0
    %endif
    %%
    %if cDT.RequiredBits <= IntegerSizes.IntNumBits && ...
        aDT.RequiredBits <= IntegerSizes.IntNumBits && ...
        bDT.RequiredBits <= IntegerSizes.IntNumBits 
      %%
      %assign divBits = IntegerSizes.IntNumBits
    %else
      %assign divBits = IntegerSizes.LongNumBits
    %endif
    %%
    %% Calculate the extra precision bits in the output
    %% compared to the "natural" precision of A / B
    %% Positive means overall shift left
    %% Negative means overall shift right
    %%
    %assign ExPrec = (%<aDT.FixedExp> - %<bDT.FixedExp> - %<cDT.FixedExp>)
    %%
    %assign topShiftLeft = 0
    %%
    %if ExPrec < 0
      %%
      %% Precision reduction required
      %%   See if precision can be fully reduced by shifting
      %%   left denominator prior to division.
      %%      If not, may be using just an int so try a long
      %%
      %if divBits < ( bDT.RequiredBits - ExPrec )
        %%
        %assign divBits = IntegerSizes.LongNumBits
      %endif
      %%
      %if divBits < ( bDT.RequiredBits - ExPrec )
        %%
        %return 0
      %endif
      %%
    %elseif ExPrec > 0
      %%
      %% Extra precision required
      %%   See if extra precision can be fully obtained
      %%   by shifting numerator left prior to division
      %%     If not, may be using just an int so try a long
      %%
      %assign topShiftLeft = ExPrec
      %%
      %if divBits < ( aDT.RequiredBits + topShiftLeft )
        %%
        %assign divBits = IntegerSizes.LongNumBits
      %endif
      %%
      %if divBits < ( aDT.RequiredBits + topShiftLeft )
        %%
        %return 0
      %endif
    %endif
    %%
    %if divBits == ( aDT.RequiredBits + topShiftLeft )
      %%
      %% Possible Arithmetic Exception for
      %%   INT_MIN  / -1   or
      %%   LONG_MIN / -1
      %%
      %% This will be ignored if Exception Protect is Not Wanted
      %%
      %if !FixPt_OptimizeAwayDivisionProtection()
        %%
        %% Protection is wanted, so try to do division in long,
        %% if already in a long then bail-out
        %% 
        %if divBits < IntegerSizes.LongNumBits
          %%
          %assign divBits = IntegerSizes.LongNumBits
        %else
          %return 0
        %endif
      %endif
      %%
    %endif
    %%
    %if roundMode != "Floor"   && ...
        roundMode != "Zero"    && ...
        roundMode != "Ceiling"
      %%
      %return 0
    %endif
    %%
    %assign TargetIntDivRoundTo = FixPt_TargetIntDivRoundTo()
    %%
    %if !ISEQUAL(TargetIntDivRoundTo,"Floor")   && ...
        !ISEQUAL(TargetIntDivRoundTo,"Zero")
      %%
      %return 0
    %endif
    %%
    %if !justCheck
      %%
      %assign divType = "int%<divBits>_T"
      %%
      %if aDT.RequiredBits < divBits
        %%
        %assign aCastLabel = "((%<divType>)%<aLabel>)"
      %else
        %assign aCastLabel = aLabel
      %endif
      %%
      %if bDT.RequiredBits < divBits
        %%
        %assign bCastLabel = "((%<divType>)%<bLabel>)"
      %else
        %assign bCastLabel = bLabel
      %endif
      %%
      %if cDT.RequiredBits == divBits
        %%
        %assign cLeftCast = ""
        %assign cRghtCast = ""
      %else
        %assign cLeftCast = "(%<cDT.NativeType>)( "
        %assign cRghtCast = " )"
      %endif    
      %%
      %assign roundModMatch = ISEQUAL(roundMode,TargetIntDivRoundTo)
      %%
      %if roundModMatch
        %%
        %if ExPrec < 0
          %%
          %% Handle case where output precision is less than natural precision
          %%   For this case, shifts right after division are needed
          %%
          %assign bCastLabel = "( %<bCastLabel> << %<-ExPrec> )"
          %%
        %elseif ExPrec > 0
          %%
          %assign aCastLabel = "( %<aCastLabel> << %<ExPrec> )"
          %%
        %endif
        %%
        %<cLabel> = %<cLeftCast>%<aCastLabel> / %<bCastLabel>%<cRghtCast>;
        %%
      %else
        %%
        %if ExPrec != 0
          %%
          %assign tempName = "s%<divBits>_DivisionTemp"
          %%
          %if ExPrec < 0
            %%
            %% Handle case where output precision is less than natural precision
            %%   For this case, shifts right after division are needed
            %%
            %<divType> %<tempName> = %<bCastLabel> << %<-ExPrec>;
            %%
            %assign bCastLabel = tempName
            %%
          %elseif ExPrec > 0
            %%
            %<divType> %<tempName> = %<aCastLabel> << %<ExPrec>;
            %%
            %assign aCastLabel = tempName
            %%
          %endif
        %endif
        %%
        %if ISEQUAL(TargetIntDivRoundTo,"Zero")
          %%
          %if     roundMode == "Floor"
            %%
            %<cLabel> = %<cLeftCast>(%<aCastLabel> / %<bCastLabel>) + ( ( ((%<aLabel><0)!=(%<bLabel><0)) && (%<aCastLabel> % %<bCastLabel>) ) ? -1 : 0 )%<cRghtCast>;
            %%
          %elseif roundMode == "Ceiling"
            %%
            %<cLabel> = %<cLeftCast>(%<aCastLabel> / %<bCastLabel>) + ( ( ((%<aLabel><0)==(%<bLabel><0)) && (%<aCastLabel> % %<bCastLabel>) ) ? 1 : 0 )%<cRghtCast>;
            %%
          %else
            %<LibReportFatalError("Unhandled rounding combinations in optimized division.")>
          %endif
          %%
        %elseif ISEQUAL(TargetIntDivRoundTo,"Floor")
          %%
          %if     roundMode == "Zero"
            %%
            %<cLabel> = %<cLeftCast>(%<aCastLabel> / %<bCastLabel>) + ( ( ((%<aLabel><0)!=(%<bLabel><0)) && (%<aCastLabel> % %<bCastLabel>) ) ? 1 : 0 )%<cRghtCast>;
            %%
          %elseif roundMode == "Ceiling"
            %%
            %<cLabel> = %<cLeftCast>(%<aCastLabel> / %<bCastLabel>) + ( (%<aCastLabel> % %<bCastLabel>) != 0 )%<cRghtCast>;
            %%
          %else
            %<LibReportFatalError("Unhandled rounding combinations in optimized division.")>
          %endif 
        %else
          %<LibReportFatalError("Unhandled rounding combinations in optimized division.")>
        %endif
        %%
      %endif
    %endif
    %%
    %return 1
%endfunction  %% FixPt_Division_TargetSpecific
    


%function FixPt_Division_StraightShot(cLabel,cDT,aLabel,aDT,bLabel,bDT,roundMode,satMode,protectZero) Output
    %<LibPushEmptyStackSharedUtils()>\
    %%
    %% the ideal "IsSigned-ness" of the quotient
    %%  effects many parts of the code generation
    %%  so use a variable to make treatment of this condition more readable
    %%
    %assign outputCanNotStoreNegQuot = !cDT.IsSigned
    %%
    %assign canHaveIdealNegQuot      = aDT.IsSigned || bDT.IsSigned
    %%
    %% Calculate the extra precision bits in the output
    %% compared to the "natural" precision of A / B
    %% Positive means overall shift left
    %% Negative means overall shift right
    %%
    %assign ExPrec = (%<aDT.FixedExp> - %<bDT.FixedExp> - %<cDT.FixedExp>)
    %%
    %if ExPrec > 0
      %<LibBlockReportFatalError(block,"Repeated Subtraction should not be required if this function is called.")>
    %endif
    %%
    %assign numShiftRight = -ExPrec
    %%
    %assign needShiftRight = (numShiftRight > 0)
    %%
    %assign noDivByZeroProtect = !protectZero
    %%
    %assign yesDivByZeroProtect = !noDivByZeroProtect 
    %%
    %assign two_tuple = fixpt_div_overflow_possible(cDT,aDT,bDT,roundMode,0)
    %assign overflowPossible = two_tuple[0]
    %assign overflowOnlyToZero = two_tuple[1]
    %%
    %assign includeSaturationCode = (satMode == "Saturate") && overflowPossible
    %%
    %assign includeNonZeroSaturationCode = (includeSaturationCode && ...
                                            !overflowOnlyToZero)
    %%
    %assign includeToZeroSaturationCode = (includeSaturationCode && ...
                                           canHaveIdealNegQuot && ...
                                           outputCanNotStoreNegQuot)
    %%
    %assign canHaveUnSaturatedNegQuot = (canHaveIdealNegQuot && ...
                                         !includeToZeroSaturationCode)
    %%
    %assign adjustedRndMeth = FixPt_get_net_round_method_for_division(roundMode,canHaveUnSaturatedNegQuot)
    %%
    %assign FixPt_Division_UtilType = "function"
    %%
    %if !needShiftRight && !includeSaturationCode && adjustedRndMeth != "Nearest" && adjustedRndMeth != "Ceiling"
      %%
      %if ( aDT.IsSigned || bDT.IsSigned )
        %%
        %assign canDoTargetSpecific = FixPt_Division_TargetSpecific("#error",cDT,"#error",aDT,"#error",bDT,adjustedRndMeth,includeSaturationCode,1)
        %%      
        %if canDoTargetSpecific
          %%
          %assign FixPt_Division_UtilType = "macro"
        %endif
      %else
        %%
        %assign FixPt_Division_UtilType = "macro"
      %endif
    %endif      
    %%
    %% Create a string to represent the division utility
    %%
    %if FixPt_Division_UtilType == "macro"
      %%
      %assign utilityName = "DIV_MACRO"
    %else
      %assign utilityName = "div"
    %endif
    %assign utilityName = FixPt_UtilityMakeName(utilityName)
    %%
    %if noDivByZeroProtect
      %%
      %assign utilityName = utilityName + "_nzp"
    %endif
    %%
    %assign appendDtName = FixPt_getDataTypeSubName(cDT,aDT,bDT)
    %%
    %assign utilityName = utilityName + appendDtName
    %%
    %% identify amount of left shifting or right shifting
    %% if any
    %%
    %if needShiftRight
      %assign utilityName = utilityName + "_SR"
    %endif
    %%    
    %if includeSaturationCode
      %assign utilityName = utilityName + "_sat"
    %endif	  
    %%
    %if adjustedRndMeth == "Zero"
      %%
      %% do not append name
      %%
    %elseif adjustedRndMeth == "Nearest"
      %assign utilityName = utilityName + "_near"
      %%
    %elseif adjustedRndMeth == "Ceiling"
      %assign utilityName = utilityName + "_ceiling"
      %%
    %elseif adjustedRndMeth == "Floor"
      %assign utilityName = utilityName + "_floor"
      %%
    %else
      %<LibBlockReportFatalError(block,"Unknown rounding mode = %<adjustedRndMeth>.")>
    %endif
    %%    
    %if FixPt_Division_UtilType == "macro"
      %if needShiftRight
        %<LibReportFatalError("Should not be attempting to use a macro when fixed-point division requires shift rights.")>
        %<utilityName>(%<cLabel>,%<aLabel>,%<bLabel>,%<numShiftRight>);
      %else
        %<utilityName>(%<cLabel>,%<aLabel>,%<bLabel>);
      %endif
      %%
      %% case of C function call
      %%
    %else
      %if needShiftRight
        %<cLabel> = %<utilityName>(%<aLabel>,%<bLabel>,%<numShiftRight>);
      %else
        %<cLabel> = %<utilityName>(%<aLabel>,%<bLabel>);
      %endif
    %endif
    %%
    %% determine if the required utility has already been defined
    %%   If it has not, then create the definition.
    %%
    %if !(ISFIELD(FixPtUtils,utilityName))
        %%
        %% compute values that help determine the form by which the
        %% quotient is computed.
        %%
        %assign PrecShiftUInt  = ( IntegerSizes.IntNumBits  - aDT.RequiredBits )
        %assign PrecShiftULong = ( IntegerSizes.LongNumBits - aDT.RequiredBits )
        %%
        %% useful bit mask
        %%
        %assign mask_ULONG_MS_BIT_SET = SetMSNBitsStr(1,IntegerSizes.LongNumBits,0)
        %%
        %%
        %% register that utility is being defined
        %%
        %assign tmpRet = SETFIELD(FixPtUtils,utilityName,1)
        %%
        %assign bitsPerLong = IntegerSizes.LongNumBits
        %assign bitsPerInt  = IntegerSizes.IntNumBits
        %%
        %assign unsignedOrigNumerator = !aDT.IsSigned
        %assign unsignedOrigDenom     = !bDT.IsSigned

        %assign uLongName = "uint%<bitsPerLong>_T"
        %assign sLongName = "int%<bitsPerLong>_T"
        %%
        %assign uIntName = "uint%<bitsPerInt>_T"
        %assign sIntName = "int%<bitsPerInt>_T"
        %%
        %assign Atag = "numerator"
        %%
        %assign Btag = "denominator"
        %%
        %assign Ctag = "quotient"
        %%
        %if needShiftRight
          %assign nShiftRightLabel = "nShiftRight"
        %else
          %assign nShiftRightLabel = "#error Should not use shift right variable"
        %endif
        %%
        %assign calcNumType = aDT.NativeType
        %assign calcDenType = bDT.NativeType
        %%
        %assign finalQuotType = cDT.NativeType
        %%
        %assign absNumCalcType = calcNumType
        %assign absDenCalcType = calcDenType
        %%
        %assign tempAbsQuotType = finalQuotType
        %%
        %assign signedAbsQuotType = "#error signedAbsQuotType data type used but not yet defined"
        %%
        %openfile utilityHeaderComment

        /*********************************************************************
         * Fixed Point Division Utility %<utilityName>
         */
        %closefile utilityHeaderComment
        %%
        %% Get output min and max in terms of stored integer
        %%
        %assign outMinStoreInt = FixPt_GetMinStr(cDT)
        %assign outMaxStoreInt = FixPt_GetMaxStr(cDT)
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        %% open a buffer to hold the utility definition
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        %openfile utilityDef
        %%
        %% create first line of utility macro or function
        %%
        %% case of C language macro
        %if FixPt_Division_UtilType == "macro"
          %if needShiftRight
            #define %<utilityName>(%<Ctag>,%<Atag>,%<Btag>,%<nShiftRightLabel>)
          %else
            #define %<utilityName>(%<Ctag>,%<Atag>,%<Btag>)
          %endif    
          %%
          %% Protect against precedence issues in use of macro arguments
          %%
          %assign Atag = "(%<Atag>)"
          %assign Btag = "(%<Btag>)"
          %assign Ctag = "(%<Ctag>)"
          %assign nShiftRightLabel = "(%<nShiftRightLabel>)"
        %%
        %% case of C function
        %%   including prototype definition
        %%
        %else
          %assign protoStr = "%<finalQuotType> %<utilityName>( %<calcNumType> %<Atag>, %<calcDenType> %<Btag>"
          %if needShiftRight
            %assign protoStr = protoStr + ",%<uIntName> %<nShiftRightLabel>)"
          %else
            %assign protoStr = protoStr + ")"
          %endif
          %openfile funcProto
	  %<protoStr>;
	  %closefile funcProto
	  %selectfile utilityDef
	  %<protoStr>
        %endif
      %%
      %% Give special treatment to the simple cases
      %%    inorder to get simplest code possible
      %%
      %if FixPt_Division_UtilType == "macro"  && ...
          !aDT.IsSigned && !bDT.IsSigned     && ...
          adjustedRndMeth == "Zero"          && ...
          !needShiftRight                    && ... 
          !includeSaturationCode             && ...
          cDT.RequiredBits == cDT.ActualBits
        %%
        %if yesDivByZeroProtect
          %%
          %<Ctag> = (%<Btag>==0) ? (%<finalQuotType>)(%<outMaxStoreInt>) : (%<finalQuotType>)(%<Atag> / %<Btag>);
        %else
          %<Ctag> = (%<finalQuotType>)(%<Atag> / %<Btag>);
        %endif
      %else
        %%
        { %% /* start fcn body */
          %if FixPt_Division_UtilType != "macro"
            %<finalQuotType> %<Ctag>;
          %endif
        %%
        %if yesDivByZeroProtect
            if ( %<Btag> == 0)
            {
                %if !aDT.IsSigned
                    %%
                    %<Ctag> = (%<finalQuotType>)(%<outMaxStoreInt>);
                    %%
                %else
                    %%
                    %% /* saturate to maximum or minimum */
                    %<Ctag> = (%<finalQuotType>)( %<Atag> >= 0 ? (%<outMaxStoreInt>) : (%<outMinStoreInt>) );
                    %%
                %endif
            }
            else
            { %% /* start div zero else case */
        %endif
        %%
        %assign didTargetSpecific = FixPt_Division_TargetSpecific(Ctag,cDT,Atag,aDT,Btag,bDT,roundMode,includeSaturationCode,0)
        %%
        %if !didTargetSpecific         
          %%
          %% the heart of division will work on absolute values of
          %% numbers.  The tags for the absolute values are initially
          %% set the same as the tags for the original numbers
          %% if the numbers are unsigned then these tags will remain unchanged
          %% but if the numbers are signed the tags will be replaced at a
          %% later point in this code
          %%
          %assign absAtag = Atag
          %assign absBtag = Btag
          %%
          %if ( aDT.IsSigned )
            %%
            %assign absAtag = "absNumerator"
            %%
            %if ( aDT.RequiredBits <= IntegerSizes.IntNumBits )
              %%
              %assign absAType = uIntName
            %else
              %assign absAType = uLongName
            %endif
          %endif
          %%
          %if ( bDT.IsSigned )
            %%
            %assign absBtag = "absDenominator"
            %%
            %if ( bDT.RequiredBits <= IntegerSizes.IntNumBits )
              %%
              %assign absBType = uIntName
            %else
              %assign absBType = uLongName
            %endif
          %endif
          %%
          %if ( includeSaturationCode || ...
                 cDT.IsSigned || ...
                 cDT.RequiredBits < aDT.RequiredBits )
            %%
            %if ( aDT.RequiredBits > bitsPerInt )
              %%
              %assign tempAbsQuotType = uLongName
            %else
              %assign tempAbsQuotType = uIntName
            %endif
          %endif
          %%
          %if tempAbsQuotType == uLongName
            %%
            %assign signedAbsQuotType = sLongName
          %else
            %assign signedAbsQuotType = sIntName
          %endif
          %%
          %assign tempAbsQuotLabel = "tempAbsQuotient"
          %%
          %<tempAbsQuotType> %<tempAbsQuotLabel>;
          %%
          %if needShiftRight && adjustedRndMeth != "Zero"
            %%
            %assign tempAbsQuotReducedLabel = "tempAbsQuotReduced"
            %%
            %<tempAbsQuotType> %<tempAbsQuotReducedLabel>;
          %else
            %assign tempAbsQuotReducedLabel = tempAbsQuotLabel
          %endif
          %%
          %if ( aDT.IsSigned )
            %%
            %<absAType> %<absAtag> = (%<absAType>)( %<Atag> < 0 ? -%<Atag> : %<Atag> );
          %endif
          %%
          %if ( bDT.IsSigned )
            %%
            %<absBType> %<absBtag> = (%<absBType>)( %<Btag> < 0 ? -%<Btag> : %<Btag> );
          %endif
          %%
          %% if applicable determine sign of result
          %% and form absolute values of num and den
          %%
          %if canHaveIdealNegQuot
            %%
            %% /* determine sign of quotient */
            %%
            %if ( aDT.IsSigned && bDT.IsSigned )
              %%
              int quotientNeedsNegation = %<Atag> < 0 != %<Btag> < 0;
              %%
            %elseif ( aDT.IsSigned )
              %%
              %% note don't need to check B
              %% because that would be division by zero
              %%
              int quotientNeedsNegation = %<Atag> < 0;
            %else
              int quotientNeedsNegation = %<Btag> < 0;
            %endif
          %endif
          %%
          %% handle case of saturating negative number to zero
          %%   when the output is unsigned
          %%
          %if includeToZeroSaturationCode
            %%
            %% /* for unsigned output, saturate negative quotient to zero */
            if (quotientNeedsNegation)
            {
              %<Ctag> = 0;
            }
            else
            { %% /* start to zero saturation else case */
              %%
          %endif
          %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	  %%
	  %%  compute quotient
	  %%
	  %% %if canHaveIdealNegQuot
	  %%    
	  %%    /* compute absolute value of quotient */
	  %% %else
	  %%    /* compute quotient */
	  %% %endif
          %%
          %<tempAbsQuotLabel> = (%<tempAbsQuotType>)(%<absAtag> / %<absBtag>);
          %%
          %if ( aDT.RequiredBits > bitsPerInt )
            %%
            %assign shiftLimit = bitsPerLong
          %else
            %assign shiftLimit = bitsPerInt
          %endif
          %%
          %if (needShiftRight)
            %%
            %<tempAbsQuotReducedLabel> = ( %<nShiftRightLabel> >= %<shiftLimit> ) ? (%<tempAbsQuotType>)(0U) : ( %<tempAbsQuotLabel> >> %<nShiftRightLabel> );
          %endif
          %%
          %% check for saturation
          %%
          %if includeNonZeroSaturationCode
	      %%
	      %% make sure things at exact limit are saturated too.
	      %%   this avoids having to worry about saturations
	      %%   again when a rounding increment or decrement is
	      %%   preformed
	      %%
	      %% /* check quotient for saturation */
	      %%
	      %% Handle case of saturation to either min or max
	      %%
	      %if canHaveIdealNegQuot && cDT.IsSigned
		%%
		if ( !quotientNeedsNegation && ( %<tempAbsQuotReducedLabel> >= (%<tempAbsQuotType>)(%<outMaxStoreInt>) ) )
		{
		  %% /* saturate to maximum */
		  %<Ctag> = (%<finalQuotType>)%<outMaxStoreInt>;
		}
		else if ( quotientNeedsNegation && ( %<tempAbsQuotReducedLabel> > (%<tempAbsQuotType>)(%<outMaxStoreInt>) ) )
		{
		  %% /* saturate to minimum */
		  %<Ctag> = (%<finalQuotType>)%<outMinStoreInt>;
		}
	      %else
		if ( %<tempQuotLabel> >= (%<tempAbsQuotType>)(%<outMaxStoreInt>) )
		{
		  %% /* saturate to maximum */
		  %<Ctag> = (%<finalQuotType>)%<outMaxStoreInt>;
		}
	      %endif
              else
              { %% /* start non-zero saturation else case */
          %endif
          %%
          %switch adjustedRndMeth
            %%
            %case "Floor"
              %%
              %if canHaveUnSaturatedNegQuot
                %%
                if (quotientNeedsNegation)
                {
                  %<absAtag> %= %<absBtag>;
                  %%
                  %if ( !needShiftRight )
                    %%
                    if ( %<absAtag> > 0 )
                    {
                    %%
                  %else
                    %assign mask = SetLSNBitsStr(shiftLimit,shiftLimit,0)
                    %%
                    if ( ( %<absAtag> > 0 ) || ( ( %<nShiftRightLabel> >= %<shiftLimit> ) ? %<tempAbsQuotLabel> : (%<tempAbsQuotLabel> & (%<mask> >> (%<shiftLimit> - %<nShiftRightLabel>)))))
                    {
                  %endif
                  %%
                    %<tempAbsQuotReducedLabel>++;
                  } 
                }
              %endif
              %break        
              %%
            %case "Ceiling"
              %%
              %if canHaveUnSaturatedNegQuot
                %%
                if (!quotientNeedsNegation)
                {
              %endif
              %%
              %<absAtag> %= %<absBtag>;
              %%
              %if ( !needShiftRight )
                %%
                if ( %<absAtag> > 0 )
                %%
              %else
                %assign mask = SetLSNBitsStr(shiftLimit,shiftLimit,0)
                %%
                if ( ( %<absAtag> > 0 ) || ( ( %<nShiftRightLabel> >= %<shiftLimit> ) ? %<tempAbsQuotLabel> : (%<tempAbsQuotLabel> & (%<mask> >> (%<shiftLimit> - %<nShiftRightLabel>)))))
              %endif
              %%
              {
                %<tempAbsQuotReducedLabel>++;
              } 
              %%
              %if canHaveUnSaturatedNegQuot
                %%
                }
              %endif
              %break
              %%
            %case "Nearest"
              %%
              %if ( !needShiftRight )
                %%
                %<absAtag> %= %<absBtag>;
                %%
                %if canHaveUnSaturatedNegQuot
                  %%
                  %if unsignedOrigDenom
                    %%
                    %assign limitConst = SetLSNBitsStr(shiftLimit-1,shiftLimit,0)
                    %%
                    if ( %<absAtag> > %<limitConst> )
                    {
                      %<tempAbsQuotReducedLabel>++;
                    } 
                    else
                    {
                  %endif
                  %%
                  %<absAtag> <<= 1;
                  %%
                  if ( (%<absAtag> >= %<absBtag>) && ( !quotientNeedsNegation || (%<absAtag> > %<absBtag>) ) )
                  {
                      %<tempAbsQuotReducedLabel>++;
                  } 
                  %%
                  %if unsignedOrigDenom
                    %%
                    }
                  %endif
                %else
                  %%
                  %if unsignedOrigDenom
                    %%
                    %assign limitConst = SetLSNBitsStr(shiftLimit-1,shiftLimit,0)
                    %%
                    if ( %<absAtag> > %<limitConst> || ( (%<absAtag> << 1) >= %<absBtag>) )
                    {
                      %<tempAbsQuotReducedLabel>++;
                    } 
                  %else
                    %%
                    if ( (%<absAtag> << 1) >= %<absBtag> )
                    {
                      %<tempAbsQuotReducedLabel>++;
                    } 
                  %endif
                %endif
              %else  
                %%
                {
                  %assign quotDropBits = tempAbsQuotLabel
                  %%
                  %<tempAbsQuotType> maskMSdropoffBit;
                  %%
                  %assign mask = SetLSNBitsStr(shiftLimit,shiftLimit,0)
                  %%
                  %if shiftLimit > bitsPerInt
                    %assign oneMask = "1UL"
                  %else
                    %assign oneMask = "1U"
                  %endif
                  %%
                  if ( %<nShiftRightLabel> <= %<shiftLimit> )
                  {
                    %<quotDropBits> = %<tempAbsQuotLabel> & ( %<mask> >> ( %<shiftLimit> - %<nShiftRightLabel> ) );
                    %%
                    maskMSdropoffBit = %<oneMask> << ( %<nShiftRightLabel> - 1 );
                    %%
                    if ( %<quotDropBits> >= maskMSdropoffBit )
                    {
                      %if canHaveUnSaturatedNegQuot
                        %%
                        if ( !quotientNeedsNegation || %<quotDropBits> > maskMSdropoffBit || %<absAtag> % %<absBtag> )
                        {
                          %<tempAbsQuotReducedLabel>++;
                        } 
                      %else
                        %<tempAbsQuotReducedLabel>++;
                      %endif
                    }
                  }
                }
              %endif
              %break
              %%
          %endswitch
          %%
          %if canHaveUnSaturatedNegQuot
            %%
            %<Ctag> = quotientNeedsNegation ? ((%<finalQuotType>)( -((%<signedAbsQuotType>)(%<tempAbsQuotReducedLabel>)) )) : ((%<finalQuotType>)(%<tempAbsQuotReducedLabel>));
            %%
          %else
            %%
            %<Ctag> = (%<finalQuotType>)(%<tempAbsQuotReducedLabel>);
            %%
          %endif 
          %%
          %% if emulating a smaller data type then force extra bits
          %% to sign value
          %%
          %<FixPt_EmulationSignExt(Ctag,cDT)>\
          %%
          %if includeNonZeroSaturationCode
            %%
              } %% /* end non-zero saturation else case */
          %endif
          %%
          %if includeToZeroSaturationCode
            } %% /* end to zero saturation else case */
          %endif
        %endif
        %%
        %if yesDivByZeroProtect
          } %% /* end divide by zero else case */
        %endif
        %%
        %if FixPt_Division_UtilType != "macro"
          return %<Ctag>;
        %endif
        %%
        %% finish off utility define
        %%
        } %% /* end fcn body */
        %%
      %endif  %% !didSpecialSimpleCases
        %%
        %closefile utilityDef
        %%
        %%
        %% For the case of C macro,
        %%    convert end of lines to backslash end of lines
        %%    as required for multiline C macros
        %%
        %if FixPt_Division_UtilType == "macro"
            %assign utilityDef = FEVAL("strrep",utilityDef,"\n"," \\\n")
        %endif
        %%
        %% create utility trailer comment
        %%
        %openfile utilityTrailerComment

        /* end %<FixPt_Division_UtilType> %<utilityName>
         *********************************************************************/
        %closefile utilityTrailerComment
        %%
        %% cause utility define to be included in generated code
        %%
        %assign utilityDef = utilityHeaderComment + utilityDef + utilityTrailerComment
        %%
        %if FixPt_Division_UtilType == "macro"
            %<SLibDumpUtilsMacro(utilityName,utilityDef)>\
        %else
            %<SLibDumpUtilsSourceCode(utilityName,funcProto,utilityDef)>\
            %<LibCacheFunctionPrototype(funcProto)>\
        %endif
        %%
    %endif  %% definition of div utility
    %assign GSUStackBuf = LibPopStackSharedUtilsIncludes()
%endfunction  %% FixPt_Division_StraightShot



/% Some Examples

wolog assume Ea = Eb = 0
so ExPrec = -Ec

IntegerSizes.LongNumBits = 8
IntegerSizes.IntNumBits  = 4

Example 1

A = 1011b = 11t
B = 1100b = 12t

ExPrec = 3

Calc is
LongA = A << 3 = 01011000b = 88t
C = LongA / B = 88t / 12t = 7t

Calculated Real World Value is 7*2^-3 = 0.8750
compared to the True Real World Value  0.9167
so the error is 0.0417 which is less than the precision 0.125 of C
*/

/* Example 2

A = 00001011b = 11t
B = 1100b = 12t

ExPrec = 4

Calc is
lden = B = 00001100b = 12t
lnum = A = 00001011b = 11t

C = lnum / lden = 00000000b =  0t
lnum %= lden    = 00001011b = 11t

i = 0
  C    <<= 1 = 00000000b =  0t
  lnum <<= 1 = 00010110b = 22t
    C    += 1    = 00000001b =  1t
    lnum -= lden = 00001010b = 10t = (22t-12t)
i = 1
  C    <<= 1 = 00000010b =  2t
  lnum <<= 1 = 00010100b = 20t
    C    += 1    = 00000011b =  3t
    lnum -= lden = 00001000b =  8t = (20t-12t)
i = 2
  C    <<= 1 = 00000110b =  6t
  lnum <<= 1 = 00010000b = 16t
    C    += 1    = 00000111b =  7t
    lnum -= lden = 00000100b =  4t = (16t-12t)
i = 3
  C    <<= 1 = 00001110b = 14t
  lnum <<= 1 = 00000100b =  4t
i = 4

Calculated Real World Value is 14*2^-4 = 0.8750
compared to the True Real World Value  0.9167
so the error is 0.0417 which is less than the precision 0.0625 of C


Example 3

A = 11000000b = 192t
B = 10100000b = 160t

ExPrec = 5

Calc is
lnum = A = 11000000b = 192t
lden = B = 10100000b = 160t

C = lnum / lden = 00000001b =   1t
lnum %= lden    = 00100000b =  32t
numeratorExtraBit = 0;


i = 0
  C    <<= 1 = 00000001b =  2t
  numeratorExtraBit = lnum >> 7 = 0t
  lnum <<= 1 = 01000000b = 64t
i = 1
  C    <<= 1 = 00000100b =  4t
  numeratorExtraBit = lnum >> 7 = 0t
  lnum <<= 1 = 10000000b = 128t
i = 2
  C    <<= 1 = 00001000b =  8t
  numeratorExtraBit = lnum >> 7 = 1t
  lnum <<= 1 = 00000000b = 0t
    Note numeratorExtraBit:lnum = 100000000b = 256t
    C    += 1    = 00001001b =  9t
    lnum -= lden = 01100000b = 96t = (256t-160t)
i = 3
  C    <<= 1 = 00010010b = 18t
  numeratorExtraBit = lnum >> 7 = 0t
  lnum <<= 1 = 11000000b = 192t
    Note numeratorExtraBit:lnum = 011000000b = 192t
    C    += 1    = 00010011b = 19t
    lnum -= lden = 00100000b = 32t = (192t-160t)
i = 4
  C    <<= 1 = 00100110b = 38t
  numeratorExtraBit = lnum >> 7 = 0t
  lnum <<= 1 = 01000000b = 64t
i = 5

Calculated Real World Value is 38*2^-5 = 1.18750000
compared to the True Real World Value  192/160 = 1.20000000
so the error is 0.0125 which is less than the precision 1/32 = 0.03125 of C
%/
