#!/usr/bin/env coffee

global._        = require 'underscore'
global.Backbone = require 'backbone'

fs               = require 'fs'
Logger           = require '../src/scripts/logger'
ModVersionParser = require '../src/scripts/models/mod_version_parser'

require '../src/scripts/underscore_mixins'

########################################################################################################################

if process.argv.length is 3
    sourceFileName = process.argv[2]
    targetFileName = process.argv[2]
else if process.argv.length is 4
    sourceFileName = process.argv[2]
    targetFileName = process.argv[3]
else
    console.error """

    USAGE: reformat <source> (<target>)

        Reformats a given recipe book into the latest version of the recipe book
        format. This includes alphabetizing entries, simplifying item lists, and
        upgrading to the latest version.

        If given a single argument, the named file will be replaced with the
        reformatted version. If two arguments are given, then the output will be
        written to the second file. If a "-" is given as the second file, the
        output will be written to stdout.

    """
    process.exit -1

global.logger = new Logger level:Logger.WARNING

text       = fs.readFileSync sourceFileName, 'UTF-8'
data       = JSON.parse text
parser     = new ModVersionParser
modVersion = parser.parse data
text       = parser.unparse modVersion

if targetFileName is '-'
    console.log text
else
    fs.writeFileSync targetFileName, text, encoding:'UTF-8'
