% Usage: y = wave1(x,filt).
% Do a one pass forward wavelet transform on input array x. If x is
% row or column vector, transform. If x is array, transform 
% columnwise. Filter choices are "haar", "orthhaar", "d4", and
% "legall". This commmand assumes periodic extension of signals.
function y = wave1(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;

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

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

%Do circular convolution with filters via FFT
X = fft(x); L = fft(l); H = fft(h);

xl=zeros(m2/2,n2); xh=zeros(m2/2,n2);

for k=1:n2
    xl(:,k) = kdownsample(real(ifft(X(:,k).*L)));
    xh(:,k) = kdownsample(real(ifft(X(:,k).*H)));
end

if rowv == 1
    y = [xl; xh]';
else
    y = [xl; xh];
end