File: chippart.c

package info (click to toggle)
chip-seq 1.5.5-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 21,320 kB
  • sloc: ansic: 10,053; perl: 1,493; makefile: 103; sh: 91
file content (712 lines) | stat: -rwxr-xr-x 21,257 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
/*
  chip_part.c

  Partitioning Tool.
  The program implements an algorithm for large-scale 
  Chip-Seq data sets. 
  It heuristically partitions the data by using a 
  two-way bisection of the ChIPseq count frequencies 
  or density over the genome. 
  
  # Arguments:
  # feature type, density threshold,
  # transition penalty, counts threshold

  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 DEBUG 
#define _GNU_SOURCE
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <ctype.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 FT_MAX  64
#define SEQ_ID  32
#define POS_MAX 16
#define CNT_MAX 16
#define EXT_MAX 256

typedef struct _options_t {
  int help;
  int debug;
} options_t;

static options_t options;

typedef struct _feature_t {
   char seq_id[SEQ_ID];
   char *ft;
   char ft_str;
   char **name;
   char *strand;
   int *pos;
   int *cnt;
   int *npo;
   int *nct;
} feature_t, *feature_p_t;

feature_t ref_ft;
int strand_flag = 0;

char *Feature = NULL;
float Dthres = 0;
int Tpen = 0;
int Coff = 1;

unsigned long TotLen = 0;
unsigned long TotCnts = 0;
int TotSeqs = 0;
int NumSegs = 0;
unsigned long TotFragLen = 0;
unsigned long AvFragLen = 0;
unsigned long AvCntsFrag = 0;
unsigned long TotCntsFrag = 0;


void 
split_seq(int len, int end, int last_seq)
{
  /* Partitioning Algorithm  */
  /* X(i) partitioning ends in over-representation state 
     Y(i) partitioning ends in under-representation state
     q(i) trace-back codes

     Recursion

      X(i) = max X(i-1) + cnt(i) - (pos(i)-pos(i-1))*Dthres,                     (XX)
                 Y(i-1) + Tpen + cnt(i) - Dthres + (pos(i)-pos(i-1)-1)*Dthres,   (YX)
		 X(i-1) + 2*Tpen + cnt(i) - Dthres + (pos(i)-pos(i-1)-2)*Dthres  (ZX)

      Y(i) = max X(i-1) + Tpen + (pos(i)-pos(i-1))*Dthres - cnt(i),              (XY)
                 Y(i-1) + (pos(i)-pos(i-1))*Dthres - cnt(i)                      (YY)
  */
  int i, j, k = 1;
  size_t mLen1 = BUF_SIZE;
  size_t mLen2 = BUF_SIZE;
  size_t mLen3 = BUF_SIZE;
  float Xmax = 0;
  float Ymax = 0;
  float XX, YX, ZX, YY, XY;
  int *q;
  int **Reg;
  int *cnt;
  int seq_len = 0;
  int tot_cnts = 0;

  if (( q = (int*)calloc(mLen1, sizeof(int))) == NULL) {
    perror("split_seq: malloc");
    exit(1);
  }
  if (( cnt = (int*)calloc(mLen2, sizeof(int))) == NULL) {
    perror("split_seq: malloc");
    exit(1);
  }
  if (( Reg = (int**)calloc((size_t)2, sizeof(int*))) == NULL) {
    perror("split_seq: malloc");
    exit(1);
  }
  for(i = 0; i < 2; i++) {
    Reg[i] = (int*)calloc(mLen3, sizeof(int));
  } 
  if (end == 0) { 
    ref_ft.pos[len + 1] = ref_ft.pos[len];
    ref_ft.name[len + 1] = ref_ft.name[len];
  } else 
    ref_ft.pos[len + 1] = end;

    ref_ft.cnt[len + 1] = 0;
    q[0] = 0;
  /* Fill in trace-back codes  q[i] */
  /* 
     0  Xmax = XX ; Ymax = YY
     1  Xmax = ZX ; Ymax = YY
     2  Xmax = YX ; Ymax = YY
     3  Xmax = XX ; Ymax = XY
     4  Xmax = ZX ; Ymax = XY
     5  Xmax = YX ; Ymax = XY
  */
  for (i = 1; i <= len + 1; i++) {
    XX = Xmax + ref_ft.cnt[i] - (ref_ft.pos[i] - ref_ft.pos[i - 1])*Dthres;
    YX = Ymax  + Tpen + ref_ft.cnt[i] - Dthres + (ref_ft.pos[i] - ref_ft.pos[i - 1] - 1)*Dthres;
    ZX = Xmax  + 2*Tpen + ref_ft.cnt[i] - Dthres + (ref_ft.pos[i] - ref_ft.pos[i - 1] - 1)*Dthres;
    YY = Ymax - ref_ft.cnt[i] + (ref_ft.pos[i] - ref_ft.pos[i - 1])*Dthres;
    XY = Xmax + Tpen - ref_ft.cnt[i] + (ref_ft.pos[i] - ref_ft.pos[i - 1])*Dthres;
    if ((unsigned int)i >= mLen1) {
      mLen1 *= 2;
      if (( q = (int *)realloc(q, mLen1 * sizeof(int))) == NULL) {
    	perror("split_seq: realloc");
    	exit(1);
      }
    }
    q[i] = 0;
    if ((YX < XX) && (ZX < XX)) { 
      Xmax = XX;
    } else if (YX < ZX) {
      Xmax = ZX;
      q[i] += 1;
    } else {
      Xmax = YX;
      q[i] += 2;
    }
    if (XY < YY) {
      Ymax = YY;
    } else {
      Ymax = XY;
      q[i] += 3;
    }
  }
  /* Trace-back */
  k = 1;
  if (Xmax > Ymax) {
    Reg[0][k] = 0;
    Reg[1][k] = ref_ft.pos[len + 1]; 
  } else {
    Reg[0][k] = 0;
    Reg[1][k] = 0; 
  }
  for (i = len + 1; i > 0; i--) {
    if (Reg[1][k] == 0) {
      if (q[i] > 2) 
        Reg[1][k] = ref_ft.pos[i - 1]; /* Enter a signal rich region 
					(we are in a poor region) */
    } else {
      if (q[i] > 2)
        q[i] -= 3;
      if ((unsigned int)k >= mLen2) {
        mLen2 *= 2;
        if ((cnt = (int*)realloc(cnt , mLen2 * sizeof(int))) == NULL) {
          perror("split_seq: realloc");
          exit(1);
        }
	memset((void *)&cnt[k], 0,  mLen2 * sizeof(int) / 2);
      }
      if (q[i] == 1) { /* Enter signal-rich region for the first time. 
      			We first close the previous one */
        Reg[0][k] = ref_ft.pos[i];
	cnt[k] += ref_ft.cnt[i];
	k++;
        if ((unsigned int)k >= mLen3) {
          mLen3 *= 2;
          for(j = 0; j < 2; j++) {
            if ((Reg[j] = (int*)realloc(Reg[j], mLen3 * sizeof(int))) == NULL) {
              perror("split_seq: realloc");
              exit(1);
	    }
          } 
        }
        Reg[0][k] = 0;
        Reg[1][k] = ref_ft.pos[i - 1];
      } else if (q[i] == 2) { /* We are at the end of a signal-rich region
      				 we are closing it, without creating a new one 
				(we're going into a signal-poor region) */
        Reg[0][k] = ref_ft.pos[i];
	cnt[k] += ref_ft.cnt[i];
	k++;
        if ((unsigned int)k >= mLen3) {
          mLen3 *= 2;
          for(j = 0; j < 2; j++) {
            if ((Reg[j] = (int*)realloc(Reg[j], mLen3 * sizeof(int))) == NULL) {
              perror("split_seq: realloc");
              exit(1);
	    }
          } 
        }
        Reg[0][k] = 0;
        Reg[1][k] = 0;
      } else { /* Extend signal-rich region */
        cnt[k] += ref_ft.cnt[i];
      }
    }
#ifdef DEBUG
    fprintf (stderr, "%d, %d, %d, %d, %d\n", i, k, Reg[0][k], Reg[1][k], cnt[k]);
#endif
  }
  /* Print out signal enriched regions */
  if (Reg[1][k] == 0) k--;
  if (Reg[0][k] == 0) Reg[0][k] = 1;
