% function [z, e2, x, e2s, CBC_optimal] = fastrank1exod(p, m1, m2, ...
%   s_max, omega, Gamma, CBC_optimal, verbose)
function [z, e2, x, e2s, CBC_optimal] = fastrank1exod(p, ...
  m1, m2, s_max, omega, Gamma, CBC_optimal, verbose)

% \emph{\ldots similar part to fastrank1expt.m lines 6 to 36 skipped \ldots}
if (nargin < 8) || isempty(verbose), verbose = 1; end;
if ~isprime(p), error('p must be prime'); end;
if (m1 < 1) || (m1 > m2), error('must have 1 <= m1 <= m2'); end;

if (nargin < 7) || isempty(CBC_optimal) % if precalculations needed
  CBC_optimal = {}; CBC_optimal{m2} = ones(s_max, 1);
  if m1 ~= m2
    for m=m1:m2
      CBC_optimal{m} = CBC_optimal{m2}; % alias using Matlab's lazy copy
      [opt_z, CBC_optimal{m}] = fastrank1exod(p, m, m, s_max, ...
          omega, Gamma, CBC_optimal, verbose-1);
    end;
  end;
end;

n = p^m2; % total number of points $n = p^{m_2}$
if p == 2, g = 5; else g = generator(p*p); end; % pseudo when $p=2$
phip0 = 1; phip = zeros(m2, 1);
phip(1) = p - 1; for m=2:m2, phip(m) = p*phip(m-1); end;
phip(phip >= 2) = phip(phip >= 2) / 2; % \texttt{phip(m)} is the size for $p^m$
perm = zeros(phip(m2), 1); perm(1) = 1;
for i=2:phip(m2), perm(i) = mod(perm(i-1)*g, n); end;
if m2~=1, sidx = [1; cumsum(phip(1:m2-1))+1]; else sidx = [1]; end;
eidx = sidx + phip - 1;

psi0 = omega(0); psi = zeros(sum(phip), 1);
fft_psi = zeros(sum(phip), 1);
for m=1:m2
  psi(sidx(m):eidx(m)) = omega(mod(perm(1:phip(m)), p^m) / p^m);
  fft_psi(sidx(m):eidx(m)) = fft(psi(sidx(m):eidx(m)));
end;

qstar = length(Gamma);
% $\vec{q}_{s,\ell}$ can be found in \texttt{q(:, ell+1)}
q0 = zeros(1, qstar+1); q = zeros(sum(phip), qstar+1);
q0(0+1) = 1; q(:,0+1) = 1;
z = zeros(s_max, 1); e2 = zeros(s_max, 1); x = zeros(s_max, 1);
prev_e2 = zeros(m2-m1+1, 1);

if (verbose >= 1) && (m1 ~= m2)
  fprintf('Calculating rule for %d^%d to %d^%d\n', p, m1, p, m2);
elseif (verbose >= 1)
  fprintf('Calculating optimal CBC for %d^%d\n', p, m1);
end;
for s=1:s_max
  E2 = zeros(phip(m2), 1); X = zeros(phip(m2), m2-m1+1);
  % calculate $S = \sum_\ell \Gamma_\ell \; \vec{q}_{s-1,\ell-1}$
  S0 = sum(q0([0:qstar-1]+1) .* Gamma);
  S  = sum(q(:,[0:qstar-1]+1) * diag(Gamma), 2);
  E2(1) = psi0 * S0;
  if p == 2, r = 1; else r = 2; end; % $p=2$ is special
  v = 1; % number of choices from the previous iteration for $m$ (next loop)
  for m=1:m2   % calculate error for each $m$
    E2(1:phip(m)) = repmat(E2(1:v), phip(m)/v, 1) ...
      + r * real(ifft(fft_psi(sidx(m):eidx(m)) ...
        .* fft(S(sidx(m):eidx(m)))));
    if m >= m1 % store and calculate $X$ where needed
      X(:, m-m1+1) = repmat(sqrt((prev_e2(m-m1+1) ...
        + E2(1:phip(m))/p^m) / CBC_optimal{m}(s)), ...
          phip(m2)/phip(m), 1);
    end;
    r = 2; v = phip(m);
  end;
  [x(s), w(s)] = min(max(X, [], 2)); % pick the good choice
  [dummy, mloc] = max(X(w(s),:)); mloc = mloc + m1 - 1;
  if s == 1, w(s) = 1; end;
  z(s) = perm(w(s)); z(s) = min(z(s), n-z(s)); % unpermute
  e2(s) = prev_e2(end) + E2(w(s))/n;  % calculate real worst-case error
  % update $\vec{q}$...
  for ell=min(qstar, s+1):-1:1 % for each $\ell$...
    q0(ell+1) = q0(ell+1) + psi0 * q0(ell-1+1);
    for m=1:m2                 % and for each $m$
      ww = mod(w(s)-1, phip(m)) + 1; J = [sidx(m):eidx(m)];
      q(J,ell+1) = q(J,ell+1) ...
        + psi([ww:-1:1 phip(m):-1:ww+1]+sidx(m)-1) ...
          .* q(J,ell-1+1);
    end;
  end;
  % calculate \texttt{prev\_e2} for next iteration
  S0 = sum(q0([1:qstar]+1) .* Gamma);
  S = sum(q(:,[1:qstar]+1) * diag(Gamma), 2);
  prev_e2(1) = S0;
  if p == 2, r = 1; else r = 2; end;
  for m=1:m2
    prev_e2(max(1,m-m1+1)) = prev_e2(max(1,m-m1)) ...
      + r * sum(S(sidx(m):eidx(m)));
    r = 2;
  end;
  prev_e2 = prev_e2 ./ p.^[m1:m2]';
  if verbose >= 2
    fprintf('s=%4d, z=%6d, e2=%.4e, x=%.4e, mloc=%4d\n', ...
             s, z(s), e2(s), x(s), mloc);
  end;
end;
e2s = prev_e2;
