#include <stdio.h>

/* Args: password-file replyblock-file from output-file */

#define DOMAIN "alpha.c2.org"

int strbegin(char str1[],char str2[]) {
  int x=0;
  int match=0;

  while ((str1[x]==str2[x]||str1[x]==(str2[x]-32))&&str1[x]!=0) {
    x++;
    if (str2[x]==0) match=1;
  }
  return(match);
}

void main(int argc,char *argv[]) {
  char input[256];
  char password[80];
  int x,y;
  FILE *outfile;
  FILE *outmsg;
  int auth=0;

  outfile=fopen(argv[1],"r");
  fscanf(outfile,"%s",password);
  fclose(outfile);
  if (password[0]<=32) {auth=1;password[0]=0;}

  outmsg=fopen(argv[4],"w");

  while(fgets(input,255,stdin)>0) {
    if (strbegin(input,"password:")&&(*password)) {
      auth=1;
      for(x=0;input[x]!=':';x++) {}
      x++;while(input[x]==32) x++;
      y=0;while(input[x]>32&&password[y]>32){
        if (input[x]!=password[y]) auth=0;
        x++;y++;
      }
    }else if ((strbegin(input,"new-password:")&&auth)
             ||(strbegin(input,"password:")&&(*password==0))) {
      outfile=fopen(argv[1],"w");
      for(x=0;input[x]!=':';x++) {}
      x++;while(input[x]==32) x++;            
      while(input[x]>32){
        fprintf(outfile,"%c",input[x]);
        x++;
      }
      fclose(outfile);
    }else if (strbegin(input,"reply-block")&&auth) {
      outfile=fopen(argv[2],"w");
      while((fgets(input,255,stdin)>0)
         &&(strbegin(input,"::")==0)) {}
      fprintf(outfile,"::\n");
      while(fgets(input,255,stdin)>0)
         /*&&(strbegin(input,"-----END PGP")==0)*/ {
        fprintf(outfile,"%s",input);
      }
      /*fprintf(outfile,"%s",input);*/
      fclose(outfile);
    }else if (strbegin(input,"from:")) {
      fprintf(outmsg,"From: %s@%s",argv[3],DOMAIN);
      for(x=0;input[x]>0;x++){
        if (input[x]=='(') {
          fprintf(outmsg," (");x++;
          while (input[x]>=32&&input[x]!=')') {
            fprintf(outmsg,"%c",input[x]);
            x++;
          }
          fprintf(outmsg,")");
        }
      }
      fprintf(outmsg,"\n");
    }else fprintf(outmsg,"%s",input);
  }
  fclose(outmsg);

  /* If the password was bogus, kill the message */
  if (auth==0||password[0]<=32) {outmsg=fopen(argv[4],"w");fclose(outmsg);}
}
