function [phi,theta,xc,phid] = ARMApar(mr,par,xdmi)
% KONVERZE PARAMETRU MODELU SARIMA NA PARAMETRY EKVIVALENTNIHO MODELU ARMA
% VOLANI: [phi,theta,xc,phid] = ARMApar(mr,par,xdmi)
% VSTUP:
% mr  ... =[p,d,q,P,D,Q,s] vektor radu modelu SARIMA, kde
%         p ... rad nesezonni AR casti modelu (p>=0, cele cislo)
%         d ... rad nesezonniho diferencovani (d>=0, cele cislo)
%         q ... rad nesezonni MA casti modelu (q>=0, cele cislo)
%         P ... rad sezonni AR casti modelu (P>=0, cele cislo)
%         D ... rad sezonniho diferencovani (D>=0, cele cislo)
%         Q ... rad sezonni MA casti modelu (Q>=0, cele cislo)
%         s ... perioda (pocet bodu) sezonni komponenty (s>=0, cele cislo)
%         s~=1; s==0 => P+D+Q=0; s>1 => P+D+Q>0.
% par ... bunecne pole (1 x 4) vsech ctyr typu parametru modelu
%         SARIMA (vektory po rade 1 x p, 1 x q, 1 x P, 1 x Q).
% xdmi... odhad stredni hodnoty diferencovane rady
%         (nepovinny nebo []: implicitne 0)
%
% VYSTUP:
% phi   ... vektor AR parametru ekvivalentniho ARMA modelu (1 x p+d+s*(P+D))
% theta ... vektor MA parametru ekvivalentniho ARMA modelu (1 x q+s*Q)
% xc    ... = xdmi*(1-sum(phid)) je korekcni konstantni clen v ekvivalentnim
%           ARMA modelu:
%           phi(z)X_t = xc +  theta(z)Z_t.
%           Zejmena je nutno jej pricist k predikci provedene pomoci
%           'armasim': xp = armasim(x,phi,theta,x0); xp = xp + xc;
% phid  ... vektor AR parametru ekvivalentniho ARMA modelu diferencovane rady
%           (1 x p+s*P)
%           Poznamka: thetad=theta
%
% (C) 1999, V. Vesely, Masaryk University of Brno (Czech Republic)
%
error(nargchk(2,3,nargin));
if nargin < 3, xdmi=[]; end
if isempty(xdmi), xdmi=0; end
%
mr = round(mr);
p = mr(1); d = mr(2); q  = mr(3);
P = mr(4); D = mr(5); Q = mr(6); s = mr(7);
if any(mr<0) | s==1 | (s==0 & P+D+Q>0) | (s>1 & P+D+Q==0)
   error('Invalid model range');
end
phi = par{1}; theta = par{2}; PHI = par{3}; THETA = par{4};
if length(phi)~=p | length(theta)~=q | length(PHI)~=P | length(THETA)~=Q
   error('Parameters disagree with model range');
end
phi_z = 1; d_z = 1; theta_z = 1; PHI_zs = 1; D_zs = 1; THETA_zs = 1;
delta = [zeros(1,s-1),1];
if p>0, phi_z   = [1,-phi] ; end
if d>0, d_z=fliplr(poly(ones(1,d))); d_z = d_z./d_z(1); end
if q>0, theta_z = [1,theta]; end
if P>0, PHI_zs  = [1,kron(-PHI,delta)]; end
if D>0, D_zs=fliplr(poly(ones(1,D)));
   D_zs = D_zs./D_zs(1);
   D_zs = [1,kron(D_zs(2:length(D_zs)),delta)];
end
if Q>0, THETA_zs=[1,kron(THETA,delta)]; end
%
dD_zs = conv(d_z,D_zs);
phi_z = conv(phi_z,PHI_zs);
phid  = -phi_z(2:length(phi_z));
xc    = xdmi*(1-sum(phid));
phi_z = conv(phi_z,dD_zs);
phi   = -phi_z(2:length(phi_z));
theta_z = conv(theta_z,THETA_zs);
theta   = theta_z(2:length(theta_z));
