/*
 * Prefix input with `From' header and optional 'To: ' line
 */

#include <stdio.h>
#include "mail.h"

extern char TO[], *strchr (), cclist[LSIZE], ORG[128];
extern int rmail;

envelope (outf, fmbuf, tobuf, textfp)
     FILE *outf;
     char *fmbuf;
     char *tobuf;
     FILE *textfp;
{
   register char *p;
   char line[LSIZE];

   putsf ("DEBUG: envelope start");
   Readio.r_size = ftell (textfp);
	putsf ("DEBUG: envelope checkpoint 0a");
   Readio.r_nlcnt = 0;
	putsf ("DEBUG: envelope checkpoint 0b");
   Readio.r_lines = 0;
	putsf ("DEBUG: envelope checkpoint 0c");
   if (Readio.r_size)
     {
	fseek (textfp, 0L, 0);

	putsf ("DEBUG: envelope checkpoint 0d");
	/* write out `From' header */
	Readio.r_size += strlen (fmbuf);
	for (p = fmbuf; p = strchr (p, '\n'); p++)
	   Readio.r_lines++;
	fputs (fmbuf, outf);

	putsf ("DEBUG: envelope checkpoint 1");
	if (rmail == 0 && ORG[0] != NULL)
	  {
	     /* do the Organization: stuff */
	     Readio.r_size += strlen (ORG) + sizeof ("Organization: ");
	     Readio.r_lines++;
	     fprintf (outf, "Organization: %s\n", ORG);
	  }

	putsf ("DEBUG: envelope checkpoint 2");
	/* if there's a `To:' line, write it out */
	if (tobuf != NULL)
	  {
	     Readio.r_size += (strlen (tobuf) + strlen (TO));
	     Readio.r_lines++;
	     fprintf (outf, "%s%s", TO, tobuf);
	     /* if we don't have an alias, don't write it out */
	     if (strcmp (tobuf, unalias (tobuf)) != 0)
		fprintf (outf, " (%s)", unalias (tobuf));
	     fprintf (outf, "\n");
	  }
	putsf ("DEBUG: envelope checkpoint 3");
	/* if there's a `Cc:' line, write it out */
	if (cclist[0] != NULL)
	  {
	     Readio.r_size += (strlen (cclist) + 4);
	     Readio.r_lines++;
	     fprintf (outf, "Cc: %s", cclist);
	     strcat (tobuf, " ");
	     strcat (tobuf, cclist);
	  }

	putsf ("DEBUG: envelope checkpoint 4");
	while (fgets (line, LSIZE, textfp) != NULL)
	  {
	     if (line[0] == '\n')
		Readio.r_nlcnt++;
	     else
	       {
		  /*
                   *   Although this version of mail can
                   *   parse "From " lines better than most
                   *   we have to escape the /^From / sequences
                   *   for older versions, so they don't get
                   *   confused.
                   */
		  putsf ("DEBUG: envelope checkpoint 5");
		  if (sindex (line, "From ") == 0)
		    {
		       Readio.r_size++;
		       fputc ('>', outf);
		    }
		  Readio.r_nlcnt = 0;
	       }
	     putsf ("DEBUG: envelope checkpoint 6");
	     Readio.r_lines++;
	     fputs (line, outf);
	  }

	putsf ("DEBUG: envelope checkpoint 7");
	if (Readio.r_nlcnt < 2)
	  {
	     fputc ('\n', outf);
	     Readio.r_lines++;
	     Readio.r_size++;
	     Readio.r_nlcnt++;
	  }

	fflush (outf);
     }

   putsf ("DEBUG: envelope checkpoint 8");
   fclose (textfp);
   fclose (outf);
   putsf ("DEBUG: envelope return");
}
