function [SCREAL,SCIMAG] = mytune2stdcorr(THIS,RANGE,TUNE,OPT,varargin)
% mytune2stdcorr  [Not a public function] Convert the option 'vary=' or a tune database to stdcorr vector.
%
% Backend IRIS function.
% No help provided.

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

isclip = any(strcmpi(varargin,'clip'));
isimag = nargout > 1;

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

% We do not include pre-sample.

ne = sum(THIS.nametype == 3);
nstdcorr = ne+ne*(ne-1)/2;

if isempty(RANGE)
    SCREAL = nan(nstdcorr,0);
    SCIMAG = nan(nstdcorr,0);
    return
end

d = struct();
doobtaindatabase();

RANGE = RANGE(1) : RANGE(end);
nper = length(RANGE);
SCREAL = nan(nstdcorr,nper);

if ~isempty(d)
    c = fieldnames(d);
    [ans,stdcorrpos] = mynameposition(THIS,c); %#ok<NOANS,ASGLU>
    for i = find(~isnan(stdcorrpos))
        x = d.(c{i});
        if isa(x,'tseries')
            x = rangedata(x,RANGE);
            x = x(:,1);
            x = x(:).';
        end
        SCREAL(stdcorrpos(i),:) = x;
    end
end

if isimag
    SCIMAG = imag(SCREAL);
end
SCREAL = real(SCREAL);

% Vector of non-NaN variances/stdevs.
scixreal = ~isnan(SCREAL);

if isimag
    sciximag = ~isnan(SCIMAG);
end

% If requested, remove all periods behind the last user-supplied data
% point.
if isclip
    last = find(any(scixreal,1),1,'last');
    SCREAL = SCREAL(:,1:last);
    if isimag
        last = find(any(sciximag,1),1,'last');
        SCIMAG = SCIMAG(:,1:last);
    end
end

% Nested functions.

%**************************************************************************
    function doobtaindatabase()
        % Choose 'vary', 'std' or tune.
        if isfield(OPT,'vary')
            d = OPT.vary;
        end
        if isempty(d) && isfield(OPT,'std') && ~isempty(OPT.std)
            d = OPT.std;
        end
        if ~isempty(TUNE)
            if isempty(d)
                d = TUNE;
            else
                utils.error('model', ...
                    ['Cannot combine a tune database and ', ...
                    'the option ''vary=''.']);
            end
        end
    end
% doobtaindatabase().

end