/* 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 : may 1995
 *
 *  Purpose    : Survey questionaire
 *
 *  Modified   : november 1995
 *               Unescape answers.
 *
 *               august 1996
 *               Replace "+" with " ".
 *
 *               september 2002
 *               Small HTML corrections.
 *          
 */

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

#include "cgilib.h"
#include "scriptlib.h"

int lib$getjpi();

int check_access();
void replace(char *s,char *s1,char *s2);

main(int argc,char *argv[])
{
   FILE *fp,*fp2;
   int n,la;
   long pid;
   char *fnm,email[51],del1[3],del2[3],all_a[8001],a[1025];
   char tmpfnm[33],cmd[256],tmp[11],*p1,*p2;
   time_t t;
   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("<P>No access to file: %s</P>\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 email-address and delimeters */
   fgets(email,sizeof(email),fp);
   email[strlen(email)-1]='\0';
   fgets(del1,sizeof(del1),fp);
   del1[strlen(del1)-1]='\0';
   fgets(del2,sizeof(del2),fp);
   del2[strlen(del2)-1]='\0';
   /* read and mail answers */
   lib$getjpi(&JPI$_PID,0,0,&pid,0,0);
   sprintf(tmpfnm,"%d.ZZZ",pid);
   fp2=fopen(tmpfnm,"w");
   n=0;
   for(;;) {
      n++;
      sprintf(tmp,"q%d=",n);
      p1=strstr(all_a,tmp);
      if(p1==NULL) goto fin2;
      p1=strstr(p1,"=");
      p1++;
      p2=strstr(p1,"&");
      if(p2==NULL) p2=p1+1024;
      memset(a,'\0',sizeof(a));
      strncpy(a,p1,p2-p1);
      la = strlen(a);
      net_unescape_string(a,&la);
      a[la] = '\0';
      replace(a,"+"," ");
      fprintf(fp2,"%s%s%s%s",del1,a,del1,del2);
   }
fin2:
   t=time(NULL);
   strcpy(a,ctime(&t));
   a[strlen(a)-1]='\0';
   fprintf(fp2,"%s%s%s\n",del1,a,del1);
   fclose(fp2);
   sprintf(cmd,"MAIL %s %s /SUBJECT=%s",tmpfnm,email,fnm);
   system(cmd);
   remove(tmpfnm);
   cgi_printf("<P>Answers successfully submitted !</P>\n");
   cgi_printf("<P>Thanks for your participation !</P>\n");
   fclose(fp);
fin:
   cgi_printf("</BODY>\n");
   cgi_printf("</HTML>\n");
}
