function DEQTN = mydiffeqtn(EQTN,MODE,NMOCC,TMOCC,LOG,varargin)
% MYDIFFEQTN  [Not a public function] Differentiate one equation wrt to a list of names.
%
% Backend IRIS function.
% No help provided.

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

if isempty(TMOCC)
    TMOCC = zeros(size(NMOCC));
end

if isempty(LOG)
    LOG = false(1,max(NMOCC));
end

isbsx = any(strcmp(varargin,'bsx'));

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

% Remove anonymous function preamble.
EQTN = regexprep(char(EQTN),'^@\(.*?\)','','once');

% Replace x(:,n,t+k) with xN, xNpK, or xNmK.
EQTN = sydney.myeqtn2symb(EQTN);

% Create sydney object for the current equation.
z = sydney(EQTN);

nocc = length(NMOCC);
unknown = cell(1,nocc);
for i = 1 : nocc
    if TMOCC(i) == 0
        % Time index == 0: replace x(1,23,t) with x23.
        unknown{i} = sprintf('x%g',NMOCC(i));
    elseif TMOCC(i) > 0
        % Time index > 0: replace x(1,23,t+1) with x23p1.
        unknown{i} = sprintf('x%gp%g',NMOCC(i),round(TMOCC(i)));
    else
        % Time index < 0: replace x(1,23,t-1) with x23m1.
        unknown{i} = sprintf('x%gm%g',NMOCC(i),round(abs(TMOCC(i))));
    end
end

if MODE == 1
    % Differentiate and reduce the result. The function returned by sydney.diff
    % computes derivatives wrt all variables at once, and returns a vector of
    % numbers.
    z = diff(z,unknown,1);
    %### deqtn = char(z,'human');
    DEQTN = char(z,varargin{:});
    % Multiply derivatives wrt log(X) by X.
    if any(LOG(NMOCC))
        c = unknown;
        if ~isbsx
            c(~LOG(NMOCC)) = {'1'};
        else
            c(~LOG(NMOCC)) = {'ones(1,1,length(t))'};
        end
        c = sprintf('%s;',c{:});
        c(end) = '';
        if ~isbsx
            DEQTN = ['(',DEQTN,').*[',c,']'];
        else
            DEQTN = ['bsxfun(@times,',DEQTN,',[',c,'])'];
        end
    end
else
    % Derivatives wrt individual names are computed and stored separately.
    DEQTN = cell(1,nocc);
    if nocc > 0
        z = diff(z,unknown,Inf);
        for i = 1 : nocc
            DEQTN{i} = char(z{i},varargin{:});
        end
    end
end

% Replace xN, xNpK, or xNmK back with x(:,N,t+/-K).
% Replace Ln back with L(n).
DEQTN = sydney.mysymb2eqtn(DEQTN);

end