some more fine-tuning
further isolate code into functions
fixed a non-Pythonic loop, fix txt creation