Some re-factorings, and WIP fixing bug of writing to output file