added some checks and comments