% Usage: y = invwave1(x,filt).
% Inverts single-stage DWT command wave1().
function y = invwave1(x,filt)

[m,n]=size(x); 

rowv=0;
if m==1 %Got fed a row vector---convert to column, undo later
    x = transpose(x);
    rowv=1;
end

[m,n]=size(x); 
m2=m; n2=n;

cL = x(1:(m2/2),:); 
ch = x((m2/2+1):m2,:); %Pick off low and high parts

w1 = zeros(m,n);
w2 = zeros(m,n);
for k=1:n2
    w1(:,k)=kupsample(cL(:,k));
    w2(:,k)=kupsample(ch(:,k));
end

l = zeros(m2,1); h = zeros(m2,1);

if strcmp(filt,'orthhaar')
    l(1)=sqrt(0.5); l(m2)=l(1);
    h(1)=l(1); h(m2)=-l(1);
elseif strcmp(filt,'haar')
    l(1)=1.0; l(m2)=l(1);
    h(1)=l(1); h(m2)=-l(1);
elseif strcmp(filt,'d4')
    l(1)=-0.12940952255092; l(m2)=0.22414386804186; l(m2-1)=0.83651630373747; l(m2-2)=0.48296291314469;
    h(1)=-0.48296291314469; h(m2)=0.83651630373747; h(m2-1)=-0.22414386804186;
    h(m2-2)=-0.12940952255092;
elseif strcmp(filt,'legall')
    h(1) = -0.25; h(2)=-0.125; h(m2-2)=-0.125; h(m2-1)=-0.25; h(m2)=0.75;
    l(1)=1.0; l(2)=0.5; l(m2)=0.5;
else %default to haar
    l(1)=sqrt(0.5); l(m2)=l(1);
    h(1)=l(1); h(m2)=-l(1);
end

%Do circular convolution with filters via FFT.  
%Slightly inefficient.
W1 = fft(w1); W2=fft(w2); L = fft(l); H = fft(h);
xL = zeros(m2,n2); xH = zeros(m2,n2);

for k=1:n2
    xL(:,k) = W1(:,k).*L; xH(:,k) = W2(:,k).*H;
end
y = real(ifft(xL+xH));

if rowv==1
    y = transpose(y);
end
