Removed global variables from script.

Also, added error handling and changed output file format.