///////////////////////////////////////////////////////////////////////////////
// hsunpack.cpp
// 
//     This utility uses the Image and Compressor classes to
// decompress a .hsc file into a true color BMP file.
///////////////////////////////////////////////////////////////////////////////

#include "Compressor.h"
#include <strings.h>
#include <fstream.h>


int main (int argc, char ** argv)
{
  // Make sure we have the correct number and style of parameters.
  
  if (argc != 2 || argv[1] == NULL || argv[1][0] == 0)
  {
    cout << argv[0] << ':' << endl;
    cout << "  This program decompresses a .HSC file into a .BMP file." <<endl;
    cout << "The .HSC file format is determined by the code you " << endl;
    cout << "place in Compressor.cpp." << endl;
    cout << endl;
    cout << "Usage:" << endl;
    cout << "  " << argv[0] << " filename" << endl;
    cout << endl;
    cout << "\"filename\" must point to a valid .HSC file." << endl;
    return -1;
  }

  // Attempt to open the input stream for reading.

  ifstream InputFile (argv[1]);

  if (!InputFile)
  {
    cout << "Unable to open " << argv[1] << " for reading." << endl;
    cout << "Decompression failed." << endl;
    return -1;
  }

  // Call the decompression utility.  This must not fail as there is no
  //   error checking or reporting.

  Compressor highSchoolCompressor;

  Image tempImage (highSchoolCompressor.decompress (InputFile));

  // Close the input file.

  InputFile.close ();
  
  // Copy the filename, remove the .hsc suffix (if any), and append a .bmp
  //   suffix.

  // Copy it.
  
  int length = strlen (argv[1]);
  
  char * filename = new char [length + 8];

  if (filename == NULL)
  {
    cout << "Memory allocation error." << endl;
    cout << "Decompression failed." << endl;
    return -1;
  }

  strcpy (filename, argv[1]);

  // Change the suffix.
  
  if (strcasecmp (& (filename[length-4]), ".hsc") == 0)
    filename[length-4] = 0;

  strcat (filename, "_new.bmp");

  // Attempt to write out the image.

  if (! tempImage.writeBMP (filename, cout))
  {
    cout << "Compression failed." << endl;
    return -1;
  }

  // Done.

  delete [] filename;
  
  return 0;
}

