added sample code
added comments and simplified the logic