/* @(#)error.c 1.5 95/09/16 */

/*
 * Copyright (c) 1994, 1995 by Wayne C. Gramlich.  All rights reserved.
 *
 * Permission to use, copy, modify, distribute, and sell this software
 * for any purpose is hereby granted without fee provided that the above
 * copyright notice and this permission are retained.  The author makes
 * no representations about the suitability of this software for any purpose.
 * It is provided "as is" without express or implied warranty.
 */

/* LINTLIBRARY */

#include <stdio.h>

#include "assert.h"
#include "error_extern.h"
#include "memory_extern.h"
#include "vector_extern.h"

typedef struct error_struct *Error;

struct error_struct {
    Str message;		/* The error message: */
};

static Error errors_fetch(Errors, unsigned);

/*
 * errors_create()
 *	This routine will create and return an empty error object
 *	for the head of the error chain.
 */
Errors
errors_create(void)
{
    Errors errors;

    errors = (Errors)vector_create();
    return errors;
}

/*
 * errors_append(errors, message)
 *	This routine will append {message} to {error}.
 */
void
errors_append(
    Errors errors,
    Str message)
{
    Error error;

    error = (Error)memory_allocate(sizeof *error);
    error->message = message;
    vector_append((Vector)errors, (Pointer)error);
}

/*
 * errors_fetch(errors, index)
 *	This routine will return the in {index}'th error mesage from
 *	{index}.
 */
static Error
errors_fetch(
    Errors errors,
    unsigned index)
{
    Error error;

    error = (Error)vector_fetch((Vector)errors, index);
    return error;
}

/*
 * errors_size(errors)
 *	This routine will return the number of errors associted with {error}.
 */
unsigned
errors_size(
    Errors errors)
{
    unsigned size;

    size = vector_size((Vector)errors);
    return size;
}


/*
 * errors_write(errors, out_file, with_html)
 *	This routine will write all of the errors associated with {error}
 *	to {out_file}.  If {with_html} is 1, the output messages will
 *	be formated in HTML.
 */
void
errors_write(
    Errors errors,
    FILE *out_file,
    int with_html)
{
    Error error;
    unsigned index;
    unsigned size;

    size = errors_size(errors);
    (void)fprintf(out_file,
      "<!-- Status: 1 -->\n"
      "%u errors were encountered:\n"
      "\n",
      size);
    if (with_html) {
	(void)fprintf(out_file, "<OL>\n");
    }
    for (index = 0; index < size; index++) {
	error = errors_fetch(errors, index);
        if (with_html) {
	    (void)fprintf(out_file, "<LI>");
	} else {
	    (void)fprintf(out_file, "%d: ", index);
	}
	(void)fprintf(out_file, "%s\n", error->message);
    }
    if (with_html) {
	(void)fprintf(out_file, "</OL>\n");
    }
}


