function t = toeplitz(c,r)
%MATLAB Code Generation Library Function

%   Copyright 2005-2014 The MathWorks, Inc.
%#codegen

eml_invariant(nargin >= 1, ...
    'MATLAB:minrhs');
if nargin < 2
    if isreal(c)
        t = toep(c,c);
    else
        % Complex: set up for Hermitian Toeplitz.
        c1 = c(1); r = c; c = conj(c); c(1) = c1; 
        t = toep(c,r);
    end
else
    if ~(isempty(r) || isempty(c)) && r(1) ~= c(1)
        if ~coder.setwarningflag
            coder.internal.warning('Coder:MATLAB:toeplitz_DiagonalConflict');
        end
    end
    t = toep(c,r);
end

%--------------------------------------------------------------------------

function t = toep(c,r)
m = cast(numel(c),coder.internal.indexIntClass);
n = cast(numel(r),coder.internal.indexIntClass);
t = coder.nullcopy(eml_expand(coder.internal.scalarEg(c,r),[m,n]));
% The index computations are tweaked here to avoid -1 indexing in the 
% generated C code.  For example, it appears that ij+1 is computed multiple
% times, but indexing with ij+1 in MATLAB corresponds to indexing with ij in C.
ij = zeros(coder.internal.indexIntClass);
for j = 0:coder.internal.indexMinus(n,1)
    k = j;
    for i = 0:coder.internal.indexMinus(m,1)
        if i < j
            t(coder.internal.indexPlus(ij,1)) = r(coder.internal.indexPlus(k,1));
            k = coder.internal.indexMinus(k,1);
        else
            t(coder.internal.indexPlus(ij,1)) = c(coder.internal.indexPlus(k,1));
            k = coder.internal.indexPlus(k,1);
        end
        ij = coder.internal.indexPlus(ij,1);
    end
end

%--------------------------------------------------------------------------
