// Generated by CoffeeScript 1.9.0
(function() {
  var CSON, conversion, convertSTDIN, data, filePath, fs, i, opts, outputHelp, path, stdin, timeout, timeoutFunction, useSTDIN;

  fs = require('fs');

  path = require('path');

  CSON = require(path.join(__dirname, '..', 'lib', 'cson'));

  opts = {};

  outputHelp = function() {
    return process.stdout.write('CSON CLI\n\nUsage:\n\n	# Convert a JSON file into a CSON file\n	json2cson in.json > out.cson\n\n	# Same thing via piping\n	cat in.json | json2cson > out.cson\n\n	# Convert a CSON file into a JSON file\n	cson2json in.cson > out.json\n\n	# Same thing via piping\n	cat in.cson | cson2json > out.json\n\nOptions\n\n	# Display this help\n	--help\n\n	# Indentation for CSON output\n	--tabs\n	--2spaces\n	--4spaces\n');
  };

  if (process.argv.indexOf('--help') !== -1) {
    outputHelp();
    process.exit(0);
  }

  if (process.argv.toString().indexOf('cson2json') !== -1) {
    conversion = 'cson2json';
  } else if (process.argv.toString().indexOf('json2cson') !== -1) {
    conversion = 'json2cson';
    opts.indent = (i = process.argv.indexOf('--tabs')) !== -1 ? '\t' : (i = process.argv.indexOf('--2spaces')) !== -1 ? '  ' : (i = process.argv.indexOf('--4spaces')) !== -1 ? '    ' : void 0;
    if (i !== -1) {
      process.argv = process.argv.slice(0, i).concat(process.argv.slice(i + 1));
    }
  } else {
    process.stderr.write('Unknown conversion');
    process.exit(1);
  }

  if (process.argv.length === 3) {
    filePath = process.argv[2];
    process.stdout.write(conversion === 'cson2json' ? CSON.createJSONString(CSON.parseCSONFile(filePath), opts) : CSON.createCSONString(CSON.parseJSONFile(filePath), opts));
  } else if (process.argv.length === 2) {
    data = '';
    useSTDIN = true;
    convertSTDIN = function() {
      return process.stdout.write(conversion === 'cson2json' ? CSON.createJSONString(CSON.parseCSONString(data), opts) : CSON.createCSONString(CSON.parseJSONString(data), opts));
    };
    timeoutFunction = function() {
      var timeout;
      timeout = null;
      if (data.replace(/\s+/, '')) {
        return;
      }
      useSTDIN = false;
      stdin.pause();
      return convertSTDIN();
    };
    timeout = setTimeout(timeoutFunction, 1000);
    stdin = process.stdin;
    stdin.resume();
    stdin.setEncoding('utf8');
    stdin.on('data', function(_data) {
      return data += _data.toString();
    });
    process.stdin.on('end', function() {
      if (!useSTDIN) {
        return;
      }
      if (timeout) {
        clearTimeout(timeout);
      }
      return convertSTDIN();
    });
  } else {
    outputHelp();
    process.exit(1);
  }

}).call(this);
