have written my doubts in comments to corresponding code.