#ifdef DEBUG
  fprintf(stderr, "Printout number of Regions: k= %d\n", k);
#endif
  for (i = k; i >= 1; i--) {
    /* Print out (SGA format) */
    /* printf("%s\t%s\t%d\t%c\t%d\n", ref_ft.seq_id, ref_ft.name[i], Reg[0][i], '+', cnt[i]);
    printf("%s\t%s\t%d\t%c\t%d\n", ref_ft.seq_id, ref_ft.name[i], Reg[1][i], '-', cnt[i]);
    */
    printf("%s\t%s\t%d\t%c\t%d\n", ref_ft.seq_id, ref_ft.name[i], Reg[0][i], '+', cnt[i]);
    printf("%s\t%s\t%d\t%c\t%d\n", ref_ft.seq_id, ref_ft.name[i], Reg[1][i], '-', cnt[i]);
    seq_len += Reg[1][i] - Reg[0][i];
    tot_cnts += cnt[i];
  }
  if (end != 0)
    printf("%s\t%s\t%d\t%c\t%d\n", ref_ft.seq_id, ref_ft.name[len + 1], ref_ft.pos[len + 1], '0', 1);
  if (k && (len != 0)) {
    /*
    fprintf(stderr,"# %s :  Number of segments %d, Tot. length %d, Ave. length %d, Tot. counts %d\n", ref_ft.seq_id, k, seq_len, seq_len/k, tot_cnts); 
    */
    NumSegs += k;
    TotFragLen += seq_len;
    AvFragLen += seq_len/k;
    TotCntsFrag += tot_cnts;
    AvCntsFrag += tot_cnts/k;
  }
  if (last_seq) {
    fprintf(stderr,"# Num of Sequences : %d , Total Sequence Length : %lu (bp) , Total Counts : %lu , Total Num of Fragments : %d\n\n", TotSeqs, TotLen, TotCnts, NumSegs);
    fprintf(stderr,"# Total Fragment Length : %lu , Average Fragment Length : %lu (bp) , Percentage of Total Length : %2.5f\n\n", TotFragLen, AvFragLen/TotSeqs, (float)TotFragLen/(float)TotLen);
    fprintf(stderr,"# Percentage of Total Counts : %2.5f , Average Num of Counts per Fragment : %lu , Num of Counts per bp : %2.5f \n", (float)TotCntsFrag/(float)TotCnts, AvCntsFrag/TotSeqs, (float)TotCntsFrag/(float)TotFragLen);
  }
 
  free(q);
  free(cnt);
  for(j = 0; j < 2; j++) {
    if (Reg[j] != NULL)
      free(Reg[j]);
  } 
  free(Reg);
}

