Made Python 2.7 happy with the code.
Reformated the code
Fixed a bug about file-writing.
more functional programming style