A proper output file is now produced. Some refactoring.