function [C,TEMPFILES] = speclatexcode(THIS)
% SPECLATEXCODE  [Not a public function] Produce LaTeX code for figure object.
%
% Backend IRIS function.
% No help provided.

% -IRIS Toolbox.
% -Copyright (c) 2007-2012 Jaromir Benes.

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

C = '';
TEMPFILES = {};

if THIS.options.visible
    visibleflag = 'on';
else
    visibleflag = 'off';
end

if isempty(THIS.children)
    if isempty(THIS.savefig) && isempty(THIS.handle)
        utils.warning('report', ...
            ['No output produced for figure ''%s'' ', ...
            'because it has no children and ', ...
            'no user-created figure has been specified.'], ...
            THIS.title);
        return
    end
    % Re-create the figure whose handle was captured at the
    % time the figure constructor was called.
    if ~isempty(THIS.savefig)
        fid = fopen(THIS.figfile,'w+');
        fwrite(fid,THIS.savefig);
        fclose(fid);
        THIS.handle = open(THIS.figfile);
        set(THIS.handle,'visible',visibleflag);
        delete(THIS.figfile);
    end
    % If there are no children and no figure handle was enterd,
    % we simply use the existing handle capture at the time of
    % the creation of THIS object.
else
    % Open new figure window.
    THIS.handle = figure('visible',visibleflag);
    % Apply user-supplied figure options one by one so that we can capture the
    % erroneous ones.
    if ~isempty(THIS.options.figureoptions)
        for i = 1 : 2 : length(THIS.options.figureoptions)
            try %#ok<TRYNC>
                name = THIS.options.figureoptions{i};
                name = strrep(name,'=','');
                value = THIS.options.figureoptions{i+1};
                set(THIS.handle,name,value);
            end
        end
    end
    % Apply styles to this figure only, do not cascade through.
    if ~isempty(THIS.options.style) ...
            && isfield(THIS.options.style,'figure')
        qstyle(THIS.options.style,THIS.handle, ...
            'cascade=',false,'warning=',false);
    end
    % Plot all children.
    myplot(THIS);
end

% Create PDF for figure handle and the latex command line.
% We need to pass in the top level report object's options
% that control orientation and paper size.
try
    rep = adam(THIS);
    [inclgraph,tempfiles] = mycompilepdf(THIS,rep.options);
    TEMPFILES = [TEMPFILES,tempfiles];
catch Error
    try %#ok<TRYNC>
        close(THIS.handle);
    end
    utils.warning('report', ...
        'Error creating figure ''%s''.\nMatlab says ''%s''', ...
        THIS.title,Error.message);
    return
end

if THIS.options.close
    try %#ok<TRYNC>
        close(THIS.handle);
    end
elseif ~isempty(THIS.title)
    % If the figure stays open add title.
    % TODO: Add also subtitle.
    grfun.ftitle(THIS.handle,THIS.title);
end

C = [beginsideways(THIS),beginwrapper(THIS,7)];
C = [C,inclgraph];
C = [C,finishwrapper(THIS),finishsideways(THIS)];

end