// Copyright 1992 by Jon Dart.  All Rights Reserved.

#include "stdafx.h"
#include "bookwrit.h"
#include "constant.h"

const int Entry_Size = sizeof(Book_Entry);
const int Header_Size = sizeof(unsigned long) + 1;
const int Buffer_Size = 4096;
// Setting this to the book size will keep the whole book in memory,
// which will improve speed.
const char Book_File_Name[] = "book";

static byte *write_buffer;

Book_Writer::Book_Writer( const byte version, const unsigned size )
: book_file( Book_File_Name, 
	     ios::out | ios::trunc | ios::binary ),
  my_size(size),
  my_version(version),
  index(0)
{
   is_open = FALSE;
   if (!book_file.good())
      return;
   is_open = TRUE;
   book_file.write( (char*)&my_version, 1 );
   book_file.write( (char*)&my_size, (int)sizeof(unsigned));
   write_buffer = new byte[Buffer_Size];
}

Book_Writer::~Book_Writer()
{
   if (index)
      book_file.write( write_buffer, index );
   book_file.close();
   delete [] write_buffer;
}

BOOL Book_Writer::Write( Book_Entry &be )
{
   ASSERT(is_open);

   if (index + sizeof(be) <= Buffer_Size )
   {
      memcpy(write_buffer+index,&be,sizeof(be));
      index += sizeof(be);
   }
   else
   {
      unsigned to_go = Buffer_Size - index;
      memcpy(write_buffer+index,&be,to_go);
      book_file.write( write_buffer, Buffer_Size );
      memcpy(write_buffer,&be + to_go,sizeof(be)-to_go);
      index = sizeof(be)-to_go;
   }
   return TRUE;
}


