/*     ~ptest/src/makelis.c   for blockmaker email server
       Read the sequences in the mail message & convert them
       into fasta format for motifj & gibbsj using blimps routines

	   makelis name return
	
	where name is from "name.in" which contains the
	mail message, "return" is the return address.
        Expects the full mail message to be in "name.in" (gets Subject
        line and sequences from the body).

	Writes name.seqlen (for block maps), name.lis, name.pros,
		name.warn & name.err: processmail mail will quit
		if name.err is non-empty.

=========================================================================
 3/11/95  Since motifj no longer requires the sequences in separate files,
          modified this to dump them all into one file   JGH
 4/ 2/95  Edit sequences and change all "-" or "*" to "X" for gibbsj, which 
	  chokes on dashes (added edit_seq() ).
 6/22/95  Don't change "*" to "X", caused problem with TC1 seqs for gibbsj
 8/ 7/97  Added .seqlen output file
10/15/97  Get sequences directly from the .in file (don't use readseq or
          the .seq file from processmail any more). Fix up non-unique
          sequence names. Warning if sequences appear to be DNA.
10/23/97  Removed warnings - writing to stderr causes processmail to quit.
10/25/97  Added .warn file
 1/12/99  If sequence names start ">P1;" change to just ">" because
	  clustalw will assume PIR format otherwise.
 6/20/99  Sequence name from 10 to 18; need to get rid of leading spaces
	  between fields on title line (eg seq->info)
 6/ 5/00  ACLEN from 7 to 9
 7/15/01  Don't run protomat.csh if DNA seqs (write to ErrP not WarnP)
 5/15/02  SNAMELEN issue; motifj really uses SNAMELEN-1; changed it from
		18 to 17 here to be safe, but this isn't really right
12/23/06 Increased sequence name length
========================================================================*/
#define EXTERN
#define XNAMELEN 19
#define ACLEN 9

/*	Include files from $BLIMPS_DIR/include  */
#include <blocksprogs.h>
/*	Include files from $BLIMPS_DIR/blimps  */
#include "blimps.h"
#include "license.h"
#include "blimps-mem.h"
#include "config.h"
#include "scores.h"
#include "scoring.h"		/* for alignments_done and scores_done */
#include "lists.h"

Boolean SavedScoresFlag;		/* not used, blimps kludge */


/*	Local routines */
int make_lis();
void edit_seq();
void get_seqs();
int read_seqs();

/*	Global variables */
char SequenceFile[LARGE_BUFF_LENGTH];
char LisFile[LARGE_BUFF_LENGTH], ProFile[LARGE_BUFF_LENGTH];
char LenFile[LARGE_BUFF_LENGTH];
char ErrFile[LARGE_BUFF_LENGTH];
FILE *LisFileP, *LenFileP, *ProFileP, *ErrP, *WarnP;

char Path[LARGE_BUFF_LENGTH];
char Process[LARGE_BUFF_LENGTH];

char User[LARGE_BUFF_LENGTH];
char Return[LARGE_BUFF_LENGTH];

char BlockName[LARGE_BUFF_LENGTH];

char SubjectLine[LARGE_BUFF_LENGTH];
char TruncSubjectLine[LARGE_BUFF_LENGTH];
char DELine[LARGE_BUFF_LENGTH];

int Count = 0;

int NumberToReport;		/* needed for lists.c */
/*	Following are needed to scores.c , not really used */
int SearchType, SequenceMatrixScoringMethod;

