/*
 *	fhist - file history and comparison tools
 *	Copyright (C) 2000, 2002, 2004 Peter Miller;
 *	All rights reserved.
 *
 *	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, USA.
 *
 * MANIFEST: functions to deliver output to stdout
 */

#include <ac/stddef.h>
#include <ac/stdio.h>
#include <ac/sys/stat.h>

#include <fcheck.h>
#include <output/private.h>
#include <output/stdout.h>
#include <str.h>
#include <error_intl.h>


typedef struct output_stdout_ty output_stdout_ty;
struct output_stdout_ty
{
	output_ty	inherited;
};


static const char *
standard_output(void)
{
	const char	*name;

	name = "standard output";
	return name;
}


static void
destructor(output_ty *this)
{
	fflush_and_check(stdout, standard_output());
}


static const char *
filename(output_ty *this)
{
	return standard_output();
}


static long
otell(output_ty *this)
{
	return ftell(stdout);
}


static void
oputc(output_ty *fp, int c)
{
	output_stdout_ty *this;

	this = (output_stdout_ty *)fp;
	if (putchar(c) == EOF)
	{
		sub_context_ty	*scp;

		scp = sub_context_new();
		sub_errno_set(scp);
		sub_var_set_charstar(scp, "File_Name", standard_output());
		fatal_intl(scp, i18n("write \"$filename\": $errno"));
		/* NOTREACHED */
	}
}


static void
owrite(output_ty *fp, const void *data, size_t len)
{
	output_stdout_ty *this;

	this = (output_stdout_ty *)fp;
	if (fwrite(data, 1, len, stdout) == EOF)
	{
		sub_context_ty	*scp;

		scp = sub_context_new();
		sub_errno_set(scp);
		sub_var_set_charstar(scp, "File_Name", standard_output());
		fatal_intl(scp, i18n("write \"$filename\": $errno"));
		/* NOTREACHED */
	}
}


static void
oflush(output_ty *this)
{
	if (fflush(stdout))
	{
		sub_context_ty	*scp;

		scp = sub_context_new();
		sub_errno_set(scp);
		sub_var_set_charstar(scp, "File_Name", standard_output());
		fatal_intl(scp, i18n("write \"$filename\": $errno"));
		/* NOTREACHED */
	}
}


static output_vtbl_ty vtbl =
{
	sizeof(output_stdout_ty),
	destructor,
	filename,
	otell,
	oputc,
	output_generic_fputs,
	owrite,
	oflush,
	"stdout",
};


output_ty *
output_stdout(void)
{
	output_ty	*result;
	output_stdout_ty *this;

	result = output_new(&vtbl);
	this = (output_stdout_ty *)result;
	return result;
}
