function position = ftell(fileID)
%MATLAB Code Generation Library Function

%   Copyright 2016-2022 The MathWorks, Inc.

%#codegen
narginchk(1,1);
if isFileIOExtrinsic
    position = 0;
    position = feval('ftell', fileID);
else
    filestar = getFileStar(fileID);
    if filestar == NULL
        position = STATUS_FAIL;
    else
        % TODO: long
        position_t = coder.opaque('long','0');
        cLibName = coder.internal.getCLibName('ftell');
        position_t = coder.ceval(cLibName,filestar);
        position = cast(position_t, 'double');
    end
end

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

function filestar = getFileStar(fileID)
% FTELL not supported on stdin.  Return NULL on error and report the error if
% possible

% Get the FILE * and assert validity
filestar = coder.internal.fileManager('filestar', fileID);
if (coder.internal.hasRuntimeErrors() && filestar == NULL)
    coder.internal.error('MATLAB:FileIO:InvalidFid');
end

% FTELL not supported for stdin, stdout or stderr
if (~isImplementedFilestar(fileID))
    filestar = NULL;
end

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

function p = isImplementedFilestar(fileID)
coder.inline('always');
p = fileID ~= 0 && fileID ~= 1 && fileID ~= 2;

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

function y = NULL
coder.inline('always');
cHeader = coder.internal.getCHeaderName('stdio');
cLibName = coder.internal.getCLibName('FILE');
y = coder.opaquePtr(cLibName,coder.internal.null,'HeaderFile',cHeader);

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

function y = STATUS_FAIL
coder.inline('always');
y = -1;

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