%#codegen

function fc = f2f_constant(const, T, fm)
    coder.inline('always');
    if isfield(T, 'DefaultWordLength') && (isfield(T, 'Fimath') || nargin == 3)
        issigned = get_sign(const);
        nt = numerictype(T.DefaultWordLength);
        if nargin == 3
            fc = get_best_prec_for_const(const, numerictype(issigned,  nt.WordLength, 0), fm);
        else
            fc = get_best_prec_for_const(const, numerictype(issigned,  nt.WordLength, 0), fimath(T.Fimath));
        end
    else
        fc = const;
    end
end

function new_const = get_best_prec_for_const(const, nt_var, fm_var)
coder.inline('always');
    
coder.extrinsic('emlGetMinWlenAndPrecisionForMxArray');
coder.extrinsic('emlGetBestPrecForMxArray');

varBias = nt_var.Bias;
const1 = const - varBias;

if coder.target('MATLAB')
    % get min precision numerictype for const with min wlen
    nt_min = emlGetMinWlenAndPrecisionForMxArray(const, varBias);
    min_prec_const = fi(const1, nt_min, fm_var);


    % get best precision numerictype for const with wlen same as var
    nt_best = emlGetBestPrecForMxArray(const,nt_var);
    best_prec_const = fi(const, nt_best, fm_var);

    q1 = cast(min_prec_const, 'like', const) - const;
    q2 = cast(best_prec_const, 'like', const) - const;    
else
    % get min precision numerictype for const with min wlen
    nt_min = eml_const(emlGetMinWlenAndPrecisionForMxArray(const, varBias));
    min_prec_const = eml_cast(const1, nt_min, fm_var);


    % get best precision numerictype for const with wlen same as var
    nt_best = eml_const(emlGetBestPrecForMxArray(const,nt_var));
    best_prec_const = eml_cast(const, nt_best, fm_var);

    q1 = eml_cast(min_prec_const, eml_typeof(const), fm_var) - const;
    q2 = eml_cast(best_prec_const, eml_typeof(const), fm_var) - const;    
end



q = q1 == q2;

if all(q(:))
    new_const = min_prec_const;
else
    new_const = best_prec_const;
end

end

function issigned = get_sign(const)
issigned = double(any(const(:) < 0));
end
