Commented the program, please say if you don't understand some code.