function [fileID,out2,out3,out4] = fopen(filename,varargin) %#ok<STOUT>
%MATLAB Code Generation Library Function

%   Limitations:
%   1. Does not support MACHINEFORMAT or ENCODING inputs.
%   2. Does not support fileID input.
%   3. If extrinsic calls are disabled, fileIDs created with FOPEN can only
%      be used internally. They cannot be returned to MATLAB or used by an
%      extrinsic function.
%   4. The MESSAGE output is not supported.
%   5. fopen('all') is not supported.
%   6. Permission string may be at most 3 characters and all characters must be
%   unique

%   Copyright 2012-2016 The MathWorks, Inc.
%#codegen

coder.inline('always');
eml_invariant(nargin > 0, ...
    'MATLAB:minrhs');
coder.internal.prefer_const(filename);
eml_invariant(nargin <= 3, ...
    'MATLAB:maxrhs');
eml_invariant(nargin < 3, ...
    'Coder:toolbox:fopenMfNotSupported');
eml_invariant(coder.internal.isCharOrScalarString(filename), ...
    'Coder:toolbox:fopenFidInputNotSupported');
eml_invariant(nargout <= 1, ...
    'Coder:toolbox:fopenMsgOutputNotSupported');
% Report the error at compile-time if possible
eml_invariant(~(eml_is_const(filename) && USINGALL(nargin,filename)), ...
              'Coder:toolbox:fopenAllNotSupported', ...
              'IfNotConst', 'Fail');
if (USINGALL(nargin,filename))
    % Include a runtime check
    if coder.internal.hasRuntimeErrors()
        coder.internal.error('Coder:toolbox:fopenAllNotSupported');
    else
        fileID = zeros();
    end
else
    if nargin == 1
        permission = 'r';
    else
        coder.internal.prefer_const(varargin);
        permission = varargin{1};
    end

    % Register cleanup function
    coder.internal.atexit(@fileioAtExit);
    fileID = double(fileManager('open',coder.internal.toCharIfString(filename),coder.internal.toCharIfString(permission)));
end

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

function p = USINGALL(n, filename)
coder.inline('always');
coder.internal.prefer_const(n,filename);
p = (n == 1 && strcmp(filename, 'all'));

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

function fileioAtExit
% Cleanup open files in PARFOR when using RTW file manager.
if coder.internal.isInParallelRegion()
    fclose('all');
end
