Debugged version by Pranjal (Please check the algo part of galeshapley)