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

#include "global.h"
#include "grade.h"

#include "manhat-lib/shared_util.h"
#include "manhat-lib/shared_cs_util.h"


static void
read_parameters (char *filename, char *course)
{
  cs_get_required_parameter ("file", filename, MAX_PATH);
  cs_get_required_parameter ("crs", course, MAX_PATH);
}




static 
void img_sent (CONFIG_STRUCT *conf, char *file)   
{

 char path[MAX_PATH +1];
 struct stat statbuf;
 FILE *fp;
 char *buffer;
 

  snprintf(path,MAX_PATH + 1, "%s%s/%s/%s", conf->course_path, GRADE_BOOK_DIR, "gradequick", file);
  if (stat (path, &statbuf)) 
       return;                  
       
  if(!statbuf.st_size)
     return;                    /* file has zero length */
          
  buffer = (char *) malloc(statbuf.st_size * sizeof(char));
  if(!buffer)
         return;                /* malloc failed - send didn't work */

   fp = fopen(path, "r");
   if(!fp)
         return;               /* can't open file - send didn't work */


  if(fread(buffer,statbuf.st_size,1,fp) != 1)
    {
     fclose(fp);
     return;      /* read error */
    }    
        
  fclose(fp);

  printf("Content-type: image/png\n\n");      
  fwrite(buffer, statbuf.st_size, 1, stdout);
  free(buffer);
} 

int
main ()
{
  char course[MAX_PATH + 1];	            /* from crs=? command line */
  char file[MAX_PATH + 1];	            /* from crs=? command line */
  CONFIG_STRUCT conf;		            /* the configuration read from config file */

  cs_cgi_init();

  read_parameters (file, course);
  read_configuration_file(course, &conf);
     
  img_sent (&conf, file);   
  cs_cgi_destroy();
  return 0;			/* exit successfully */

}

