/*
  chip_score.c

  Feature extraction Tool.
  The program compares two features, reference and target,
  and extracts those reference tags that are enriched or 
  depleted in the target feature
  
  # Arguments:
  # feature_1 type, feature_1 strand, feature_2 type, feature_2 strand,
  # beginning of range, end of range, output Threshold 
  # count cut-off value

  Giovanna Ambrosini, EPFL, Giovanna.Ambrosini@epfl.ch

  Copyright (c) 2014 EPFL and Swiss Institute of Bioinformatics.

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/
#define _GNU_SOURCE
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <ctype.h>
#include <math.h>
#include <sys/stat.h>
#ifdef DEBUG
#include <mcheck.h>
#endif

#include "version.h"

/*#define BUF_SIZE 4096 */
#define BUF_SIZE 8192
#define LINE_SIZE 1024
#define FT_MAX  64
#define SEQ_ID  32
#define POS_MAX 16
#define CNT_MAX 16
#define EXT_MAX 256

typedef struct _options_t {
  int cutOff;
  int report;
  int help;
  int debug;
  int oriented;
  int reverse;
} options_t;

static options_t options;

typedef struct _feature_t {
   char seq_id[SEQ_ID];
   char ft[FT_MAX];
   char strand;
   int  *pos;
   int  *cnt;
   int  *ptr;
   char *str;
   char **ext;
} feature_t, *feature_p_t;

feature_t ref_ft;
feature_t tar_ft;

char *RefFeature = NULL;
char *TarFeature = NULL;

int From = 0;
int To = 0;
int Tmp = 0;

int Thres = 0;

int Rtot = 0;      /* Total Reference Counts      */
int Ttot = 0;      /* Total Target Counts         */

unsigned long Len  = 0;      /* Total Sequence Length       */

int ref_specs = 1; /* if = 1 feature specs : <name> AND <strand> */
int tar_specs = 1;
int no_tar_ft = 0;

int or_same_strand = 0;
int or_opposite_strand = 0;
int or_any_strand = 0;


