function y = apply_prec2(x,P1,P2,adj)
% Apply preconditioner P or P'
% INPUT:    x - vector
%           P1,P2 - preconditioner in factored form P=P1*P2 (unfactored form also
%                   possible by setting P2=[]; can be matrices or function handles
%           adj - 1 for adjoint solve, 0 otherwise
% OUTPUT:   y=P\x or y=P'\x
%
% (C) Patrick Kuerschner 2011-24


if nargin < 4 || isempty(adj)
    adj=0;
end
if (~isempty(P2) && ~isempty(P1)) % e.g., standard (i)lu (or (i)cholesky)
    if isnumeric(P1) && isnumeric(P2)
        if ~adj
            x2 = P1\x;
            y = P2\x2;
        else
            x2 = P2'\x;
            y = P1'\x2;
        end
    else
        if ~adj
            x2 = P1(x,0);
            y = P2(x2,0);
        else
            x2 = P2(x,1);
            y = P1(x2,1);
        end
    end
else
    if ~isempty(P1)
        if isnumeric(P1)
            if ~adj
                y=P1\x;
            else
                y=P1'\x;
            end
        else
            y=P1(x,adj);
        end
    else
        y=x;
    end
end
