/*
** output.c:
**
** Reads through the contents of the student hass-d selection database
** and prints the values in the following format:
** 
** One line per student, consisting of
** Field:          login  MIT-id  First  Middle  Last  Course1  Section1...
** Length:         8      9       16     16      16    8        3
** 
** The course-section pair is repeated six times.  All fields are padded
** with spaces.
**
*/

#include        "db.h"
#include        <stdio.h>
#include        <ndbm.h>
#include	<sys/file.h>

#define	CHOICES		1
#define	DEENROLL	2

static int	mode;
static int	fakessn = 100000000;

main (argc, argv)
int     argc;
char    *argv[];
{

	DBM	*db;
	datum   data;
        datum   key;
        StudentRecPtr	value;
        StudentRec	realrecord;


	if (argc != 2 || (strcmp (argv[1], "1") && strcmp (argv[1], "2"))) {
		fprintf (stderr, "Usage: %s [1 | 2]\n", argv[0]);
		fprintf (stderr, "1 = list of students' choices\n");
		fprintf (stderr, "2 = list of students requesting deenroll\n");
		exit(-1);
	}
	if (!strcmp (argv[1], "1")) {
		mode = CHOICES;
	}
	if (!strcmp (argv[1], "2")) {
		mode = DEENROLL;
	}


/*
** Open my database.
*/

        db = dbm_open(DATAFILE, O_RDWR, 0600);
        if (db == NULL) {
                err_dump ("can't open database file");
        }

/*
** Loop through the entries and print out their contents.
*/
	for (	key = dbm_firstkey(db); 
		key.dptr != NULL; 
		key = dbm_nextkey(db)) {

		data = dbm_fetch(db, key);

		bcopy (data.dptr, &realrecord, sizeof (StudentRec));

		fakessn++;

		if (mode == CHOICES)
			FormattedOutputChoices(&realrecord);
		if (mode == DEENROLL)
			FormattedOutputDeenroll(&realrecord);
	}
}


FormattedOutputChoices(value)
StudentRecPtr value;
{
	int i;

	printf ("%-8s%-9d%-16s%-16s%-16s",
		value->login,
		fakessn,
		"John",
		"Queue",
		"Public");

	for (i = 0; i < MAX_CHOICES; i++) {
		if ((value->selections[i].course)[0] != NULL)
			printf (	"%-8s%-3d", 
					value->selections[i].course,
					value->selections[i].section);
		else
			printf (	"%-8s%-3d", 
					"NONE",
					0);
	}
	printf ("\n");
}

FormattedOutputDeenroll(value)
StudentRecPtr value;
{
	 if (value->deenroll)
	 /*
		printf ("%s\n", value->login);
	*/
		printf ("%d\n", fakessn);
}