/*=========================================================================*/
int main(argc, argv)
     int argc;
     char *argv[];		/* arg[1] path name + process name */
				/* arg[2] return address */
{
  int i, str_length;

  FILE *mailfp;

  ErrorLevelReport = SERIOUS_ERR_LVL; /* report only serious and higher */
  /*  Have to use stderr because the blimps routines write to it, so
      make it a named file. Any write to .err causes processmail to
      quit, non-fatal messages are written to .warn later    */
  sprintf(ErrFile, "%s.err", argv[1]);
  ErrP = freopen(ErrFile, "a", stderr);

  initialize_lists();

  strncpy(Path, argv[1], LARGE_BUFF_LENGTH);

  /*------------------------------------------------------------------------------*/
  /*  All this code is to construct the first line of the .lis file for protomat:
       format is ">AC     ;ID ;DE ;;$", here AC = 1st 8 chars of Subject line,
	ID = complete Subject line, DE = from first sequence info */

  str_length = (int) strlen(Path);
  str_length--;
  while ((Path[str_length] != '/') &&
	 (str_length >= 0)) {
    str_length--;
  }

  strncpy(Process, Path+str_length+1, LARGE_BUFF_LENGTH);
  Path[str_length+1] = '\0';

  strncpy(User, argv[2], LARGE_BUFF_LENGTH);
  str_length = (int) strlen(User);
  str_length--;
  while ((User[str_length] != '@') &&
	 (str_length >= 0)) {
    str_length--;
  }

  if (str_length < 0) {
    sprintf(Return, " ");	/* the space is so that the header is */
				/* built right */
  }
  else {
    strncpy(Return, User+str_length+1, LARGE_BUFF_LENGTH);
    User[str_length] = '\0';
  }

  strncpy(BlockName, User, LARGE_BUFF_LENGTH);
  BlockName[ACLEN] = ' ';
  BlockName[ACLEN+1] = '\0';
  str_length = 0;
  for (i=0; i<ACLEN; i++) {
    if ((BlockName[i] == '\0') ||
	(BlockName[i] == ' ')) {
      BlockName[i] = '_';
    }
  }


  /* get the Subject line */
  sprintf(Buffer, "%s.in", argv[1]);
  if ( (mailfp = fopen(Buffer, "r")) == NULL)
  {
     fprintf(stderr, "Could not open %s\n", Buffer);
     exit(-1);
  }
  while ((fgets(Buffer, LARGE_BUFF_LENGTH, mailfp) != NULL) &&
	 (! feof(mailfp)) &&
	 (strncmp(Buffer, "Subject:", 8) != 0));
  /* copy the info of the subject line */
  if (feof(mailfp)) {
    strcpy(SubjectLine, "");
  }
  else {
    strcpy(SubjectLine, &Buffer[ACLEN]);
    remove_trailing_whitespace(SubjectLine);
    if ((int) strlen(SubjectLine) != 0) {
      if ((int) strlen(SubjectLine) > 20) {
	sprintf(SubjectLine, "%19s...", SubjectLine);
      }
    }
  }
  strncpy(TruncSubjectLine, SubjectLine, LARGE_BUFF_LENGTH);
  TruncSubjectLine[ACLEN] = ' ';
  TruncSubjectLine[ACLEN+1] = '\0';
  str_length = 0;
  for (i=0; i<ACLEN; i++) {
    if ((TruncSubjectLine[i] == '\0') ||
	(TruncSubjectLine[i] == ' ')) {
      TruncSubjectLine[i] = '_';
    }
  }
  strcpy(DELine, "SubjectLine");
  fclose(mailfp);

  /*---------------------------------------------------------------------*/
  /*   Open the output files  */

  sprintf(LisFile, "%s.lis", argv[1]);
  sprintf(LenFile, "%s.seqlen", argv[1]);
  sprintf(ProFile, "%s.pros", argv[1]);
  sprintf(ErrFile, "%s.warn", argv[1]);
  
  LisFileP = fopen(LisFile, "w");
  LenFileP = fopen(LenFile, "w");
  ProFileP = fopen(ProFile, "w");
  WarnP = fopen(ErrFile, "w");

  /*---------------------------------------------------------------------*/
  /*  Extract the sequences from the body of the .in file  & put them in
      a list */
  sprintf(SequenceFile, "%s.in", argv[1]);
  get_seqs(SequenceFile);

  /*   Initialize the .lis file, DELine was set in get_seqs  */
  if ((int) strlen(SubjectLine) != 0) {
    fprintf(LisFileP, ">%s;%s;%s;;$\n", TruncSubjectLine, SubjectLine, DELine);
  }
  else {
    fprintf(LisFileP, ">%s;%s;%s;;$\n", BlockName, argv[2], DELine);
  }
  fprintf(LisFileP, "%s\n", Path);

  /*  Executes make_lis for each sequence in the list of sequences */
  DoForSL(Sequences, make_lis, NULL);

  if (Count < 3)
    fprintf(stderr, "Only %d sequence found, need at least 3\n", Count);
  fclose(LisFileP); fclose(LenFileP); fclose(ProFileP);
  exit(0);
}  /* end of main */

