//
//  Title:  JpegOutputFileStream Implementation
//
//  Copyright 1997-1999, Colosseum Builders, Inc.
//  All rights reserved.
//
//  Colosseum Builders, Inc. makes no warranty, expressed or implied
//  with regards to this software. It is provided as is.
//
//  Author:  John M. Miano (miano@colosseumbuilders.com)
//
//  Date:    March 15, 1999
//
//  Version: 1
//
//  Description:
//
//    JpegOutputFileStream implements JPEG output through a file.
//
//  Revision History:
//
//
#include <fstream>
#include "jpgoutputfilestream.h"

#include <cerrno>
#include <cstring>

using namespace std ;

namespace Colosseum
{
//
//  Description:
//
//    Default Constructor
//
JpegOutputFileStream::JpegOutputFileStream () 
: is_open (false),
  output_buffer (0),
  output_buffer_size (1<<18)
{
  return ;
}
//
//  Description:
//
//    Class Destructor
//
JpegOutputFileStream::~JpegOutputFileStream () 
{
  close () ;
  return ;
}
//
//  Description:
//
//    This function opens the output file.
//
//  Parameters:
//
//    filename : The name of the file to open
//
void JpegOutputFileStream::open (const std::string &filename)
{
  if (is_open)
    throw StreamError ("Already Open") ;

  output_stream.open (filename.c_str (), ios::binary|ios::trunc) ;
  if (output_stream)
  {
    is_open = true ;

    output_buffer = new UBYTE1 [output_buffer_size] ;

    current_byte = output_buffer ;
    buffer_limit = &output_buffer [output_buffer_size] ;
  }
  return ;
}

//
//  Description:
//
//    This function closes the output file.
//
void JpegOutputFileStream::close ()
{
  if (is_open)
  {
    flushBuffer () ;
    output_stream.close () ;
  }
  delete [] output_buffer ; output_buffer = 0 ;
  return ;
}

//
//  Description:
//
//    This function returns the state of the output stream.
//
//  Return Value:
//
//    The state of the output stream.
//
JpegOutputFileStream::operator bool ()
{
#if defined (_MSC_VER)
  bool result = static_cast<void*> (output_stream) != 0 ? true : false ;
#else
  bool result = static_cast<bool> (output_stream) ;
#endif
  return result ;
}
//
//  Description:
//
//    This function writes the contents of the output buffer to
//    the output file.
//
void JpegOutputFileStream::flushBuffer () 
{
  unsigned int count = current_byte - output_buffer ;
  output_stream.write (reinterpret_cast<char*>(output_buffer), count) ;
  buffer_limit = &output_buffer [output_buffer_size] ;
  current_byte = output_buffer ;
  return ;  
}

} // End Namespace
