/* This file is part of cardwords
   (c) 1999 Tobias Peters
   see file COPYING for the copyright terms.
   
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

// cardwords_readfile.cc

#include <sys/stat.h> // for stat().
#include <unistd.h>   // for stat().
#include <stdio.h>    // for perror().
#include <strstream.h>
#include <fstream.h>
#include "cardwords_readfile.hh"
#include "cardwords_gettext.hh"

CardWords_ReadFile::CardWords_ReadFile(const string & filename)
{
  // Opening the text file: constructing the filename:
  ostrstream text_file_name;
  text_file_name << LIBDIR_STR
                 << filename
                 << ends;

  // Open the file that contains the text:
  text_file_name.freeze(true);

  ifstream text_file(text_file_name.str());

  
  if (text_file.bad()) {
    // Text file not found
    cerr << gettext("WARNING: Cannot open text file ")
         << text_file_name.str()
         << endl;
    text_file_name.freeze(false);
    successful = false;
    return;
  }
  
  text_file.unsetf(ios::skipws); // Read all white space.

  struct stat text_file_stat;
  if (stat(text_file_name.str(),
           &text_file_stat)
      < 0) {
    cerr << gettext("WARNING: Cannot open text file ")
         << flush;
    perror(text_file_name.str());
    text_file_name.freeze(false);
    successful = false;
    return;
  }

  text_file_name.freeze(false);

  char * text_file_contents_array = new char[text_file_stat.st_size + 1];

  // Copy the help file contents into memory:
  text_file.get(text_file_contents_array,
                text_file_stat.st_size + 1,
                '\0');
  text_file_contents = text_file_contents_array;
  delete [] text_file_contents_array;
  
  successful = true;
}

CardWords_ReadFile::CardWords_ReadFile(const CardWords_ReadFile &other)
{
  successful = other.successful;

  if (other.successful == true) {
    text_file_contents = other.str();
  }
}


CardWords_ReadFile::~CardWords_ReadFile()
{
}

CardWords_ReadFile::operator bool() const
{
  return successful;
}

const string &
CardWords_ReadFile::str(void) const
{
  return text_file_contents;
}
