function [ MFpair ] = stable_marriage(male_pref, female_pref )
%UNTITLED2 Summary of this function goes here
%   Detailed explanation goes here
    [n,~]=size(male_pref);

    MFpair=zeros(n,1);
%     Fpair=zeros(n,1);

    exist_free_man = 1;
    
    freeman_idx = 1;
    while (exist_free_man == 1);
%                freeman_idx = freeman_idx + 1;
                if (freeman_idx > n)
                    freeman_idx = 1;
                end

        % lista preferenze 
%         disp('free man idx :')
%         disp(freeman_idx)
        freeman_pref = male_pref(freeman_idx,:);
        %index of highest ranked woman of the free man
        idx_tmp = find(freeman_pref > 0, 1);
        HRwoman = freeman_pref(idx_tmp);
        %remove HRwoman from freeman list
        male_pref(freeman_idx,idx_tmp) = 0;
        
        if isfree(HRwoman, MFpair)
            MFpair(freeman_idx) = HRwoman;

        else %HRWoman is not free, is alredy coupled with otherman
            otherman_idx = find(MFpair == HRwoman);
            freeman_rank = find(female_pref(HRwoman,:) == freeman_idx);
            otherman_rank = find(female_pref(HRwoman,:) == otherman_idx);
            if (freeman_rank<otherman_rank) %HRFemale prefers new mate
                MFpair(otherman_idx) = 0; %otherman becomes free
                MFpair(freeman_idx) = HRwoman;

            else
               freeman_idx = freeman_idx + 1;
               if (freeman_idx > n)
                    freeman_idx = 1;
                end
                %HRfemale prefers is actual mate, no change
            end
        end
               
%                 
%         MFpair
        %does exist a free man?
        if (min(MFpair) > 0)
            % all man married
            exist_free_man = 0; %end cicle
        else
            %choose free man
            while(MFpair(freeman_idx) > 0)
                freeman_idx = freeman_idx + 1;
                if (freeman_idx > n)
                    freeman_idx = 1;
                end
            end
        end
        
%         male_pref
%         female_pref
%         pause;
        
        
    end

end

function [ free ] = isfree( idx, list)
    free = 1;
    for cont=1:length(list)
        if (list(cont) == idx)
            free = 0;
            return;
        end
    end
end

