#include        "stdio.h"
#include        "string.h"

char top_path[]="admin/sys:\\nos\\spool\\mqueue\\";

#define PATH_LEN 72
#define FILE_LEN 13

int get_sequence()
{
	char    path[PATH_LEN+FILE_LEN];
	FILE    *seq_fp;
	long int seq_num;

	strcpy(path,top_path);
	strcat(path,"sequence.seq");

	seq_fp=fopen(path,"r+");

	fscanf(seq_fp,"%d",&seq_num);

	fseek(seq_fp,0,SEEK_SET);

	fprintf(seq_fp,"%d",seq_num+1);

	fclose(seq_fp);

	return (short int)seq_num;

}

int parse_message(char *mess,char *send)
{
	FILE    *mess_fp;
	char    type[128];
	int     send_f=0;

	mess_fp=fopen(mess,"r");

	while(!feof(mess_fp)&&!(send_f==1))
	{
		fscanf(mess_fp,"%s",type);

		if(strncmp(type,"From:",5)==0)
		{
                        fscanf(mess_fp,"%s",send);

			send_f=1;
		}
	}

	fclose(mess_fp);
	return         send_f;
}

#define BUFFSIZE 1024

char    buff[BUFFSIZE];

void main(int argc,char *argv[])
{
	int     seq;
	char    send[128];
	FILE    *src_file;
	FILE    *dest_file;
	char    dest_path[128];
	char    file_name[13];
	int     num_bytes,i;

	seq=get_sequence();

	if(parse_message(argv[1],send))
	{
		src_file=fopen(argv[1],"r");

		strcpy(dest_path,top_path);
		itoa(seq,file_name,10);

		strcat(dest_path,file_name);
		strcat(dest_path,".TXT");

		dest_file=fopen(dest_path,"w+");

		do
		{
			num_bytes=fread(buff,1,BUFFSIZE,src_file);
			fwrite(buff,1,num_bytes,dest_file);
		}
		while(num_bytes==BUFFSIZE)
			;

		fclose(src_file);
		fclose(dest_file);

		strcpy(dest_path,top_path);
		strcat(dest_path,file_name);
		strcat(dest_path,".WRK");

		dest_file=fopen(dest_path,"w+");

	
		if(strchr(argv[2],'@'))
		{
			fprintf(dest_file,"%s\n",strchr(argv[2],'@')+1);

			fprintf(dest_file,"%s\n",send);

			for(i=2;i<argc;i++)
			{
				fprintf(dest_file,"%s\n",argv[i]);
			}
		}

		fclose(dest_file);
		remove(argv[1]);

	}
	else
	{
		printf("RMAILER Failed to send DID not send");
    }
}

