function Vout = imodwtj(Win, Vin, ht, gt, j)
% Usage
%   Vout = imodwtj(Wt_j, Vin, ht, gt, j)
%
% INPUTS
%   Wt_j            - MODWT wavelet coefficients for jth level.
%   Vin             - Scaling coefficients at J0, or j-1 level.
%   ht              - MODWT avelet filter coefficients.
%   gt              - MODWT Scaling filter coefficients.
%   j               - Level of decomposition.
%
% OUTPUTS
%   Vout            - MODWT scaling coefficients (residuals) for jth level.
%
%   This is matlab code to replace the c routine imodwtj.c in wmtsa
%
%   Joel Hasbrouck, January 8, 2013
%
L = length(ht);
N = length(Vin);
Vout = ht(1)*Win + gt(1)*Vin;
kShift = 2^(j-1);
for n=2:L;
    shift = -(n-1)*kShift;
    k = circshift(1:N,[0,shift]);
    Vout = Vout + ht(n)*Win(k) + gt(n)*Vin(k);
end

% replaced c code:
%   int k, n, t;
% 
%   for(t = 0; t < *N; t++) {
%     k = t;
%     Vout[t] = (ht[0] * Win[k]) + (gt[0] * Vin[k]);
%     for(n = 1; n < *L; n++) {
%       k += (int) pow(2.0, (double) *j - 1.0);
%       if(k >= *N) k -= *N;
%       Vout[t] += (ht[n] * Win[k]) + (gt[n] * Vin[k]);
%     }
%   }
% }

