almost done comparing with David's code