TESTED :D

comments explain what's happening
the file i/o is proper
Made only one change, removing unnecessary newline.