void
score_update(unsigned int ft_nb, unsigned int tar_nb)
{
  int j, k;
  unsigned long long sum = 0;
  char B_score[128];
#ifdef DEBUG
  printf(" score_update: nb of ref features : %d\n", ft_nb);
#endif
  for (j = 1; j <= (int)ft_nb; j++) {
    sum = 0;
    k = ref_ft.ptr[j];
    if (!options.oriented || (ref_ft.str[j] == '+')) { /* Ref Feat Un-oriented or
                                                          Oriented on Pos Strand 
                                                          Examin Upstream Tar pos */
      while (tar_ft.pos[k] > ref_ft.pos[j] + To) {k--;}
      while ((k >= 0) && (tar_ft.pos[k] >= ref_ft.pos[j] + From)) {
        if (!options.oriented || (or_same_strand && tar_ft.str[k] == '+') || (or_opposite_strand && tar_ft.str[k] == '-') || or_any_strand) {
          sum += tar_ft.cnt[k];
        }
#ifdef DEBUG
        printf(" score_update : Sum = %llu Tar Cnts = %d\n", sum, tar_ft.cnt[k]);
#endif
        k--; /* examine further upstream positions within the window range */
      }
    } else { /* Reverse Loop - Ref Feature Oriented on Neg Strand (Examin Upstream Tar pos) */
      while (tar_ft.pos[k] > ref_ft.pos[j] - From) {k--;}
      while ((k >= 0) && (tar_ft.pos[k] >= ref_ft.pos[j] - To)) {
        if ((or_same_strand && tar_ft.str[k] == '-') || (or_opposite_strand && tar_ft.str[k] == '+') || or_any_strand) {
          sum += tar_ft.cnt[k];
        }
        k--; /* examine further upstream positions within the window range */
      }
    }
    k = ref_ft.ptr[j] + 1;
    if (!options.oriented || (ref_ft.str[j] == '+')) { /* Ref Feat Un-oriented or Oriented on Pos Strand (Examin Downstream Tar pos) */
      while ((tar_ft.pos[k] < ref_ft.pos[j] + From)  && k <= (int)tar_nb) {k++;}
      while ((tar_ft.pos[k] <= ref_ft.pos[j] + To) && k <= (int)tar_nb) {
        if (!options.oriented || (or_same_strand && tar_ft.str[k] == '+') || (or_opposite_strand && tar_ft.str[k] == '-') || or_any_strand) {
          sum += tar_ft.cnt[k];
        }
#ifdef DEBUG
        printf(" score_update : Sum = %llu Tar Cnts = %d\n", sum, tar_ft.cnt[k]);
#endif
        k++; /* examine further downstream positions within the window range */
      }
    } else { /* Reverse Loop - Ref Feature Oriented on Neg Strand (Examin Downstream Tar pos) */
      while ((tar_ft.pos[k] < ref_ft.pos[j] - To) && k <= (int)tar_nb) {k++;}
      while ((tar_ft.pos[k] <= ref_ft.pos[j] - From) && k <= (int)tar_nb) {
        if ((or_same_strand && tar_ft.str[k] == '-') || (or_opposite_strand && tar_ft.str[k] == '+') || or_any_strand) {
          sum += tar_ft.cnt[k];
        }
        k++; /* examine further downstream positions within the window range */
      }
    }
    if (options.reverse) {
      if ( sum < (unsigned long long)Thres) {
        if (options.report) {
          sprintf(B_score," %s=%llu", tar_ft.ft, sum);
        } else {
          sprintf(B_score," %llu", sum);
        }
        if (ref_ft.ext[j] != NULL) {
          printf("%s\t%s\t%d\t%c\t%d\t%s\t%s\n", ref_ft.seq_id, ref_ft.ft, ref_ft.pos[j], ref_ft.str[j], ref_ft.cnt[j], ref_ft.ext[j], B_score); 
        } else {
          printf("%s\t%s\t%d\t%c\t%d\t%s\n", ref_ft.seq_id, ref_ft.ft, ref_ft.pos[j], ref_ft.str[j], ref_ft.cnt[j], B_score); 
        }
      }
    } else {
      if ( sum >= (unsigned long long)Thres) {
        if (options.report) {
          sprintf(B_score," %s=%llu", tar_ft.ft, sum);
        } else {
          sprintf(B_score," %llu", sum);
        }
        if (ref_ft.ext[j] != NULL) {
          printf("%s\t%s\t%d\t%c\t%d\t%s\t%s\n", ref_ft.seq_id, ref_ft.ft, ref_ft.pos[j], ref_ft.str[j], ref_ft.cnt[j], ref_ft.ext[j], B_score); 
        } else {
          printf("%s\t%s\t%d\t%c\t%d\t%s\n", ref_ft.seq_id, ref_ft.ft, ref_ft.pos[j], ref_ft.str[j], ref_ft.cnt[j], B_score); 
        }
      }
    }
  } /* Loop over Reference positions (j) */

  return;
}

