/*
 * Copyright (C) by Argonne National Laboratory
 *     See COPYRIGHT in top-level directory
 */

#include "mpi.h"
#include <stdio.h>
#include <stdlib.h>
#include "mpitest.h"
#include "mpitestconf.h"
#ifdef HAVE_STRING_H
#include <string.h>
#endif

/* Create NCLASSES new classes, each with 5 codes (160 total) */
#define NCLASSES 32
#define NCODES   5

int main(int argc, char *argv[])
{
    int errs = 0;
    char string[MPI_MAX_ERROR_STRING], outstring[MPI_MAX_ERROR_STRING];
    int newclass[NCLASSES], newcode[NCLASSES][NCODES];
    int i, j, slen, outclass;

    MTest_Init(&argc, &argv);

#if MTEST_HAVE_MIN_MPI_VERSION(4,1)
    /* add and delete a bunch of times */
    for (int k = 0; k < 10000; k++) {
        for (i = 0; i < NCLASSES; i++) {
            MPI_Add_error_class(&newclass[i]);
            for (j = 0; j < NCODES; j++) {
                MPI_Add_error_code(newclass[i], &newcode[i][j]);
                sprintf(string, "random incorrect string\n");
                MPI_Add_error_string(newcode[i][j], string);
            }
        }
        for (i = 0; i < NCLASSES; i++) {
            for (j = 0; j < NCODES; j++) {
                MPI_Remove_error_string(newcode[i][j]);
                MPI_Remove_error_code(newcode[i][j]);
            }
            MPI_Remove_error_class(newclass[i]);
        }
    }
#endif

    /* Initialize the new codes */
    for (i = 0; i < NCLASSES; i++) {
        MPI_Add_error_class(&newclass[i]);
        for (j = 0; j < NCODES; j++) {
            MPI_Add_error_code(newclass[i], &newcode[i][j]);
            sprintf(string, "code for class %d code %d\n", i, j);
            MPI_Add_error_string(newcode[i][j], string);
        }
    }

    /* check the values */
    for (i = 0; i < NCLASSES; i++) {
        MPI_Error_class(newclass[i], &outclass);
        if (outclass != newclass[i]) {
            errs++;
            printf("Error class %d is not a valid error code %x %x\n", i, outclass, newclass[i]);
        }
        for (j = 0; j < NCODES; j++) {
            MPI_Error_class(newcode[i][j], &outclass);
            if (outclass != newclass[i]) {
                errs++;
                printf("Class of code for %d is not correct %x %x\n", j, outclass, newclass[i]);
            }
            MPI_Error_string(newcode[i][j], outstring, &slen);
            sprintf(string, "code for class %d code %d\n", i, j);
            if (strcmp(outstring, string)) {
                errs++;
                printf("Error string is :%s: but should be :%s:\n", outstring, string);
            }
        }
    }

    MTest_Finalize(errs);
    return MTestReturnValue(errs);
}
