function gamutMappingStep4

%gamutMappingStep4 allows you to find out which hue sector contains color
%with most shift and display the result in the command window. For this 
%test image, the hue sector is at (100,105] and you may find the hue sector
%view of previous three steps in the output/plots folder. Then, this MATLAB
%function also updates every pair of Cx and Cz values from compressed chroma 
%values, rotates and shifts back gamut-mapped source gamut. 

    load('data/keyInfo.mat')
    load('data/ch_src_gamutMapped.mat')
    load('data/l_src_gamutMapped.mat')

    %Find out which hue sector contains color with most shift
    maxDeltaE = 0;%max delta E
    indexMaxDeltaE = -1;
    %calculate deltaE between before compression and after compression
    deltaE = real(sqrt(((l_src_ref.^2)+(ch_src_ref.^2))-((l_src.^2)+(ch_src.^2))));
    for i=1:num
        if maxDeltaE < deltaE(i)
            maxDeltaE = deltaE(i);
            indexMaxDeltaE = i;
        end
    end
    
    hue = abs((atan(src_gamut(indexMaxDeltaE,3)/src_gamut(indexMaxDeltaE,2))/pi)*180);%calculate hue angle at max delta E
    if src_gamut(indexMaxDeltaE,2)==0 && src_gamut(indexMaxDeltaE,3)==0
        hue= 0;
    elseif src_gamut(indexMaxDeltaE,2)>=0 && src_gamut(indexMaxDeltaE,3)>=0%first
        hue= hue;
    elseif src_gamut(indexMaxDeltaE,2)<=0 && src_gamut(indexMaxDeltaE,3)>=0%second
        hue = 180 - hue;
    elseif src_gamut(indexMaxDeltaE,2)<=0 && src_gamut(indexMaxDeltaE,3)<=0%third
        hue= -180 + hue;
    elseif src_gamut(indexMaxDeltaE,2)>=0 && src_gamut(indexMaxDeltaE,3)<=0%fourth
        hue= -hue;
    end
    fprintf('Most color shift occured at hue angle = %f\n',hue);
    fprintf('The hue sector contains most color shift is at (%d,%d]\n',round(hue/5)*5-5, round(hue/5)*5);
    fprintf('You may find hue sector plots from output/hueSlicePlots folder\n')

    %%%%%%%%%%%%%%%%%%%%%%%%
    YyCxCz=zeros(num,3);
    %Map compressed Chroma back to ycxcz
    for i = 1:num
        scale_ch=ch_src(i)/ch_src_ref(i);
        if src_gamut(i,2)==0 && src_gamut(i,3)==0
            YyCxCz(i,1)=l_src(i);
            YyCxCz(i,2)=0;
            YyCxCz(i,3)=0;      
        else
            YyCxCz(i,1)=l_src(i);
            YyCxCz(i,2)=src_gamut(i,2) * scale_ch;
            YyCxCz(i,3)=src_gamut(i,3) * scale_ch;
        end
    end

    %%%%%%%%%%%%%%%Rotate and Shift back to Indigo press%%%%%%%%%%%%%%

    YyCxCzR = R1\YyCxCz'; %rotate
    YyCxCzR=YyCxCzR';
    imgYyCxCzUniqueUpdate=YyCxCzR+np_cmy;%shift
    imgYyCxCzUniqueUpdate(num,:)=IndigoGamut(1,:);
    save data/imgYyCxCzUniqueUpdate.mat imgYyCxCzUniqueUpdate

end


