/*
 *      dnsutl - utilities to make DNS easier to configure
 *      Copyright (C) 1996, 1999, 2006, 2007 Peter Miller
 *
 *      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 3 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, see
 *      <http://www.gnu.org/licenses/>.
 */

#include <ac/stdarg.h>
#include <ac/stdio.h>

#include <error.h>
#include <output.h>


static FILE     *fp;
static const char *fn;
static int      number_of_errors;


void
output_open(const char *filename)
{
    assert(!fp);
    if (filename)
    {
        fp = fopen(filename, "w");
        if (!fp)
            nfatal("open \"%s\"", filename);
        fn = filename;
    }
    else
    {
        fp = stdout;
        fn = "standard output";
    }
    number_of_errors = 0;
}


void
output_close(void)
{
    assert(fp);
    if (number_of_errors)
    {
        fatal
        (
            "%s: found %d fatal error%s",
            fn,
            number_of_errors,
            (number_of_errors == 1 ? "" : "s")
        );
    }
    if (fflush(fp))
        nfatal("write %s", fn);
    if (fp != stdout && fclose(fp))
        nfatal("close %s", fn);
    fn = 0;
    fp = 0;
}


void
output_printf(const char *s, ...)
{
    va_list         ap;

    assert(fp);
    va_start(ap, s);
    vfprintf(fp, s, ap);
    va_end(ap);
    if (ferror(fp))
        nfatal("write %s", fn);
}


void
output_error(const char *s, ...)
{
    va_list         ap;
    char            buffer[1000];

    va_start(ap, s);
    vsprintf(buffer, s, ap);
    va_end(ap);
    error("%s: %s", fn, buffer);
    ++number_of_errors;
}


void
output_error_locn(const char *fname, int lnum, const char *s, ...)
{
    va_list         ap;
    char            buffer[1000];

    va_start(ap, s);
    vsprintf(buffer, s, ap);
    va_end(ap);
    error("%s: %d: %s", fname, lnum, buffer);
    ++number_of_errors;
}


syntax highlighted by Code2HTML, v. 0.9.1