/* COPYRIGHT 2000 Fred Hutchinson Cancer Research Center 
	email.c
	Read a file sequences and submit them at intervals
	to the blocks server; interval is determined by
	sequence length and type
		email <file of seqs> 
--------------------------------------------------------------------
 9/ 4/00
====================================================================*/

#define EXTERN
#define MAXNAME 80	/* Maximum file name length */
#define EMAILADD "blocks@blocks.fhcrc.org"	/* email server address */

#include <blocksprogs.h>

/*=======================================================================*/
/*
 * main
 */

int main(argc, argv)
     int argc;
     char *argv[];
{
  FILE *bfp, *ofp;
  Sequence *sequence;
  char filename[MAXNAME], outname[MAXNAME], ctemp[MAXNAME];
  int seconds, pid;
  int db_type, seq_type;

  /* ------------1st arg = sequence file -----------------------------------*/
   if (argc > 1)
      strcpy(filename, argv[1]);
   else
   {
      printf("\nEnter name of sequence file: ");
      gets(filename);
   }
   if ( (bfp=fopen(filename, "r")) == NULL)
   {
      printf("\nCannot open file %s\n", filename);
      exit(-1);
   }
   /*  Making a unique temporary file name here */
   pid = (int) getpid();
   sprintf(outname, "%d.seq", pid);

   db_type = type_dbs(bfp, DbInfo);
   seq_type = seq_type_dbs(bfp, DbInfo, db_type);

  /*-----------------------------------------------------------------*/

  while ((sequence = read_a_sequence(bfp, db_type, seq_type)) != NULL)
  {
     /*  Assuming rate of 150aas/min, 2.5/sec   */
     seconds = round((double) sequence->length/2.5);
     if (seq_type == NA_SEQ) seconds *= 2;

     if ( (ofp=fopen(outname, "w")) != NULL)
     {
        /* Add or modify parameters; see
		http://blocks.fhcrc.org/help/email.html  */
        fprintf(ofp, "#OU sum\n");
        fprintf(ofp, "#EX 1\n");
        fprintf(ofp, "#SQ\n");
        output_sequence(sequence, ofp);
        fclose(ofp);

	/* mailx is the Solaris mail program, yours might be in
		/bin/mail or someplace else */
        sprintf(ctemp, "/usr/bin/mailx -s %s %s < %s",
	   sequence->name, EMAILADD, outname);
        printf("Submitting %s (len=%d %d seconds)\n", 
              sequence->name, sequence->length,  seconds);
        system(ctemp);
        sleep(seconds);
     }
  }
  fclose(bfp);
  sprintf(ctemp, "rm %s", outname);
  system(ctemp);

  exit(0);

}  /* end of main */
