little debugged version by Pranjal