
NUM_OF_ITERATIONS=3;
percentage_of_k_space=0;
percentage_of_k_space_delta=0.02;
epsilon1=0.1;

%% Load data
load data

size_im=size(im,1);

%% generate fully sampled k-spaced of follow-up (Y_full) and reference (Y_0) images
dft_mat=dftmtx(size_im)/sqrt(size_im);
Y_0=dft_mat*im0*dft_mat';
Y_full=dft_mat*im*dft_mat';
W=Wavelet;
X0=W*im0;

inverse_wav_baseline_representation=(1./(1+abs(X0)));

%% Initialize algoritm parameters
f_VD=pdf_vardens;
f_R=abs(Y_0)./sum(sum(abs(Y_0)));
gamma=0;
W1=ones(size(X0));
W2=zeros(size(X0));

%% Sample for first iteration


for j=1:NUM_OF_ITERATIONS
   

    % Increase the number of samples
    percentage_of_k_space=percentage_of_k_space+percentage_of_k_space_delta;
    
    % Sample k-space
    sampl_mtx=generate_samples(f_R,f_VD,gamma,percentage_of_k_space);
    Y=Y_full.*sampl_mtx;
    
    % Solve l1 mimimization problem
      h = waitbar(0,'Please wait...','Name',['Minimization solver, ',num2str(percentage_of_k_space*100),'% of data']);
    X=FISTA_based_solver(Y,dft_mat,W,X0,W1,W2,h);
    close(h);
    %Compute weighting coeficients for next iteration
    reconstructed_image=abs((W'*X));
    diff_in_wav=abs(W*(reconstructed_image-im0));
    map_diff=diff_in_wav./(diff_in_wav+1);
    W1(map_diff>epsilon1)=1;
    W1(map_diff<=epsilon1)=inverse_wav_baseline_representation(map_diff<=epsilon1);  
    W2=1./(1+abs(reconstructed_image-im0));
    gamma=mean(W2(:));  
end
% Transfer image to image domain
im_adaptive=abs(W'*X);

%% For comparison: reconstruct using wavelet based CS from same number of samples
disp('Image reconstruction with wavelet based CS for comparison...');
sampl_mtx_for_comparison=generate_samples(f_R,f_VD,0,percentage_of_k_space);
Y_temp=Y_full.*sampl_mtx_for_comparison;
X_wavelet_CS=POCS_func(Y_temp,dft_mat,W);
im_non_adaptive=abs(W'*X_wavelet_CS);


%% Show results
figure; imagesc(flipud(im_adaptive'),[0 0.75]); colormap(gray); title('Reference-based MRI results from 6% of k-space data');
figure; imagesc(flipud(im_non_adaptive'),[0 0.75]); colormap(gray); title('Wavelet-based CS-MRI results from 6% of k-space data');
figure; imagesc(flipud(im'),[0 0.75]); colormap(gray); title('Ground truth');
disp('Done!');
