function [c,flag] = file2char(fname,type,lines)

if nargin < 3
    lines = Inf;
    selectLines = false;
else
    lines(round(lines) ~= lines | lines < 1) = [];
    if isempty(lines)
        c = '';
        return
    else
        selectLines = ~isequal(lines,Inf);
    end
end

if nargin < 2 || isempty(type)
    type = 'char';
end

%**************************************************************************

if iscellstr(fname) && length(fname) == 1
    text = fname{1};
    flag = true;
    return
end

flag = true;
fid = fopen(fname,'r');
if fid == -1
    if ~exist(fname,'file')
        error('FILE2CHAR cannot find file ''%s''.',fname);
    else
        error('FILE2CHAR cannot open file ''%s'' for reading.',fname);
    end
end

if strcmpi(type,'cellstrl')
    % Remove new line characters.
    c = {};
    while ~feof(fid)
        c{end+1} = fgets(fid); %#ok<AGROW>
    end
    do_lastempty();
    if selectLines
        n = length(c);
        lines(lines < 1 | lines > n) = [];
        c = c(lines);
    end
elseif strcmpi(type,'cellstrs') || selectLines
    % Keep new line characters.
    c = {};
    while ~feof(fid)
        c{end+1} = fgets(fid); %#ok<AGROW>
    end
    do_lastempty();
    if selectLines
        n = length(c);
        lines(lines < 1 | lines > n) = [];
        c = c(lines);
    end
    if ~strcmpi(type,'cellstrs')
        c = [c{:}];
    end
else
    c = char(transpose(fread(fid,type)));
end

if fclose(fid) == -1
    warning('iris:utils', ...
        'FILE2CHAR cannot close file ''%s'' after reading.',fname);
end

    function do_lastempty()
        try %#ok<TRYNC>
            % If the last character is newline or return, there is an empty
            % line at the end of the file which is not read by `fgets`. We need
            % to add this empty line to `c`.
            fseek(fid,-1,'eof');
            test = fread(fid,1);
            if test == 10 || test == 13
                c{end+1} = '';
            end
        end
    end

end
