Question: Stable Marriage Problem

Hi there, I'm trying to write an Algoritm to solve a Stable Marriage Problem and have written what I think should work but it doesn't.  Any hints or tips on how to fix it would be greatly appreciated!

 

stableMatching:= proc(M,W)
 local n,i,j,k,c,d,g,Mm,Ww,s:
    g:=0:
    c:=0:
 with(ArrayTools):
    n:=max(Size(M)):
       Mm := Array(1..n): #stores the number of the woman the man is married to
       Ww := Array(1..n):
         for i from 1 to n do #sets marriages to 0
         Mm[i] := 0:
         Ww[i] := 0:
        end do:
     for d from 1 while g<>n do #loops until all men are married
     for j from 1 to n do
     for i from 1 to n do
      if Ww(M[i,n-j+1])=0 then #if the man's prefered woman isn't married
        Mm[i]:= M[i,n-j+1]: #man marries woman
         Ww[Mm[i]]:=i: #woman marries man
           g:=g+1:
         else
       for k from 1 to n do # see if the woman prefers the new man to old. if she does, swap.
        if W[M[i,n-j+1],k]=Ww(M[i,n-j+1]) then if c<>2 then
         c:=1:
          s:=k:
       end if:
       end if:
      if W[M[i,n-j+1],k]=i then if c=1 then
       c:=2:
     end if:  
    end if:
   end do:
    if c = 2 then #if she prefers the second man swaps them.
     Mm[Ww[s]]:=0:
     Mm[i]:=M[i,n-j+1]:
     Ww[Mm[i]]:=i:
    end if:
   end if:
  end do:
 end do:
end do:
return Mm
end proc:

Please Wait...