function x = flip(x,dim)
%MATLAB Code Generation Library Function
%
% Limitations:
% 
%   1. Cell input for first argument is not supported

%   Copyright 1984-2019 The MathWorks, Inc.
%#codegen

coder.internal.allowEnumInputs;
coder.internal.allowHalfInputs;
eml_invariant(nargin > 0,'MATLAB:minrhs');
eml_invariant(~iscell(x), ...
    'Coder:toolbox:CellArraysNotSupported', mfilename);
if nargin == 1
    dim = coder.internal.nonSingletonDim(x);
else
    coder.internal.prefer_const(dim);
    coder.internal.assertValidDim(dim);
end
if dim <= ndims(x) && ~isempty(x) && size(x,dim) > 1
    ZERO = coder.internal.indexInt(0);
    ONE = coder.internal.indexInt(1);
    if coder.internal.avoidArrayFlattening
        x = fliplooper(x,dim);
    else
        vlen = coder.internal.indexInt(size(x,dim));
        vstride = coder.internal.prodsize(x,'below',dim);
        pagelen = vstride*vlen;
        npages = coder.internal.prodsize(x,'above',dim);
        n = coder.internal.indexInt(size(x,dim));
        nd2 = eml_rshift(n,ONE);
        for j = ZERO:npages-ONE
            for i = ZERO:vstride-ONE
                offset = j*pagelen + i;
                for k = ONE:nd2
                    tmp = x(offset+(k-1)*vstride+ONE);
                    x(offset+(k-1)*vstride+ONE) = x(offset+(n-k)*vstride+ONE);
                    x(offset+(n-k)*vstride+ONE) = tmp;
                end
            end
        end
    end
end

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

function x = fliplooper(x,dim,thisDim,varargin)
coder.inline('always');
coder.internal.allowEnumInputs;
coder.internal.prefer_const(dim);
ONE = coder.internal.indexInt(1);
ND = coder.internal.indexInt(eml_ndims(x));
if nargin > 2
    coder.internal.prefer_const(thisDim);
elseif coder.isRowMajor
    thisDim = ONE;
else
    thisDim = coder.internal.indexInt(eml_ndims(x));
end
n = coder.internal.indexInt(size(x,dim));
if thisDim >= ONE && thisDim <= ND
    if dim == thisDim
        lup = eml_rshift(n,ONE);
    else
        lup = coder.internal.indexInt(size(x,thisDim));
    end
    if coder.isRowMajor
        for k = ONE:lup
            x = fliplooper(x,dim,thisDim + 1,varargin{:},k);
        end
    else
        for k = ONE:lup
            x = fliplooper(x,dim,thisDim - 1,k,varargin{:});
        end
    end
else
    subs2 = varargin;
    subs2{dim} = n - subs2{dim} + 1;
    tmp = x(varargin{:});
    x(varargin{:}) = x(subs2{:});
    x(subs2{:}) = tmp;
end

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