///////////////////////////////////////////////////////////////////////////////
// hspack.cpp
// 
//     This utility uses the Image and Compressor classes to compress a
// true color BMP file.  Note that the Image class can only read 24-bit,
// uncompressed BMP files.
///////////////////////////////////////////////////////////////////////////////

#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 compresses a .BMP file into a .HSC file." << endl;
    cout << "The .BMP file must be true color (24 bit), uncompressed," << endl;
    cout << "normal bitmap to be read.  The .HSC file format is" << endl;
    cout << "determined by the code you place in Compressor.cpp." << endl;
    cout << endl;
    cout << "Usage:" << endl;
    cout << "  " << argv[0] << " filename" << endl;
    cout << endl;
    cout << "\"filename\" must point to a valid .BMP file, see above." << endl;
    return -1;
  }

  // Attempt to read in the image.

  Image InputImage;

  if (! InputImage.readBMP (argv[1], cout))
  {
    cout << "Compression failed." << endl;
    return -1;
  }

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

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

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

  strcpy (filename, argv[1]);

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

  strcat (filename, ".hsc");

  // Attempt to open the output stream for writing.

  ofstream OutputFile (filename);

  if (!OutputFile)
  {
    cout << "Unable to open " << filename << " for writing." << endl;
    cout << "Compression failed." << endl;
    return -1;
  }

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

  Compressor highSchoolCompressor;

  highSchoolCompressor.compress (InputImage, OutputFile);

  // Make sure the output file is still open and writable.

  if (!OutputFile)
  {
    cout << "Unknown file " << filename << " error." << endl;
    cout << "Compression failed, output file is in an unknown state." << endl;
    return -1;
  }

  // Close it.  Success!

  OutputFile.close ();

  delete [] filename;
  
  return 0;
}

