function [ result ] = ColorCorrection_dominant_color( source, target, mask, alpha, membrane, w)
% ColorCorrection_dominant_color creates a composition according three
% parameters that weight the dominant color present in the surroundings of
% the image source in the image target and their 2 orthonormal vectors.
% INPUT
%   - source - Image that will be pasted in the target image
%   - target - Background image
%   - mask - rough cut of the image source
%   - alpha - alpha mask of the image source
%   - membrane - 
%   - w - vector [3x1] with the weight for each vector space
% OUTPUT
%   - result - image composite

start = start_timer('Starting Color Correction... ');

dominant_color = computeDominantColor(target,mask,alpha);
[basis_matrix dominant_norm] = change_basis_matrix(dominant_color);
[width height channels] = size(source);

tmp = [ reshape(source(:,:,1),[],1), reshape(source(:,:,2),[],1), reshape(source(:,:,3),[],1)] * basis_matrix;
newSource(:,:,1) = reshape(tmp(:,1),width,height);
newSource(:,:,2) = reshape(tmp(:,2),width,height);
newSource(:,:,3) = reshape(tmp(:,3),width,height);

tmp = [ reshape(target(:,:,1),[],1), reshape(target(:,:,2),[],1), reshape(target(:,:,3),[],1)] * basis_matrix;
newTarget(:,:,1) = reshape(tmp(:,1),width,height);
newTarget(:,:,2) = reshape(tmp(:,2),width,height);
newTarget(:,:,3) = reshape(tmp(:,3),width,height);

tmp = [ reshape(membrane(:,:,1),[],1), reshape(membrane(:,:,2),[],1), reshape(membrane(:,:,3),[],1)] * basis_matrix;
newMembrane(:,:,1) = reshape(tmp(:,1),width,height);
newMembrane(:,:,2) = reshape(tmp(:,2),width,height);
newMembrane(:,:,3) = reshape(tmp(:,3),width,height);

for i=1:3   
    tar = newTarget(:,:,i);
    temp = (1 - w(i) * alpha) .* newMembrane(:,:,i) + newSource(:,:,i);
    tar(mask) = temp(mask);
    resultNew(:,:,i) = tar;
end

tmp = [ reshape(resultNew(:,:,1),[],1), reshape(resultNew(:,:,2),[],1), reshape(resultNew(:,:,3),[],1)] * basis_matrix';
result(:,:,1) = reshape(tmp(:,1),width,height);
result(:,:,2) = reshape(tmp(:,2),width,height);
result(:,:,3) = reshape(tmp(:,3),width,height);

end_timer(start);

end

function t = start_timer(msg)
	fprintf(1, msg); t = tic;
end

function end_timer(timer)
	t = toc(timer); fprintf(1, '%.8f sec\n', t);
end
