#include <fstream.h>
#include "yacio.h"
#include "portable.h"
#include <stdlib.h>
#include <errno.h>
#include "copyright.h"

// This file controls redirected debuging communication

int user_copyright = 0 ;

class TappedFileBuf : public streambuf {
	int overflow(int) ;
	int underflow() ;
	int * CppLine ;
	filebuf * TheFile ;
public:
	TappedFileBuf(const TappedFileBuf &) {exit(224455);}
	TappedFileBuf(int& Line);
	~TappedFileBuf() ;
	filebuf * open(const char * name);
} ;

void CerrSystemErrorMessage(int LastLineFeed=1)
{
	cerr << "The system error message is:\n" ;
	if (errno < sys_nerr) cerr << sys_errlist[errno] ;
	else cerr << "error number: " << errno <<
		" which is not in the system error table" ;
	cerr << "." ;
	if (LastLineFeed) cerr << "\n" ;

}

void OpenFileBuf(const char * FileName, filebuf * ActTabFile)
{
	if (!ActTabFile->open(FileName,ios::out)) {
		cerr << "Can't create output file " << FileName
		<< ".\n" ; 
		CerrSystemErrorMessage();
		exit(1) ;
	}
}

filebuf * TappedFileBuf::open(const char * name)
{
	OpenFileBuf(name,TheFile);
	return TheFile ;
}

TappedFileBuf::TappedFileBuf(int& Line)
{
	TheFile = new filebuf ;
	CppLine = &Line ;
}

TappedFileBuf::~TappedFileBuf()
{
	overflow('\n');
}

int TappedFileBuf::underflow()
{
	cerr << "Underflow\n" ;
	return EOF ;
}

int TappedFileBuf::overflow(int c)
{

	if (c == '\n') (*CppLine)++;
	return TheFile->overflow(c);
}



void add_copyright_notice(const char * FileName, ostream& out)
{
	AddCopyright& add = AddCopyright::add_copyright() ;
	add.write_short(out,FileName,user_copyright);
}

int UserOwnedFiles = 0 ;

ostream* OpenFile (const char * FileName)
{
	struct filebuf * ActTabFile = new filebuf ;
	OpenFileBuf(FileName,ActTabFile);
	// ostream* Ret =  new ostream(ActTabFile) ;
	ostream* Ret =  new ostream ;
	Ret->rdbuf(ActTabFile);
	if (!UserOwnedFiles) add_copyright_notice(FileName,*Ret);
	return Ret ;
}


ostream& OpenTappedFile (const char * FileName, int& line)
{
	struct TappedFileBuf * TheBuf = new TappedFileBuf(line);
	TheBuf->open(FileName);
	// ostream * Ret = new ostream(TheBuf);
	ostream * Ret = new ostream;
	Ret->rdbuf(TheBuf);
	add_copyright_notice(FileName,*Ret);
	return *Ret ;
}

extern int UserOwnedFiles ;
// set to `1' in delivered package to avoid adding copyright
// notice to user created files

