% Usage: Y = kidct(y).  Substitute for Matlab's idct() command. Not as 
% efficient, but it works. If input y is row vector, transforms the row, 
% otherwise transforms column by column.
function y = kidct(Y)

[M,N] = size(Y);

if M==1 %Inverse transform a row vector
    Yt = Y(1:N).*exp(0.5*i*pi*(0:N-1)/N)*sqrt(2*N); Yt(1) = Yt(1)*sqrt(2);
    Y2 = [Yt, 0, conj(Yt(N:-1:2))];
    y2 = ifft(double(Y2));
    y = real(y2(1:N));
else %Do matrix column by column
    for k = 1:M
        r = sqrt(2*M)*exp(0.5*i*pi*(k-1)/M);
        Yt(k,:) = r*Y(k,:);
    end
    Yt(1,:) = sqrt(2)*Yt(1,:);
    Y2= [Yt; zeros(1,N); conj(Yt(M:-1:2,:))];  %Duplicate/reflect each column
    y2 = ifft(double(Y2));
    y = real(y2(1:M,:));
end
