/*************************************************************

 Huffman coding main.cpp

 This program parses the command-line arguments.  
							     
 *************************************************************/
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <utility>

#include "huffman_codec.h"

// The name of the executable
std::string exec_name;

/*************************************************************

 Print the following error message if the command-line arguments
 are not correct.

 *************************************************************/
void usage_error() {
  std::cerr << "usage: " << exec_name << " encode|decode infile [outfile]" 
	    << std::endl;
  exit(1);
}

/*************************************************************

 Main routine.

 Input: command-line arguments

 *************************************************************/
void main(int argc, char * argv[]) {

  // Sets the name of the executable
  exec_name = argv[0];

  // Tests if the number of command-line arguments is correct.
  if (argc < 3 || argc > 4)
    usage_error();

  // Gets the mode
  // Modes are "encode" or "decode"
  std::string mode;
  std::istringstream s;
  s.str(argv[1]);
  s >> mode;

  // Sets the input file stream
  std::ifstream infile(argv[2], std::ios_base::in|std::ios_base::binary);
  if (!infile)
  {
    std::cerr << "error opening input file: " << argv[2] << std::endl;
    exit(1);
  }
  
  // Sets the standard output stream to the output file
  std::ofstream outfile;
  if (argc > 3)
  {
    outfile.open(argv[3], std::ios_base::out|std::ios_base::binary);
    if (!outfile)
    {
      std::cerr << "error opening output file: " << argv[3] << std::endl;
      exit(1);
    }
    std::cout = outfile;
  }
  
  // Calls huffman decode or encode depending upon the mode
  // Call both functions with the input file stream and output stream
  huffman_codec c;
  if (!mode.compare("encode"))
    c.encode(infile, std::cout);
  else if (!mode.compare("decode"))
    c.decode(infile, std::cout);
  else
    usage_error();
}