int
process_sga(FILE *input, char *iFile) 
{
  unsigned int l = 0;
  unsigned int m = 0;
  unsigned int k = 0;
  unsigned int j = 0;
  char seq_id_prev[SEQ_ID] = "";
  int pos, cnt, last_pos = 0;
  char *s, *res, *buf;
  size_t rf_mLen = BUF_SIZE;
  size_t tf_mLen = BUF_SIZE;
  size_t mLen = LINE_SIZE;

  if (options.debug && input != stdin) {
    char sort_cmd[1024] = "sort -s -c -k1,1 -k3,3n ";
    fprintf(stderr, "Check whether file %s is properly sorted\n", iFile);
    if (strcat(sort_cmd, iFile) == NULL) {
      fprintf(stderr, "strcat failed\n");
      return 1;
    }
    if (strcat(sort_cmd, " 2>/tmp/sortcheck.out") == NULL) {
      fprintf(stderr, "strcat failed\n");
      return 1;
    }
    fprintf(stderr, "executing : %s\n", sort_cmd);
    int sys_code = system(sort_cmd);
    /*fprintf(stderr,"system command sort : return code %d\n", sys_code);*/
    if (sys_code != 0) {
      fprintf(stderr, "system command failed\n");
      return 1;
    }
    struct stat file_status;
    if(stat("/tmp/sortcheck.out", &file_status) != 0){
      fprintf(stderr, "could not stat\n");
      return 1;
    }
    if (file_status.st_size != 0) {
      fprintf(stderr, "SGA file %s is not properly sorted\n", iFile);
      return 1;
    } else {
      system("/bin/rm /tmp/sortcheck.out");
    }
  }
  if ((ref_ft.pos = (int *)calloc(rf_mLen, sizeof(int))) == NULL) {
    perror("process_sga: malloc");
    exit(1);
  }
  if ((ref_ft.cnt = (int *)calloc(rf_mLen, sizeof(int))) == NULL) {
    perror("process_sga: malloc");
    exit(1);
  }
  if ((ref_ft.ptr = (int *)calloc(rf_mLen, sizeof(int))) == NULL) {
    perror("process_sga: malloc");
    exit(1);
  }
  if ((ref_ft.str = (char *)calloc(rf_mLen, sizeof(char))) == NULL) {
    perror("process_sga: malloc");
    exit(1);
  }
  if ((ref_ft.ext = (char**)calloc(rf_mLen, sizeof(*(ref_ft.ext)))) == NULL) {
    perror("process_sga: malloc");
    exit(1);
  }
  if ((tar_ft.pos = (int *)calloc(tf_mLen, sizeof(int))) == NULL) {
    perror("process_sga: malloc");
    exit(1);
  }
  if ((tar_ft.cnt = (int *)calloc(tf_mLen, sizeof(int))) == NULL) {
    perror("process_sga: malloc");
    exit(1);
  }
  if ((tar_ft.str = (char *)calloc(tf_mLen, sizeof(char))) == NULL) {
    perror("process_sga: malloc");
    exit(1);
  }
  if ((s = malloc(mLen * sizeof(char))) == NULL) {
    perror("process_sga: malloc");
    exit(1);
  }

  tar_ft.pos[0] = From - 1;
  if (options.debug)
    fprintf(stderr, "Processing file %s\n", iFile);
#ifdef DEBUG
  int c = 1; 
#endif
  /* while (fscanf(f,"%s %s %d %c %d %*s", seq_id, feature, &pos, &strand, &cnt) != EOF) { */
  while ((res = fgets(s, (int) mLen, input)) != NULL) {
    size_t cLen = strlen(s);
    char seq_id[SEQ_ID] = "";
    char feature[FT_MAX] = ""; 
    char position[POS_MAX] = ""; 
    char count[CNT_MAX] = ""; 
    char strand = '\0';
    char ext[EXT_MAX]; 
    unsigned int i = 0;

    memset(ext, 0, (size_t)EXT_MAX);
    while (cLen + 1 == mLen && s[cLen - 1] != '\n') {
      mLen *= 2;
      if ((s = realloc(s, mLen)) == NULL) {
        perror("process_file: realloc");
        exit(1);
      }
      res = fgets(s + cLen, (int) (mLen - cLen), input);
      cLen = strlen(s);
    }
    if (s[cLen - 1] == '\n')
      s[cLen - 1] = 0;

    buf = s;
    /* Get SGA fields */
    /* SEQ ID */
    while (*buf != 0 && !isspace(*buf)) {
      if (i >= SEQ_ID) {
        fprintf(stderr, "Seq ID is too long \"%s\" \n", buf);
        exit(1);
      }
      seq_id[i++] = *buf++;
    }
    while (isspace(*buf))
      buf++;
    /* FEATURE */
    i = 0;
    while (*buf != 0 && !isspace(*buf)) {
      if (i >= FT_MAX) {
        fprintf(stderr, "Feature is too long \"%s\" \n", buf);
        exit(1);
      }
      feature[i++] = *buf++;
    }
    while (isspace(*buf))
      buf++;
    /* Position */
    i = 0;
    while (isdigit(*buf)) { 
      if (i >= POS_MAX) {
        fprintf(stderr, "Position is too large \"%s\" \n", buf);
        exit(1);
      }
      position[i++] = *buf++;
    }
    position[i] = 0;
    pos = atoi(position);
    while (isspace(*buf))
      buf++;
    /* Strand */
    strand = *buf++;
    while (isspace(*buf))
      buf++;
    /* Counts */
    i = 0;
    while (isdigit(*buf)) { 
      if (i >= CNT_MAX) {
        fprintf(stderr, "Count is too large \"%s\" \n", buf);
        exit(1);
      }
      count[i++] = *buf++;
    }
    count[i] = 0;
    cnt = atoi(count);
    while (isspace(*buf))
      buf++;
    /* SGA Extension */
    i = 0;
    while (*buf != 0) {
      if (i >= EXT_MAX) {
        fprintf(stderr, "Extension is too long \"%s\" \n", buf);
        exit(1);
      }
      ext[i++] = *buf++;
    }
    ext[i] = 0;
#ifdef DEBUG
    printf(" [%d] seq ID: %s   Feat: %s%c  Pos: %d  Cnts: %d Ext: %s\n", c++, seq_id, feature, strand, pos, cnt, ext);
#endif

    if (j >= rf_mLen - 1) {
      rf_mLen *= 2;
      if ((ref_ft.pos = (int *)realloc(ref_ft.pos, rf_mLen * sizeof(int))) == NULL) {
        perror("process_sga: realloc");
        exit(1);
      }
      if ((ref_ft.cnt = (int *)realloc(ref_ft.cnt, rf_mLen * sizeof(int))) == NULL) {
        perror("process_sga: realloc");
        exit(1);
      }
      if ((ref_ft.ptr = (int *)realloc(ref_ft.ptr, rf_mLen * sizeof(int))) == NULL) {
        perror("process_sga: realloc");
        exit(1);
      }
      if ((ref_ft.str = (char *)realloc(ref_ft.str, rf_mLen * sizeof(char))) == NULL) {
        perror("process_sga: realloc");
        exit(1);
      }
      if ((ref_ft.ext = (char**)realloc(ref_ft.ext, rf_mLen * sizeof(*(ref_ft.ext)))) == NULL) {
        perror("process_sga: realloc");
	exit(1);
      }
    }
    if (k >= tf_mLen - 1) {
      tf_mLen *= 2;
      if ((tar_ft.pos = (int *)realloc(tar_ft.pos, tf_mLen * sizeof(int))) == NULL) {
        perror("process_sga: realloc");
        exit(1);
      }
      if ((tar_ft.cnt = (int *)realloc(tar_ft.cnt, tf_mLen * sizeof(int))) == NULL) {
        perror("process_sga: realloc");
        exit(1);
      }
      if ((tar_ft.str = (char *)realloc(tar_ft.str, tf_mLen * sizeof(char))) == NULL) {
        perror("process_sga: realloc");
        exit(1);
      }
    }
    if (strcmp(seq_id, seq_id_prev) != 0) {
      l = j;
      tar_ft.pos[k + 1] = ref_ft.pos[l] + To + 1;
      m = k + 1;
      score_update(l, m);
      strcpy(seq_id_prev, seq_id);
      for (unsigned int i = 1; i <= j; i++) {
        if (ref_ft.ext[i] != NULL)
          free(ref_ft.ext[i]);
      }
      j = 0;
      k = 0;
      Len += last_pos;
    }
    if (ref_specs) {
      if (strcmp(feature, ref_ft.ft) == 0 && strand == ref_ft.strand) {
        j++;
	strcpy(ref_ft.seq_id, seq_id);
        ref_ft.pos[j] = pos;
        ref_ft.str[j] = strand;
        ref_ft.ptr[j] = k;
        if (cnt > options.cutOff)
          ref_ft.cnt[j] = options.cutOff;
        else
          ref_ft.cnt[j] = cnt;
        if (ext[0] == 0) {
          ref_ft.ext[j] = NULL;
        } else {
	  ref_ft.ext[j] = (char *)malloc(strlen(ext) + 1);
	  strcpy(ref_ft.ext[j], ext);
        }
	Rtot += ref_ft.cnt[j];
      }
    } else {
      if (strcmp(feature, ref_ft.ft) == 0) {
        j++;
	strcpy(ref_ft.seq_id, seq_id);
        ref_ft.pos[j] = pos;
        ref_ft.str[j] = strand;
        ref_ft.ptr[j] = k;
        if (cnt > options.cutOff)
          ref_ft.cnt[j] = options.cutOff;
        else
          ref_ft.cnt[j] = cnt;
        if (ext[0] == 0) {
          ref_ft.ext[j] = NULL;
        } else {
	  ref_ft.ext[j] = (char *)malloc(strlen(ext) + 1);
	  strcpy(ref_ft.ext[j], ext);
        }
	Rtot += ref_ft.cnt[j];
      }
    }
    if (tar_specs) { 
      if (strcmp(feature, tar_ft.ft) == 0 && strand == tar_ft.strand) {
        k++;
        tar_ft.pos[k] = pos;
        tar_ft.str[k] = strand;
        if (cnt > options.cutOff)
          tar_ft.cnt[k] = options.cutOff;
        else
          tar_ft.cnt[k] = cnt;
	Ttot += tar_ft.cnt[k];
      }
    } else if (strcmp(feature, tar_ft.ft) == 0) {
        k++;
        tar_ft.pos[k] = pos;
        tar_ft.str[k] = strand;
        if (cnt > options.cutOff)
          tar_ft.cnt[k] = options.cutOff;
        else
          tar_ft.cnt[k] = cnt;
	Ttot += tar_ft.cnt[k];
    } else if (no_tar_ft) {
      if (strcmp(feature, ref_ft.ft) != 0) {
        k++;
        tar_ft.pos[k] = pos;
        tar_ft.str[k] = strand;
        if (cnt > options.cutOff)
          tar_ft.cnt[k] = options.cutOff;
        else
          tar_ft.cnt[k] = cnt;
	Ttot += tar_ft.cnt[k];
      }
    }
    last_pos = pos;
  } /* End of While */
  free(s);
  /* The last time (at EOF) */
  if (input != stdin) {
    fclose(input);
  }
  Len += last_pos;
  l = j;
  tar_ft.pos[k + 1] = ref_ft.pos[l] + To + 1;
  m = k + 1;
  score_update(l, m);
  fprintf(stderr,"#  Total Sequence Len : %lu , Total Reference Counts : %d , Total Target Counts : %d\n", Len, Rtot, Ttot);
  for (unsigned int i = 1; i <= j; i++) {
    free(ref_ft.ext[i]);
  }
  free(ref_ft.pos);
  free(ref_ft.cnt);
  free(ref_ft.str);
  free(ref_ft.ptr);
  free(ref_ft.ext);
  free(tar_ft.pos);
  free(tar_ft.cnt);
  free(tar_ft.str);
  return 0;
}

