Debugged version by Pranjal(Some pain with scanner)