/* Collection of code snippets by Arne VajhÃ¸j */
/* (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) */
/*
 *  Author     : Arne Vajhøj
 *
 *  Programmed : april 1995
 *
 *  Purpose    : Q & A test
 *
 *  Modified   : april 1995
 *               Added a SECURE option (which is default on), that will
 *               only use files in a WWW-subdirectory.
 *
 *               april 1995
 *               Changed check to use generic check_access function.
 *
 *               february 1996
 *               Include stdlib.h to compile with DEC C.
 *
 *               august 1996
 *               Handle long questions.
 *
 *               september 2002
 *               Small HTML corrections.
 *
 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

#include "cgilib.h"

int check_access();

main(int argc,char *argv[])
{
   FILE *fp;
   int n,la,ok;
   char *fnm,q[257],*p1,*p2,*p3,*p4,all_a[2001],a[21],tmp[11];
   cgi_init(argc,argv);
   fnm=cgi_info("PATH_INFO");
   fnm++;
   la=atoi(cgi_info("CONTENT_LENGTH"));
   cgi_read(all_a,la);
   all_a[la]='\0';
   cgi_printf("content-type: text/html\n\n");
   cgi_printf("<HTML>\n");
   cgi_printf("<HEAD>\n");
   cgi_printf("<TITLE>%s</TITLE>\n",fnm);
   cgi_printf("</HEAD>\n");
   cgi_printf("<BODY>\n");
   /* open file */
   if(!check_access(fnm)) {
      cgi_printf("No access to file: %s\n",fnm);
      goto fin;
   }
   fp=fopen(fnm,"r");
   if(fp==NULL) {
       cgi_printf("<P>Can not open file: %s</P>\n",fnm);
       goto fin;
   }
   /* read answers and compare with true answer */
   n=0;
   ok=0;
   while(!feof(fp)) {
      fgets(q,sizeof(q),fp);
      p1=strstr(q,"#");
      if(p1!=NULL) {
         *p1='\0';
         p1++;
         while(*p1==' ') p1++;
         p2=p1;
         p2=strstr(p2,"\n");
         p2--;
         while(*p2==' ') p2--;
         p2++;
         *p2='\0';
         n++;
         cgi_printf("%s: ",q);
         sprintf(tmp,"q%d=",n);
         p3=strstr(all_a,tmp);
         p3=strstr(p3,"=");
         p3++;
         p4=strstr(p3,"&");
         if(p4==NULL) p4=p3+20;
         memset(a,'\0',sizeof(a));
         strncpy(a,p3,p4-p3);
         cgi_printf(" %s",a);
         if(strcmp(p1,a)==0) {
            cgi_printf(", True");
            ok++;
         } else {
            cgi_printf(", False (%s)",p1);
         }
         cgi_printf("<BR>\n");
      }
   }
   cgi_printf("<P>\nScore = %d %%</P>\n",(100*ok)/n);
   fclose(fp);
fin:
   cgi_printf("</BODY>\n");
   cgi_printf("</HTML>\n");
}
