#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>  /* for unlink() */
#include <dirent.h>

#include "../global.h"

#include "shared_util.h"
#include "shared_person_list.h"
#include "shared_cs_util.h"


void
update_grades_inf (const CONFIG_STRUCT *conf, const char *username)
{
  DIR *dir_p;
  struct dirent *dir_entry_p;
  char *ptr;
  char dirname[MAX_PATH + 1];
  char red_fname[MAX_PATH + 1];
  char inf_fname[MAX_PATH + 1];
  GRADES_INFO_STRUCT grades_inf;
  FILE *fp, *outfp;

  snprintf (dirname, MAX_PATH + 1, "%speople/%s/grades", conf->course_path, username);
  dir_p = opendir (dirname);
  if (!dir_p)
    cs_critical_error (ERR_OPENDIR_FAILED, "");
  snprintf (inf_fname, MAX_PATH + 1, "%s/%s", dirname, GRADES_INF_FNAME);
  outfp = fopen (inf_fname, "a");
  if (!outfp)
    cs_critical_error (ERR_FOPEN_APPEND_FAILED, "");

  while (NULL != (dir_entry_p = readdir (dir_p)))
    {
      ptr = strstr (dir_entry_p->d_name, ".red");
      if (ptr && *(ptr + 4) == '\0')	/* i.e. if file ends in .red */
	{
	  snprintf (red_fname, MAX_PATH + 1, "%s/%s", dirname,
		    dir_entry_p->d_name);

	  /* read the *.red file */
	  fp = fopen (red_fname, "r");
	  if (!fp)
	    cs_critical_error (ERR_RED_READ_OPEN, "");
	  if (fread (&grades_inf, sizeof (GRADES_INFO_STRUCT), 1, fp) != 1)
	    cs_critical_error (ERR_RED_READ, "");
	  fclose (fp);
	  unlink (red_fname);

	  /* append it to the 'info' file */

	  if (fwrite (&grades_inf, sizeof (GRADES_INFO_STRUCT), 1, outfp) != 1)
	    cs_critical_error (ERR_FWRITE_FAILED, "");
	}

    }
  fclose (outfp);
  closedir (dir_p);
}



