simplified algorithm and added inline documentation