final version

Adapted code from example and added comments