int
process_sga(FILE *input, char *iFile) 
{
  char seq_id_prev[SEQ_ID] = "";
  int pos, cnt, end = 0, last_pos = 0;
  size_t mLen = BUF_SIZE;
  char *s, *res, *buf;
  size_t bLen = LINE_SIZE;
  unsigned int k = 0;
  unsigned int i = 0;
  int end_flag = 0;

  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(mLen, sizeof(int))) == NULL) {
    perror("process_sga: malloc");
    exit(1);
  }
  if ((ref_ft.strand = (char*)calloc(mLen, sizeof(char))) == NULL) {
    perror("process_sga: malloc");
    exit(1);
  }
  if ((ref_ft.cnt = (int*)calloc(mLen, sizeof(int))) == NULL) {
    perror("process_sga: malloc");
    exit(1);
  }
  if ((ref_ft.name = (char**)calloc(mLen, sizeof(*(ref_ft.name)))) == NULL) {
    perror("process_sga: malloc");
    exit(1);
  }
  if ((s = malloc(bLen * sizeof(char))) == NULL) {
    perror("process_sga: malloc");
    exit(1);
  }
#ifdef DEBUG
  int c = 1; 
#endif
/*
  while (fscanf(f,"%s %s %d %c %d", seq_id, ft, &pos, &strand, &cnt) != EOF) {
  */
  while ((res = fgets(s, (int) bLen, input)) != NULL) {
    size_t cLen = strlen(s);
    char seq_id[SEQ_ID] = "";
    char ft[FT_MAX] = ""; 
    char position[POS_MAX] = ""; 
    char count[CNT_MAX] = ""; 
    char strand = '\0';
    char ext[EXT_MAX]; 
    unsigned int j = 0;

    memset(ext, 0, (size_t)EXT_MAX);
    while (cLen + 1 == bLen && s[cLen - 1] != '\n') {
      bLen *= 2;
      if ((s = realloc(s, bLen)) == NULL) {
        perror("process_file: realloc");
        exit(1);
      }
      res = fgets(s + cLen, (int) (bLen - 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 (j >= SEQ_ID) {
        fprintf(stderr, "Seq ID is too long \"%s\" \n", buf);
        exit(1);
      }
      seq_id[j++] = *buf++;
    }
    while (isspace(*buf))
      buf++;
    /* FEATURE */
    j = 0;
    while (*buf != 0 && !isspace(*buf)) {
      if (j >= FT_MAX) {
        fprintf(stderr, "Feature is too long \"%s\" \n", buf);
        exit(1);
      }
      ft[j++] = *buf++;
    }
    while (isspace(*buf))
      buf++;
    /* Position */
    j = 0;
    while (isdigit(*buf)) { 
      if (j >= POS_MAX) {
        fprintf(stderr, "Position is too large \"%s\" \n", buf);
        exit(1);
      }
      position[j++] = *buf++;
    }
    position[j] = 0;
    pos = atoi(position);
    while (isspace(*buf))
      buf++;
    /* Strand */
    strand = *buf++;
    while (isspace(*buf))
      buf++;
    /* Counts */
    j = 0;
    while (isdigit(*buf)) { 
      if (j >= CNT_MAX) {
        fprintf(stderr, "Count is too large \"%s\" \n", buf);
        exit(1);
      }
      count[j++] = *buf++;
    }
    count[j] = 0;
    cnt = atoi(count);
    while (isspace(*buf))
      buf++;
    /* SGA Extension */
    j = 0;
    while (*buf != 0) {
      if (j >= EXT_MAX) {
        fprintf(stderr, "Extension is too long \"%s\" \n", buf);
        exit(1);
      }
      ext[j++] = *buf++;
    }
#ifdef DEBUG
    printf(" [%d] seq ID: %s   Feat: %s (%c)  Pos: %d  Cnts: %d Ext: %s\n", c++, seq_id, ft, strand, pos, cnt, ext);
#endif
    if (k >= mLen - 1) {
      mLen *= 2;
#ifdef DEBUG
      fprintf(stderr, "reallocating memory for ref_ft.pos ref_ft.strand ref_ft.cnt (k=%d, size=%d)\n", c, mLen);
#endif
      if ((ref_ft.pos = (int *)realloc(ref_ft.pos, mLen * sizeof(int))) == NULL) {
    	perror("process_sga: realloc");
    	exit(1);
      }
      if ((ref_ft.cnt = (int *)realloc(ref_ft.cnt, mLen * sizeof(int))) == NULL) {
    	perror("process_sga: realloc");
    	exit(1);
      }
      if ((ref_ft.strand = (char *)realloc(ref_ft.strand, mLen * sizeof(char))) == NULL) {
    	perror("process_sga: realloc");
    	exit(1);
      }
      if ((ref_ft.name = (char**)realloc(ref_ft.name, mLen * sizeof(*(ref_ft.name)))) == NULL) {
        perror("process_sga: malloc");
        exit(1);
      }
    }
    /* Check Chromosome BEGINNING, split sequences in regions and printout results*/
    if (strcmp(seq_id, seq_id_prev) != 0) {
      split_seq((int)k, end, 0); 
      for (i = 1; i <= k; i++) { 
	if (ref_ft.name[i] != NULL)
          free(ref_ft.name[i]);
      }
      if (end_flag) {
	if (ref_ft.name[k + 1] != NULL)
          free(ref_ft.name[k + 1]);
      }
      k = 0;
      end = 0;
      end_flag = 0;
      TotLen += last_pos;
      TotSeqs ++;
      ref_ft.pos[0] = 1;
      ref_ft.cnt[0] = 0;
      strcpy(seq_id_prev, seq_id);
      strcpy(ref_ft.seq_id, seq_id);
    }
    if (ref_ft.ft == NULL) {
      k++;
      ref_ft.name[k] = malloc(strlen(ft) + 1);
      strcpy(ref_ft.name[k], ft);
      ref_ft.strand[k] = strand;
      ref_ft.pos[k] = pos;
      if (cnt > Coff)
          ref_ft.cnt[k] = Coff;
      else
          ref_ft.cnt[k] = cnt;
      TotCnts += ref_ft.cnt[k];
    } else if (ref_ft.ft_str == '\0') {
      if (strcmp(ft, ref_ft.ft) == 0) {
        k++;
        ref_ft.name[k] = malloc(strlen(ft) + 1);
        strcpy(ref_ft.name[k], ft);
        ref_ft.strand[k] = strand;
        ref_ft.pos[k] = pos;
	if (cnt > Coff)
          ref_ft.cnt[k] = Coff;
        else
          ref_ft.cnt[k] = cnt;
      TotCnts += ref_ft.cnt[k];
      }
    } else if (strand_flag == 1) {
      if (strand == ref_ft.ft_str) {
        k++;
        ref_ft.name[k] = malloc(strlen(ft) + 1);
        strcpy(ref_ft.name[k], ft);
        ref_ft.strand[k] = strand;
        ref_ft.pos[k] = pos;
	if (cnt > Coff)
          ref_ft.cnt[k] = Coff;
        else
          ref_ft.cnt[k] = cnt;
      TotCnts += ref_ft.cnt[k];
      }
    } else if (strcmp(ft, ref_ft.ft) == 0  && strand == ref_ft.ft_str) {
        k++;
        ref_ft.name[k] = malloc(strlen(ft) + 1);
        strcpy(ref_ft.name[k], ft);
        ref_ft.strand[k] = strand;
        ref_ft.pos[k] = pos;
	if (cnt > Coff)
          ref_ft.cnt[k] = Coff;
        else
          ref_ft.cnt[k] = cnt;
      TotCnts += ref_ft.cnt[k];
    } 
    if (strcmp(ft, "END") == 0 ) {
        ref_ft.name[k + 1] = malloc(strlen(ft) + 1);
        strcpy(ref_ft.name[k + 1], ft);
        end = pos;
        end_flag = 1;
    }
    last_pos = pos;
#ifdef DEBUG
    fprintf(stderr,"k = [%d]   pos = %d cnts = %d\n", k, ref_ft.pos[k], ref_ft.cnt[k]);
#endif
  } /* End of While */
  free(s);
  /* Partition last chromosome */ 
  TotLen += last_pos;
  split_seq((int)k, end, 1); 
  for (i = 1; i <= k; i++) { 
    if (ref_ft.name[i] != NULL)
      free(ref_ft.name[i]);
  }
  if (end_flag) {
    if (ref_ft.name[k + 1] != NULL)
      free(ref_ft.name[k + 1]);
  }
  free(ref_ft.name);
  free(ref_ft.pos);
  free(ref_ft.cnt);
  free(ref_ft.strand);
  if (input != stdin) {
    fclose(input);
  }
  return 0;
}

int
main(int argc, char *argv[])
{
#ifdef DEBUG
  mcheck(NULL);
  mtrace();
#endif
  FILE *input;

  while (1) {
    int c = getopt(argc, argv, "f:dhs:p:c:");
    if (c == -1)
      break;
    switch (c) {
      case 'f':
        Feature = optarg;
        break;
      case 'd':
        options.debug = 1;
        break;
      case 'h':
        options.help = 1;
        break;
    case 's':
        Dthres = atof(optarg);
	break;
    case 'p':
        Tpen = atoi(optarg);
	break;
    case 'c':
        Coff = atoi(optarg);
	break;
      default:
        printf ("?? getopt returned character code 0%o ??\n", c);
    }
  }
  if (optind > argc || options.help == 1 || Dthres == 0 || Tpen == 0 || Coff < 0) {
    fprintf(stderr, "Usage: %s [options] [-f <feature>] -s <densitiy threshold> -p <transition penalty> [<] <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 -c     Count Cut-off (default is %d). It must be >= 0.\n"
	     "\n\tPartitioning Tool.\n"
	     "\n\tThe program reads a ChIP-seq data file (or from stdin [<]) in SGA format (<SGA file>),\n"
	     "\tand heuristically partitions the data corresponding to a specific feature\n"
	     "\t<feature>, if the latter is given.\n"
	     "\tThe <feature> parameter is a name that corresponds to the second field of the SGA file.\n"
	     "\tIt might optionally include the strand specification (+|-).\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"
	     "\tInput parameters are the density threshold (<density threshold>),\n"
	     "\tthe transition penalty (<transition penalty>), which are used to\n"
             "\tsplit the data in regions of high density count.\n" 
	     "\tA value can be optionally specified as a cut-off for the feature counts.\n"
             "\tThe output is an SGA-formatted list containing the regions of interest.\n"
             "\tThe program also generates (to stderr) a statistical report with the\n"
             "\tfollowing information:\n"
	     "\t  - Total number of processed sequences, total DNA length, and\n" 
	     "\t    total number of fragments;\n"
	     "\t  - Total length of fragments, average fragment length, and\n"
	     "\t    percentage of total DNA length;\n"
             "\t  - Percentage of total counts, average number of counts, and\n"
	     "\t    number of count per bp (count density).\n\n",
	     argv[0], VERSION, Coff);
      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, " Selected Feature : %s\n", Feature);
    fprintf(stderr, " Density Threshold : %f\n\n", Dthres);
    fprintf(stderr, " Transition Penalty : %d\n\n", Tpen);
    fprintf(stderr, " Count Cut-off : %d\n\n", Coff);
  }
  /* Process Feature Specs */
  if (Feature == NULL) {
    ref_ft.ft = NULL;      /* Process all features */
    ref_ft.ft_str = '\0';
  } else {
    ref_ft.ft = malloc(FT_MAX * sizeof(char));
    char *s = Feature;
    int i = 0;
    while (*s != 0  && !isspace(*s)) {
      if (i >= FT_MAX) {
        fprintf(stderr, "Feature Description too long \"%s\" \n", Feature);
        return 1;
      }
      ref_ft.ft[i++] = *s++;
    }
    ref_ft.ft[i] = '\0';
    ref_ft.ft_str = '\0';
    while (isspace(*s++))
    ref_ft.ft_str = *s;
  }
  if (options.debug) {
    if (ref_ft.ft_str == '\0' && ref_ft.ft == NULL) {
      fprintf(stderr, "Feature Specs: ALL -> Process all features\n");
    } else if (ref_ft.ft_str == '\0') {
      fprintf(stderr, "Feature Specs: Feature name : %s\n", ref_ft.ft);
    } else {
      fprintf(stderr, "Feature Specs: Feature name/str : %s %c\n", ref_ft.ft, ref_ft.ft_str);
    }
  }
  if ( ref_ft.ft != NULL && (strcmp(ref_ft.ft, "+") == 0 || strcmp(ref_ft.ft, "-") == 0)) {
    strcpy(&ref_ft.ft_str, ref_ft.ft);
    strand_flag = 1;
    if (options.debug)
      fprintf(stderr, "Feature Specs: Process all features on str : %c\n", ref_ft.ft_str);
  }
  if (process_sga(input, argv[optind++]) != 0) {
    return 1;
  }
  free(ref_ft.ft);
  return 0;
}