Bugfix and cleanup.

+ Fixing bug. Now truncates the file first when writing to file. Thus
fixing bug.
+ Some cleaning up of code.