#!/usr/bin/awk -f 

# rustic "formail" 


BEGIN	{ 
n=0;

if (TMP=="") DIR="/tmp"
}

/^From /		{ start_hdr=1; start_body=0; n++;
			 body[n]="";
			split($0,A,"^From +"); head[n]=canon(A[2])
			}

/^From:/		{ split($0,A,"^From: +"); from[n]=canon(A[2])} 
/^Subject:/		{ split($0,A,"^Subject: +"); subject[n]=canon(A[2])} 
/^To:/			{ split($0,A,"^To: +"); to[n]=canon(A[2])} 
/^Cc:/			{ split($0,A,"^Cc: +"); cc[n]=canon(A[2])} 
/^X-Mailer:/		{ split($0,A,"^X-Mailer: +"); xmailer[n]=canon(A[2])} 
/^Status:/		{ split($0,A,"^Status: +"); status[n]=A[2]} 
/^Date:/		{ split($0,A,"^Date: +"); date[n]=A[2]}

# usenet part

/^X-Newsreader:/	{ split($0,A,"^X-Newsreader: +"); 
			xnewsreader[n]=canon(A[2])} 
/^Newsgroups:/		{ split($0,A,"^Newsgroups: +"); 
			newsgroups[n]=canon(A[2])} 
/^Organization:/	{ split($0,A,"^Organization: +"); 
			organization[n]=canon(A[2])} 

/^$/			{ if (start_hdr) { start_hdr=0; start_body=1} }

			{ if (start_body) body[n]=body[n]$0"\n"; }

END {

	for (i=1; i<=n; i++)
	{
	fbody=TMP"/body."i
	fhdr=TMP"/hdr."i

	# print report
	if (status[i]=="") status[i]="N";
	

	# split header 
		printf "Head=\"%s\"\n",head[i] > fhdr
		printf "From=\"%s\"\n",from[i] > fhdr
		printf "To=\"%s\"\n",to[i] >> fhdr
		printf "Cc=\"%s\"\n",cc[i] >> fhdr
		printf "Subject=\"%s\"\n",subject[i] >>fhdr
		printf "Date=\"%s\"\n",date[i] >>fhdr
		printf "XMailer=\"%s\"\n",xmailer[i] >>fhdr

		printf "Newsgroups=\"%s\"\n",newsgroups[i] >>fhdr
		printf "Organization=\"%s\"\n",organization[i] >>fhdr
		printf "XNewsreader=\"%s\"\n",xnewsreader[i] >>fhdr

		printf "Status=\"%s\"\n",status[i] >>fhdr
		close(fhdr)
	# split body
		print body[i] > fbody 
		close(fbody);
	}

	# total
	print n > TMP"/msg.count" 
}

# "" problem (remove)

function canon(s)
{

gsub("\"","",s)
return s;

}