int
main(int argc, char *argv[])
{
#ifdef DEBUG
  mcheck(NULL);
  mtrace();
#endif
  FILE *input;
  options.cutOff = 9999;
  options.report = 0;
  options.reverse = 0;
  int i = 0;

  while (1) {
    int c = getopt(argc, argv, "c:qdhorA:B:b:e:t:");
    if (c == -1)
      break;
    switch (c) {
      case 'c':
        options.cutOff = atoi(optarg);
        break;
      case 'd':
        options.debug = 1;
        break;
      case 'h':
        options.help = 1;
        break;
      case 'A':
        RefFeature = optarg;
	break;
      case 'B':
        TarFeature = optarg;
	break;
      case 'b':
        From =  atoi(optarg);
	break;
      case 'e':
        To =  atoi(optarg);
	break;
      case 'o':
        options.oriented = 1;
        break;
      case 'q':
        options.report = 1;
        break;
      case 'r':
        options.reverse = 1;
        break;
      case 't':
        Thres =  atoi(optarg);
	break;
      default:
        printf ("?? getopt returned character code 0%o ??\n", c);
    }
  }
  if (optind > argc || options.help == 1 || RefFeature == NULL  || TarFeature == NULL || From > To || options.cutOff < 0) {
     fprintf(stderr, "Usage: %s [options] -A <feature A> -B <feature B> -b<from> -e<to> [-t <thres>] [<] <SGA file>\n"
         "      - version %s\n"
         "      where options are:\n"
         "  \t\t -h     Show this help text\n"
         "  \t\t -d     Print debug information and check SGA file\n"
         "  \t\t -o     Oriented strand processing\n"
         "  \t\t -r     Reverse extraction process\n"
         "  \t\t -c     Cut-Off value for feature counts (default is %d)\n"
         "  \t\t -q     Report feature B tag counts as 'feature_name=<int>'\n"
	 "\n\tFeature Extraction Tool for ChIP-seq data analysis.\n"  
         "\tThe program reads a ChIP-seq data file (or from stdin [<]) in SGA format (<SGA file>),\n"
         "\tand compares two features, a reference feature (<feature A>) and a target feature\n"         
	 "\t(<feature B>), with respect to their relative position.\n"
	 "\tBy default, the program extracts feature A tags that are enriched in feature B\n"
	 "\ttags according to a given count output threshold or score(<thres>) that is %d by default.\n"
	 "\tIf option -r is specified, the program extracts sites that are depleted in feature B.\n"
         "\tThe feature specification must have the following format:\n"
         "      \t<feature> = <name> [<+|->]\n\n"
	 "\tthe strand specification being optional.\n"
	 "\tThe <feature> parameter is a name that corresponds to the second field of the SGA file.\n"
	 "\tIf no feature is given then all input tags are processed.\n"
	 "\tThe SGA input file MUST BE sorted by sequence name (or chromosome id), position,\n"
	 "\tand strand.\n"
	 "\tOne should check the input SGA file with the following command:\n"
	 "\tsort -s -c -k1,1 -k3,3n -k4,4 <SGA file>.\n\n"
	 "\tIn debug mode (-d), the program performs the sorting order check.\n\n"
         "\tThe relative distance between the two features is analysed within a\n"
	 "\tgiven range: <from>-<to>.\n"
	 "\tA value can be optionally specified as a cut-off for the feature counts.\n\n",
              argv[0], VERSION, options.cutOff, Thres);
      return 1;
  }
  if (argc > optind) {
      if(!strcmp(argv[optind],"-")) {
          input = stdin;
      } else {
          input = fopen(argv[optind], "r");
          if (NULL == input) {
              fprintf(stderr, "Unable to open '%s': %s(%d)\n",
                  argv[optind], strerror(errno), errno);
             exit(EXIT_FAILURE);
          }
          if (options.debug)
             fprintf(stderr, "Processing file %s\n", argv[optind]);
      }
  } else {
      input = stdin;
  }
  if (options.debug) {
    fprintf(stderr, " Arguments:\n");
    fprintf(stderr, " Feature A (ref): %s\n", RefFeature);
    fprintf(stderr, " Feature B (tar): %s\n", TarFeature);
    fprintf(stderr, " Range : [%d, %d]\n", From, To);
    fprintf(stderr, " Cut-off : %d\n", options.cutOff);
    fprintf(stderr, " Output Threshold : %d\n\n", Thres);
    fprintf(stderr, " Feature B tag count report : %d (1:ON, 0:OFF)\n", options.report);
  }
  char *s = RefFeature;
  i = 0;
  while (*s != 0  && !isspace(*s)) {
    if (i >= FT_MAX) {
      fprintf(stderr, "Feature Description too long \"%s\" \n", RefFeature);
      return 1;
    }
    ref_ft.ft[i++] = *s++;
  }
  ref_ft.strand = '\0';
  if (!options.oriented) {
    while (isspace(*s++))
    ref_ft.strand = *s;
  }
  s = TarFeature;
  i = 0;
  while (*s != 0  && !isspace(*s)) {
    if (i >= FT_MAX) {
      fprintf(stderr, " Feature Description too long \"%s\" \n", TarFeature);
      return 1;
    }
    tar_ft.ft[i++] = *s++;
  }
  tar_ft.strand = '\0';
  while (isspace(*s++))
  tar_ft.strand = *s;
  if (options.debug)
    fprintf(stderr, " Ref feature : %s %c (R)\n Tar Feature: %s %c (T)\n", ref_ft.ft, ref_ft.strand, tar_ft.ft, tar_ft.strand);
  size_t cLen = strlen(ref_ft.ft);
  if (!cLen) {
      fprintf(stderr, " Wrong Reference Feature Description (ref) \"%s\". You must at least provide a name for your Ref Feature!\n Feature Specs Format: = <feature desc> [<strand(+|-)>]\n", RefFeature);
      return 1;
  }
  cLen = strlen(tar_ft.ft);
  if (!cLen) {
      fprintf(stderr, " No Target Feature Description (tar) has been provided. Define Feature B name as 'score'\n");
      strcpy(tar_ft.ft, "score");
      no_tar_ft = 1;
  }
  if (ref_ft.strand == '\0') {
      /* fprintf(stderr, " Warning Ref Feature \"%s\" !\n Feature Format: = <feature desc> [<strand(+|-)>]\n", RefFeature); */
      ref_specs = 0;
  }
  if (tar_ft.strand == '\0') {
      /* fprintf(stderr, " Warning Tar Feature \"%s\" !\n Feature Format: = <feature desc> [<strand(+|-)>]\n", TarFeature); */
      tar_specs = 0;
  }
  if ((strcmp(tar_ft.ft, ref_ft.ft) == 0)) { /* Check For Auto-Correlation */
    if (ref_ft.strand == '\0' && tar_ft.strand == '\0') {
        fprintf(stderr, " Autocorrelation: Reference and Target Feature are the same!\n");
        return 1;
    } else if ((ref_ft.strand == '+' && tar_ft.strand == '+') || (ref_ft.strand == '-' && tar_ft.strand == '-')) {
        fprintf(stderr, " Autocorrelation: Reference and Target Feature are the same!\n");
        return 1;
    }
  }
  if (options.oriented) {
    if (tar_ft.strand == '+') {
      or_same_strand = 1;
    } else if (tar_ft.strand == '-') {
      or_opposite_strand = 1;
    } else {
      or_any_strand = 1;
    }
    tar_specs = 0;
  }
  if (process_sga(input, argv[optind++]) != 0) {
    return 1;
  }
  return 0;
}
