Now writes an output file

Cleaned up code and added file output.