clear all
close all

nr_sources = 2;
nr_mixtures = 2;
wname = 'db8';
downsample_by = 4;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%       jednostavno mixanje
%%%%%%%%%%%%%%%%%%%%

% loading + downsampling
[ss1, fs1, nbits1] = wavread('bird.wav');
ss1 = ss1(1:downsample_by:length(ss1), 1);
len1 = length(ss1);
fs1 = fs1/downsample_by;
[ss2, fs2, nbits2] = wavread('bizarro.wav');
ss2 = ss2(1:downsample_by:length(ss2), 1);
len2 = length(ss2);
fs2 = ss2/downsample_by;
%[ss3, fs3, nbits3] = wavread('marble.wav');
%ss3 = ss3(1:downsample_by:length(ss3), 1);
%len3 = length(ss3);
%fs3 = ss3/downsample_by;

%srezati ih malo
%ss1 = ss1(501:1500,1); len1 = 1000;
%ss2 = ss2(501:1500,1); len2 = 1000;
%ss3 = ss3(501:1500,1); len3 = 1000;

figure, plot(ss1)
figure, plot(ss2)
%figure, plot(ss3)

mixlen = max([len1 len2]);
fs = fs1; %fs=fs1=fs2

%wp_level = wmaxlev(mixlen/4, wname);   %razina dekompozicije
wp_level = 6;


% simple linear mixing, 2 mixes
SS = zeros(2, mixlen);
SS(1, 1:len1) = ss1';
SS(2, 1:len2) = ss2';
%SS(3, 1:len3) = ss3';
AA = abs(randn(2, 2));

%XX = zeros(2, mixlen);
XX = AA*SS;

figure, plot(XX(1,:), XX(2,:), '.');

% mixtures : t -> wp
for i = 1 : nr_mixtures,
    X{i} = wpdec(XX(i,:), wp_level, wname, 'shannon');
end



%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%       WP koeficijenti, terminalni cvorovi u posljednjoj razini
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

coeffs = [];
for i = 1 : nr_mixtures,
    cfs_tmp = read(X{i}, 'allcfs');
    coeffs = [coeffs cfs_tmp'];
end
figure, plot(coeffs(:,1), coeffs(:,2), '.')

[centroids, avg_distorsion_tmp] = get_centroids(coeffs, nr_sources);
figure, plot(coeffs(:,1), coeffs(:,2), '.')
hold, plot(centroids(:,1), centroids(:,2), 'r*')


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%  dobivanje matrice mijesanja iz smjerova koeficijenata
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

AA
centroids
AArec = centroids'
invAArec = inv(AArec);
SSrec = invAArec*XX;
plot(SSrec(1,:))
plot(SSrec(2,:))