/*========================================================================
    Fixes up the sequence name, writes the .lis, .seqlen & .pros files
=========================================================================*/
int make_lis(seq, arg)
     Sequence *seq;
     void *arg;   /* Not used */
{
  char seqname[LARGE_BUFF_LENGTH];

  strncpy(seqname, seq->name, XNAMELEN);
  if (strcmp(seqname, "\0") == 0) {
    sprintf(seqname, "%s_%d", Process, Count);
  }
  seqname[XNAMELEN] = '\0';		/* ensure ony 20 characters long */

  fprintf(LisFileP, "%s\tLENGTH=%d\n", seqname, seq->length);
  fprintf(LenFileP, "%s\t%d\n", seqname, seq->length);

  output_sequence(seq, ProFileP);

  Count++;

  return SL_CONTINUE;
} /* end of make_lis */

/*=========================================================================
    Change "-" to "X" for gibbsj so it doesn't choke
	X is 23, - is 0, * is 24
===========================================================================*/
void edit_seq(seq)
Sequence *seq;
{
   int i;

   for (i=0; i < seq->length; i++)
      if (seq->type == AA_SEQ && seq->sequence[i] == 0)
	  seq->sequence[i] = 23;
}   /* end of edit_seq */

/*=======================================================================
     Open the .in file and skip to the first blank line. The sequences
     are assumed to start following the first blank line.
     Problems if the first non-blank line following the first blank line
	begins with white space ...
=========================================================================*/
void get_seqs(seq_file)
     char *seq_file;
{
  long fpos;
  char line[LARGE_BUFF_LENGTH];
  int nseq;

  /* put the sequence file in the memory */
  insert_file(seq_file, SEQUENCE_FILES);

  SequenceFiles.fp = fopen(SequenceFiles.file_names[0], "r");
  
  /*  read to first blank line, then set start of sequences to next line */
  if (SequenceFiles.fp != NULL) 
  {
    /*  Read to first blank line and mark it  */
    while(!feof(SequenceFiles.fp) && 
          fgets(line, sizeof(line), SequenceFiles.fp) != NULL &&
                strlen(line) > 1 )
/*>>>>DEBUG
                  printf("%d %s", (int) strlen(line), line);
DEBUG<<<<*/
			;
    fpos = ftell(SequenceFiles.fp);

    /* determine sequence database db_type and seq_type */
    /*  type_dbs() reads one line and then rewinds .fp  */
    SequenceFiles.db_type = type_dbs(SequenceFiles.fp, DbInfo);
    fseek(SequenceFiles.fp, fpos, 0);

    if (SequenceFiles.db_type < 0 || SequenceFiles.db_type >= MAXDB)
    {
      /* unknown database type */
      sprintf(ErrorBuffer, 
              "Unknown sequence format.  Known formats are:");
      ErrorReport(SERIOUS_ERR_LVL);
      sprintf(ErrorBuffer,
              "Fasta, GenBank, PIR, Swiss Prot, and GCG.");
      ErrorReport(SERIOUS_ERR_LVL);
      sprintf(ErrorBuffer,
              "Trying with Fasta format.\n");
      ErrorReport(SERIOUS_ERR_LVL);
      SequenceFiles.db_type = FASTA;
    }
    SequenceFiles.seq_type = seq_type_dbs(SequenceFiles.fp, DbInfo,
            SequenceFiles.db_type, UNKNOWN_SEQ);
    fseek(SequenceFiles.fp, fpos, 0);

    if (SequenceFiles.seq_type == NA_SEQ) 
    {
      fprintf(ErrP, 
         "Sequences appear to be DNA: Block Maker is designed for protein.");
    }

    /*   Now read the sequences   */
    nseq =
     read_seqs(SequenceFiles.fp, SequenceFiles.db_type, SequenceFiles.seq_type);
  }  /* end of good input file  */

  else 
  {
    sprintf(ErrorBuffer, "Unable to read sequence file: %s ",
            SequenceFiles.file_names[0]);
    ErrorReport(SERIOUS_ERR_LVL);
    sprintf(ErrorBuffer, "to determine the type of database\n");
    ErrorReport(SERIOUS_ERR_LVL);
  }
} /* end of get_seqs */

