added additional comments and defensive checks