some refactoring/re-organizing and writing the final file