/*======================================================================
   Read the sequences into a list
=======================================================================*/
int read_seqs(fp, db_type, seq_type)
FILE *fp;
int db_type, seq_type;
{
  Sequence *seq;
  Boolean first_seq = TRUE;
  int i, itemp, nseq;
  char ctemp[80];

  nseq = 0;
  while((seq = read_a_sequence(fp, db_type, seq_type)) != NULL)
  {
    /*   Get rid of leading "P1;"    */
    if (strncmp(seq->name, "P1;", 3) == 0)
    {
        if ((int) strlen(seq->name) > XNAMELEN) seq->name[XNAMELEN] = '\0';
        strcpy(ctemp, seq->name);
        strcpy(seq->name, ctemp+3);
    }

    /*  Get rid of leading spaces */
    itemp = strspn(seq->name, " ");
    if (itemp > 0)
    {
      strcpy(ctemp, seq->name);
      strcpy(seq->name, ctemp+itemp);
    }

    if ((int) strlen(seq->name) > XNAMELEN)
        seq->name[XNAMELEN] = '\0';		/* ensure ony 20 characters long */

    /*  Get rid of leading spaces */
    itemp = strspn(seq->info, " ");
    if (itemp > 0)
    {
      strcpy(ctemp, seq->info);
      strcpy(seq->info, ctemp+itemp);
    }

    if (first_seq) {
      first_seq = FALSE;
      /* read the DE line stuff */
      if ((int)strlen(seq->info) <= (60-ACLEN)) {
	sprintf(DELine, "%s family", seq->info);
      }
      else {
	strncpy(Buffer, seq->info, 50);
	Buffer[50] = '\0';
	sprintf(DELine, "%s... family", Buffer);
      }
    }
    nseq++;

  /*  Check for duplicate sequence names here & append an error to
      stderr if not unique */
    if (SearchSL(Sequences, seq) != NULL) 
    {
     fprintf(WarnP, "Non-unique sequence name: %s\n", seq->name);
     fprintf(WarnP, "First 20 characters of sequence name must be unique.\n");
     if (strlen(seq->name) < XNAMELEN)  /*  Try using other info */
     { 
        strcpy(seq->name, seq->info);
        seq->name[XNAMELEN] = '\n';
        for (i=0; i< XNAMELEN; i++) if (seq->name[i] == ' ') seq->name[i] = '_';
     }
     i = strlen(seq->name);
     while (i >= 0 && SearchSL(Sequences, seq) != NULL) 
     {
        strcpy(ctemp, seq->name);
        ctemp[i] = '\0';
        sprintf(seq->name, "%s%d", ctemp, nseq);
        seq->name[XNAMELEN] = '\0';
        i--;
     }
     fprintf(WarnP, "Modified name to %s\n", seq->name);
    } /* end of non-unique name */

    edit_seq(seq);		/* Change gap characters, etc. */
    InsertSL(Sequences, seq);

  }  /* end of sequence file */
  return(nseq);
}  /*  end of read_seqs */
