lucy.c 32.5 KB
Newer Older
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 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
/****************************************************************************
*
* Copyright (c) 2003, The Institute for Genomic Research (TIGR), Rockville,
* Maryland, U.S.A.  All rights reserved.
*
****************************************************************************/

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <pthread.h>

#define TABLE_LENGTH 1023
#define BUFFER_LENGTH 4096
#define REPORT_FREQUENCY 50
#define RANGES 3
/* maximum number of splice sequences in splice file */
#define MAX_SPLICE_SEQS 40
#define newstring(len, str) (strcpy(malloc(sizeof(char)*(len)), (str)))

typedef struct seq_struct {
  char *name;
  struct seq_struct *next;
  long spos, qpos;
  int len, left, right;
  struct range_struct {
    int left, right;
  } CLN, CLZ, CLB, CLV;
} Seq;

static int convert[128]={
  -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
  -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
  -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,15,-1,-1,
  -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
/* @  A  B  C  D  E  F  G  H  I  J  K  L  M  N  O
   P  Q  R  S  T  U  V  W  X  Y  Z                */
  -1, 0,14, 1,11,-1,-1, 2,12,-1,-1,10,-1, 7,15,-1,
  -1,-1, 5, 9, 3, 4,13, 8,15, 6,-1,-1,-1,-1,-1,-1,
  -1, 0,14, 1,11,-1,-1, 2,12,-1,-1,10,-1, 7,15,-1,
  -1,-1, 5, 9, 3, 4,13, 8,15, 6,-1,-1,-1,-1,-1,-1};
 
/* variables defined in qual_trim.c */
#define MAX_NUMBER_OF_WINDOWS 20
extern int *conf_val_raw;
extern int num_windows, windows[];
extern double err_limits[], max_avg_error, end_limit;

/* variables defined in abi.c */
extern struct abi_struct {
  unsigned tag;
  int index;
} *abi_well;
extern struct hit_struct {
  int diff, count;
} *hit_well;

/* variables defined in vector.c */
extern int tag_size;

/* variables defined in splice.c */
#define MAXIMUM_THREADS 32
extern int *splice_match_base;
extern int *splice_score_pool[]; 
extern char *splice_direc_pool[];

/* variables defined in poly.c */
extern int cdna, cerr, crng, keep;

static char *program_name;

void giveup(msg)
char *msg;
{
  fprintf(stderr, "%s: %s\n", program_name, msg);
  fprintf(stderr, 
	  "usage: %s\n"
	  "   [-pass_along min_value max_value med_value]\n"
	  "   [-range area1 area2 area3] [-alignment area1 area2 area3]\n"
	  "   [-vector vector_sequence_file splice_site_file]\n"
	  "   [-cdna [minimum_span maximum_error initial_search_range]] [-keep]\n"
	  "   [-size vector_tag_size] [-threshold vector_cutoff]\n"
	  "   [-minimum good_sequence_length] [-debug [filename]]\n"
	  "   [-output sequence_filename quality_filename]\n"
          "   [-error max_avg_error max_error_at_ends]\n"
          "   [-window window_size max_avg_error [window_size max_avg_error ...]]\n"
          "   [-bracket window_size max_avg_error]\n"
	  "   [-quiet] [-inform_me] [-xtra cpu_threads]\n"
	  "   sequence_file quality_file [2nd_sequence_file]\n\n"
	  "For more information try 'man -F lucy'.\n",
	  program_name);
  exit(99);
}

void complain(msg)
char *msg;
{
  fprintf(stderr, "%s: %s\n", program_name, msg);
}

unsigned int hashstring(s)
unsigned char *s;
{
  register unsigned int value, g;
  register unsigned char *ptr;
 
  value=0;  ptr = s;
  while (*ptr) {
    value = (value << 4) + *ptr;
    if (g = value&0xF0000000) {
      value = value ^ (g>>24);
      value = value ^ g;
    }
    ptr++;
  }
  return value;
}

static Seq *table[TABLE_LENGTH];
 
Seq *lookup(s)
char *s;
{
  register Seq *slot;
  
  slot = table[hashstring(s)%TABLE_LENGTH];
  while (slot != NULL) {
    if (strcmp(s, slot->name)==0)
      return slot;
    else
      slot = slot->next;
  }
  return slot;
}
 
void insert(ptr)
Seq *ptr;
{
  register int i;
 
  i = hashstring(ptr->name)%TABLE_LENGTH;
  ptr->next=table[i];
  table[i] = ptr;
}
 
/* thread related variables */
pthread_mutex_t job_lock, acc_lock;
pthread_cond_t job_waiting, job_returning, job_done;
int thread_count, job_count, job_close, shutdown, *jobs, job_todo, job_pool;
pthread_t *threads;
void (*work)();

int assign_job(id)
     int id;
{
  pthread_mutex_lock(&job_lock);
  job_todo=id;
  job_count++;
  pthread_cond_signal(&job_waiting);
  while (job_pool<0)
    pthread_cond_wait(&job_returning, &job_lock);
  id=job_pool;
  job_pool=-1;
  pthread_mutex_unlock(&job_lock);
  return id;
}

void *worker(arg)
     void *arg;
{
  int id=(int)arg;
  pthread_mutex_lock(&job_lock);
  while (1) {
    while (job_todo<0 && !shutdown)
      pthread_cond_wait(&job_waiting, &job_lock);
    if (shutdown) {
      pthread_mutex_unlock(&job_lock);
      pthread_exit(NULL);
    }
    job_pool=id;
    id=job_todo;
    job_todo=-1;
    pthread_cond_signal(&job_returning);
    pthread_mutex_unlock(&job_lock);
    (*work)(id);
    pthread_mutex_lock(&job_lock);
    job_count--;
    if (job_close && job_count<=0)
      pthread_cond_signal(&job_done);
  }
}

Seq *seqs;
int acc, splice_seqs, first, match[RANGES], range[RANGES], 
  minimum, splice_bases[MAX_SPLICE_SEQS];
char *target_seq[MAXIMUM_THREADS+1], *splice_seq[MAX_SPLICE_SEQS];

void work_splice(id)
     int id;
{
  int i, j, left, right, shift, saved;

  i=jobs[id];
  for (j=0; j<splice_seqs && seqs[i].left<seqs[i].right; j+=2) {
    splice_align_left(id, target_seq[id], 
		      seqs[i].len>first ? first : seqs[i].len,  
		      splice_seq[j], splice_bases[j], 
		      0, first, &right);
    if (seqs[i].left>first) {
      shift = seqs[i].left;
      splice_align_left(id, target_seq[id]+shift-match[RANGES-1],
			(seqs[i].len>shift+range[RANGES-1]) ? 
			(range[RANGES-1]+match[RANGES-1]) :
			(seqs[i].len-shift+match[RANGES-1]),   
			splice_seq[j], splice_bases[j],
			shift-match[RANGES-1], seqs[i].left, &saved); 
      if (saved>right) right=saved;
      shift += range[RANGES-1];
    } else if (right<0 && seqs[i].len>first) {
      shift = first;
      splice_align_left(id, target_seq[id]+shift-match[RANGES-1],
			(seqs[i].len>shift+range[RANGES-1]) ? 
			(range[RANGES-1]+match[RANGES-1]) :
			(seqs[i].len-shift+match[RANGES-1]),   
			splice_seq[j], splice_bases[j],
			shift-match[RANGES-1], seqs[i].left, &right); 
      shift += range[RANGES-1];
    } else
      shift = first;
    for (; right+1>=shift && seqs[i].len>shift; shift+=range[RANGES-1]) {
      splice_align_left(id, target_seq[id]+shift-match[RANGES-1],
			(seqs[i].len>shift+range[RANGES-1]) ? 
			(range[RANGES-1]+match[RANGES-1]) :
			(seqs[i].len-shift+match[RANGES-1]),   
			splice_seq[j], splice_bases[j],
			shift-match[RANGES-1], shift, &saved);  
      if (saved>right) right=saved;
    }
    if (right>=0) {
      if (right+2>seqs[i].CLV.left)
	seqs[i].CLV.left=right+2;
      if (right>=seqs[i].left)
	seqs[i].left=right+1;
    }
    if (seqs[i].left<=seqs[i].right-minimum) {
      splice_align_right(id, target_seq[id]+seqs[i].left, 
			 seqs[i].right-seqs[i].left+1,
			 splice_seq[j+1], splice_bases[j+1],
			 seqs[i].left, match[RANGES-1], &left);
      if (left<0 && seqs[i].right<seqs[i].len-1) {
        /* No hit found -- look again just at the end of the current */
        /* clear range, extending past the end of the range to find any */
        /* splice hits that begin near the end of the clear range. */
        /* We'll use N bases from the end of the current clear range and */
        /* N bases after the range, where N is the required match length. */
        left=seqs[i].right-match[RANGES-1]+1;
        if (left<seqs[i].left)
          left=seqs[i].left;
        right=seqs[i].right+match[RANGES-1];
        if (right>=seqs[i].len)
          right=seqs[i].len-1;
        splice_align_right(id, target_seq[id]+left, 
                           right-left+1,
                           splice_seq[j+1], splice_bases[j+1],
                           left, match[RANGES-1], &left);
      }
      if (left>=0) {
	if (seqs[i].CLV.right<=0 || left<seqs[i].CLV.right)
	  seqs[i].CLV.right=left;
	if (left<=seqs[i].right)
	  seqs[i].right=left-1;
      }
    }
    if (seqs[i].right-seqs[i].left<minimum) {
      seqs[i].left=seqs[i].right=0;
      pthread_mutex_lock(&acc_lock);
      acc++;
      pthread_mutex_unlock(&acc_lock);
    }
  }
}

main (argc, argv)
int argc;
char *argv[];
{
  register int i, j, bases;
  register Seq *ptr;
  int title, count, max_bases, abi_max_bases, left, right, saved, id;
  int c_min, c_max, c_med, threshold, debug, verbose, inform;
  int bracket_size;
  double bracket_err;
  char buf[BUFFER_LENGTH], buf2[BUFFER_LENGTH], *abi_seq, *vec_seq,
    *phred_seq, *tmp;
  char *seq_name, *qul_name, *abi_name, *vec_name, *spl_name;
  FILE *seq_file, *qul_file, *abi_file, *vec_file, *spl_file;
  char *seq_out_name, *qul_out_name, *debug_file_name;
  FILE *seq_out, *qul_out, *debug_file;
  
  /***************************************************************/
  /* Phase 0.0: initialize file names, pointers, variables, etc. */
  /***************************************************************/
  seq_name=qul_name=abi_name=vec_name=spl_name=NULL;
  seq_file=qul_file=abi_file=vec_file=spl_file=NULL;
  program_name=argv[0];
  c_min=c_max=c_med=0; 
  range[0]=40; range[1]=60; range[2]=100; 
  match[0]=8;  match[1]=12; match[2]=16;
  tag_size=10;  threshold=20;  minimum=100;  debug=0;  verbose=1;
  inform=0; cdna=keep=0; thread_count=1;
  seq_out_name="lucy.seq"; qul_out_name="lucy.qul"; 
  debug_file_name="lucy.debug";
  num_windows = 0;

  /*******************************************/
  /* Phase 0.1: parse command line arguments */
  /*******************************************/
  for (i=1; i<argc; i++)
    if (argv[i][0]=='-') /* an option */
      switch (argv[i][1]) {
      case 'w':
        for (num_windows=0; (i+2)<argc; num_windows++) {
          if (!isdigit(argv[i+1][0]))
            break;
	  if (num_windows>=MAX_NUMBER_OF_WINDOWS)
	    giveup("maximum number of -window option pairs exceeded");
          windows[num_windows]=atoi(argv[++i]);
	  if (windows[num_windows]<=0)
	    giveup("invalid window size for -window options");
          if (num_windows &&
              windows[num_windows]>windows[num_windows-1])
            giveup("sizes must be in decreasing order for -window options");
          if (!isdigit(argv[i+1][0]) && argv[i+1][0]!='.')
            giveup("incorrect number of -window options");
          err_limits[num_windows]=atof(argv[++i]);
          if (err_limits[num_windows]>1.0||err_limits[num_windows]<0.0)
            giveup("invalid probability values for -window options");
        }
        if (num_windows<=0)
          giveup("incorrect number of -window options");
        break;
      case 'e':
        if ((i+2)<argc) {
          max_avg_error=atof(argv[++i]);
          end_limit=atof(argv[++i]);
          if (max_avg_error>1.0 || max_avg_error<0.0 || end_limit>1.0
              || end_limit<0.0)
            giveup("invalid probability values for -error options");
        } else
          giveup("incorrect number of -error options");
        break;
      case 'b':
        if ((i+2)<argc) {
          bracket_size=atoi(argv[++i]);
          bracket_err=atof(argv[++i]);
          if (bracket_err>1.0 || bracket_err<0.0 || bracket_size<=0)
            giveup("invalid values for -bracket option");
        } else
          giveup("incorrect number of -bracket options");
        set_bracket(bracket_size, bracket_err);
        break;
      case 'p':
	if ((i+3)<argc) {
	  c_min=atoi(argv[++i]);
	  c_max=atoi(argv[++i]);
	  c_med=atoi(argv[++i]);
	} else
	  giveup("incorrect number of -pass_along options");
	break;
      case 'r':
	if ((i+3)<argc) {
	  range[0]=atoi(argv[++i]);
	  range[1]=atoi(argv[++i]);
	  range[2]=atoi(argv[++i]);
	} else
	  giveup("incorrect number of -range options");
	break;
      case 'a':
	if ((i+3)<argc) {
	  match[0]=atoi(argv[++i]);
	  match[1]=atoi(argv[++i]);
	  match[2]=atoi(argv[++i]);
	} else
	  giveup("incorrect number of -alignment options");
	break;
      case 'v':
	if ((i+2)<argc) {
	  vec_name=argv[++i];
	  spl_name=argv[++i];
	} else
	  giveup("incorrect number of -vector options");
	break;
      case 's':
	if ((i+1)<argc)
	  tag_size=atoi(argv[++i]);
	else
	  giveup("incorrect number of -size options");
	if (tag_size>16 || tag_size<8)
	  giveup("invalid tag size; must be between 8 to 16");
	break;
      case 't':
	if ((i+1)<argc)
	  threshold=atoi(argv[++i]);
	else
	  giveup("incorrect number of -threshold options");
	break;
      case 'm':
	if ((i+1)<argc)
	  minimum=atoi(argv[++i]);
	else
	  giveup("incorrect number of -minimum options");
	break;
      case 'd':
	debug=1;
	if ((i+1)<argc && argv[i+1][0]!='-')
	  debug_file_name=argv[++i];
	break;
      case 'q':
	verbose=0;
	break;
      case 'i':
	inform=1;
	break;
      case 'c':
	cdna=10; cerr=3; crng=50;
	if ((i+1)<argc && isdigit(argv[i+1][0])) {
	  if ((i+3)<argc) {
	    cdna=atoi(argv[++i]);
	    cerr=atoi(argv[++i]);
	    crng=atoi(argv[++i]);
	  } else
	    giveup("incorrect number of -cdna options");
	}
	break;
      case 'k':
	keep=1;
	break;
      case 'o':
	if ((i+2)<argc) {
	  seq_out_name=argv[++i];
	  qul_out_name=argv[++i];
	} else
	  giveup("incorrect number of -output options");
	break;
      case 'x':
	if ((i+1)<argc)
	  thread_count=atoi(argv[++i]);
	else
	  giveup("incorrect number of -extra options");
	if (thread_count>MAXIMUM_THREADS || thread_count<1)
	  giveup("invalid thread_count; must be between 1 to 32.");
	break;
      default:
	sprintf(buf, "unknown option %s", argv[i]);
	giveup(buf);
      }
    else if (seq_name==NULL)
      seq_name=argv[i];
    else if (qul_name==NULL)
      qul_name=argv[i];
    else if (abi_name==NULL)
      abi_name=argv[i];
    else
      giveup("extraneous file names");
  
  if (num_windows == 0) {
    /* set up default windows for quality trimming */
    default_windows();
  }

  if (verbose) {
    fprintf(stderr, 
	    "Less Useful Chunks Yank (lucy) 1.20p, by Hui-Hsien Chou and Michael Holmes,\n");
    fprintf(stderr, 
	    "  with help from Granger, Anna, John and Terry Shea.\n");
  }
  
  /******************************************************/
  /* Phase 0.2: done with parsing, check required files */
  /******************************************************/
  if (seq_name==NULL)
    giveup("no input sequence file");
  else if ((seq_file=fopen(seq_name, "r"))==NULL)
    giveup("error opening input sequence file");

  if (qul_name==NULL)
    giveup("no input quality file");
  else if ((qul_file=fopen(qul_name, "r"))==NULL)
    giveup("error opening input quality value file");

  if (abi_name && (abi_file=fopen(abi_name, "r"))==NULL)
    giveup("error opening 2nd sequence file");

  if (vec_name==NULL)
    vec_name=getenv("VECTOR_FILE");
  if (vec_name) {
    if ((vec_file=fopen(vec_name, "r"))==NULL)
      giveup("error opening vector sequence file");
  } else
    complain("Warning! No vector file given;" 
	     " vector removal will not be done!");

  if (spl_name==NULL)
    spl_name=getenv("SPLICE_FILE");
  if (spl_name)  {
    if ((spl_file=fopen(spl_name, "r"))==NULL)
      giveup("error opening splice site file");
  } else
    complain("Warning! No splice file given;" 
	     " splice site will not be trimmed!");
    
  /******************************************************/
  /* Phase 0.3: spin off extra computing threads        */
  /******************************************************/
  threads=(pthread_t*)malloc(sizeof(pthread_t)*thread_count);
  jobs=(int*)malloc(sizeof(int)*(thread_count+1));
  job_count=job_close=shutdown=0; job_todo=job_pool=-1; id=thread_count;

  if (pthread_mutex_init(&job_lock, NULL))
    giveup("can't initialize thread mutex job_lock");
  if (pthread_mutex_init(&acc_lock, NULL))
    giveup("can't initialize thread mutex acc_lock");
  if (pthread_cond_init(&job_waiting, NULL))
    giveup("can't initialize thread condition job_waiting");
  if (pthread_cond_init(&job_returning, NULL))
    giveup("can't initialize thread condition job_returning");
  if (pthread_cond_init(&job_done, NULL))
    giveup("can't initialize thread condition job_done");
  for (i=0; i<thread_count; i++)
    if (pthread_create(&threads[i], NULL, worker, (void*)i))
      giveup("error creating extra computing threads");
  
  /********************************************************/
  /* Phase 1: count the number of sequences in input file */
  /********************************************************/
  if (verbose)
    fprintf(stderr, "Phase 1: Checking the number of input sequences...\n");
  for (count=0; fgets(buf, BUFFER_LENGTH, seq_file);  )
    if (buf[0]=='>' && !isspace(buf[1])) {
      count++;
      if (verbose && count%REPORT_FREQUENCY==0)
	fprintf(stderr, "%d\r", count);
    }
  if (count<=0)
    giveup("input sequence file has no sequence data");
  if (verbose)
    fprintf(stderr, "         %d input sequences found.\n", count);
  
  /* allocate sequence array for information gathering */
  seqs=(Seq*)calloc(count, sizeof(Seq));

  /*********************************************************************/
  /* Phase 2: read sequence name, length and file position information */
  /*********************************************************************/
  if (verbose)
    fprintf(stderr, "Phase 2: Reading sequence name, length and position data...\n");

  /* initial value of max_bases is the sum of the alignment ranges */
  for (i=max_bases=0; i<RANGES; i++)
	max_bases+=range[i];

  rewind(seq_file);
  while (fgets(buf, BUFFER_LENGTH, seq_file) && buf[0]!='>') ;
  for (i=acc=0; i<count; i++) {
    for (j=1; buf[j] && !isspace(buf[j]); j++) ;
    buf[j]='\0';
    seqs[i].name=newstring(j, &buf[1]);
    if (lookup(seqs[i].name)) {
      sprintf(buf, "duplicate names >%s in input sequence file",
	      seqs[i].name);
      giveup(buf);
    }
    insert(&seqs[i]);
    seqs[i].spos=ftell(seq_file); 
    seqs[i].qpos=-1;

    for (bases=0; fgets(buf, BUFFER_LENGTH, seq_file) && buf[0]!='>';  ) {
      for (j=0; buf[j] && !isspace(buf[j]); j++)
	if (convert[buf[j]&0x7F]<0) {
	  sprintf(buf, "invalid character %c for >%s in sequence file",
		  buf[j], seqs[i].name); 
	  giveup(buf);
	}
      bases+=j;
    }
    
    if ((seqs[i].len=bases)<=0)
      acc++;
    if (bases>max_bases)
      max_bases=bases;
    if (verbose && i%REPORT_FREQUENCY==0)
      fprintf(stderr, "%d\r", i);
  }
  if (verbose)
    fprintf(stderr, "         %d empty sequences discarded.\n", acc);
  
  /**********************************************************/
  /* Phase 3: determine good quality range based on average */
  /*          probability of error.                         */
  /**********************************************************/
  /* allocate appropriate data structures for grim.c/range() */
  conf_val_raw=(int*)malloc(sizeof(int)*max_bases);

  /* read in quality values, determine clear range for each sequence */
  if (verbose)
    fprintf(stderr, "Phase 3: Reading quality values and checking good"
	    " sequence regions...\n");
  while ((tmp=fgets(buf, BUFFER_LENGTH, qul_file)) && buf[0]!='>') ;
  for (title=i=acc=0; tmp; i++) {
    for (j=1; buf[j] && !isspace(buf[j]); j++) ;
    buf[j]='\0';
    if ((ptr=lookup(&buf[1]))==NULL) {
      if (title==0) {
	complain("the quality inputs below (except dropped) "
		 "have no counterpart in the sequence file");
	title=1;
      }
      complain(buf);
      while ((tmp=fgets(buf, BUFFER_LENGTH, qul_file)) && buf[0]!='>') ;
      continue;
    }
    ptr->qpos=ftell(qul_file);
    for (j=0; j<ptr->len; j++)
      if (fscanf(qul_file, "%d", &conf_val_raw[j])!=1) {
	sprintf(buf, "invalid/mismatch quality input for sequence >%s",
		ptr->name);
	giveup(buf);
      }
    if (j)
      fgets(buf, BUFFER_LENGTH, qul_file);
    if ((tmp=fgets(buf, BUFFER_LENGTH, qul_file)) && buf[0]!='>') {
      sprintf(buf, "invalid/mismatch quality input for sequence >%s",
	      ptr->name);
      giveup(buf);
    }
    if (j) {
      /* trim the sequence (determine clean range based on quality) */
      quality_trim(conf_val_raw, j, minimum, &(ptr->left), &(ptr->right));
      if (ptr->left>=ptr->right) {
	ptr->CLN.left=0; ptr->CLN.right=0;
	acc++;
	if (verbose && inform) {
	  sprintf(buf2, "==> dropping %s", ptr->name);
	  complain(buf2);
	}
      } else {
	ptr->CLN.left=ptr->left+1; ptr->CLN.right=ptr->right+1;
      }
    }
    if (verbose && i%REPORT_FREQUENCY==0)
      fprintf(stderr, "%d\r", i);
  }
  if (verbose)
    fprintf(stderr, "         %d quality sequences read; "
	    "%d low quality sequences dropped.\n", i, acc);

  /* deallocate data structures for grim.c/range() */
  free(conf_val_raw);
  
  /*******************************************************************/
  /* Phase 4: compare Phred base calls to ABI base calls if provided */
  /*******************************************************************/
  if (abi_file) {
    if (verbose)
      fprintf(stderr, "Phase 4: Comparing to 2nd sequence file...\n");

    /* allocate arrays for abi.c/abi_align() */
    prepare_abi_mask();
    phred_seq=(char*)malloc(sizeof(char)*max_bases);
    abi_well=(struct abi_struct*)malloc(sizeof(struct abi_struct)*max_bases);
    hit_well=(struct hit_struct*)malloc(sizeof(struct hit_struct)*max_bases);
    abi_max_bases=max_bases+BUFFER_LENGTH;
    abi_seq=(char*)malloc(sizeof(char)*abi_max_bases);

    while ((tmp=fgets(buf, BUFFER_LENGTH, abi_file)) && buf[0]!='>') ;
    for (saved=title=i=acc=0; tmp; i++) {
      for (j=1; buf[j] && !isspace(buf[j]); j++) ;
      buf[j]='\0';
      if ((ptr=lookup(&buf[1]))==NULL) {
	if (title==0) {
	  complain("the 2nd sequences below (except salvaged) "
		   "are not found in the first sequence file");
	  title=1;
	}
	complain(buf);
	while ((tmp=fgets(buf, BUFFER_LENGTH, abi_file)) && buf[0]!='>') ;
	continue;
      }
      if (ptr->len>0) {
	fseek(seq_file, ptr->spos, SEEK_SET);
	for (bases=0; fgets(buf, BUFFER_LENGTH, seq_file) && buf[0]!='>';  ) 
	  for (j=0; buf[j] && !isspace(buf[j]); j++)
	    phred_seq[bases++]=convert[buf[j]&0x7F];
	if (bases!=ptr->len)
	  giveup("how can bases!=ptr->len happen in Phase 4? "
		 "Report to programmer!");
      }
      for (bases=0; (tmp=fgets(buf, BUFFER_LENGTH, abi_file)) &&
	   buf[0]!='>';  ) 
	for (j=0; buf[j] && !isspace(buf[j]); j++) {
	  if (bases>=abi_max_bases) {
	    abi_max_bases += BUFFER_LENGTH;
	    abi_seq=realloc(abi_seq, sizeof(char)*abi_max_bases);
	  }	    
	  if ((abi_seq[bases++]=convert[buf[j]&0x7F])<0) {
	    sprintf(buf, "invalid character %c for >%s in 2nd sequence file",
		    buf[j], ptr->name); 
	    giveup(buf);
	  }
	}
      if (ptr->len>0) {
	abi_align(phred_seq, ptr->len, abi_seq, bases, &left, &right);
	if (left>=right) {
	  ptr->CLZ.left=0; ptr->CLZ.right=0;
	} else {
	  ptr->CLZ.left=left+1; ptr->CLZ.right=right+1;
	}
	if (right-left>minimum) {
	  if (ptr->left>=ptr->right) {
	    saved++; acc++;
	    ptr->left=left;
	    ptr->right=right;
	    if (verbose && inform) {
	      sprintf(buf2, "<== saving %s", ptr->name);
	      complain(buf2);
	    }
	  } else if (left<ptr->left) {
	    ptr->left=left; acc++;
	    if (right>ptr->right)
	      ptr->right=right;
	  } else if (right>ptr->right) {
	    ptr->right=right; acc++;
	  }
	}
      }
      if (verbose && i%REPORT_FREQUENCY==0)
	fprintf(stderr, "%d\r", i);
    }
    if (verbose)
      fprintf(stderr, "         %d 2nd sequences compared;"
	      " %d sequences extended.\n", i, acc);
    if (verbose && saved)
      fprintf(stderr, "         %d low quality sequences salvaged.\n", saved);

    /* deallocate dynamic programming matrix for abi.c/abi_align() */
    free(abi_seq);
    free(hit_well);
    free(abi_well);
    free(phred_seq);
  } else
    if (verbose)
      fprintf(stderr, "Phase 4: 2nd sequences comparsion skipped...\n"
	      "         no 2nd sequence file provided.\n"); 

  /* update CLB information */
  for (i=0; i<count; i++) {
    if (seqs[i].left>=seqs[i].right) {
      seqs[i].CLB.left=0;
      seqs[i].CLB.right=0;
    }
    else {
      seqs[i].CLB.left=seqs[i].left+1;
      seqs[i].CLB.right=seqs[i].right+1;
    }
  }
    
  /***********************************************/
  /* Phase 5: locate splice sites on sequences   */
  /***********************************************/
  if (spl_file) {
    if (verbose)
      fprintf(stderr, "Phase 5: Locating splice sites...");

    /* making match array */
    for (i=bases=0; i<RANGES; i++)
      bases+=range[i];
    first=bases;
    splice_match_base=(int*)malloc(sizeof(int)*max_bases);
    for (i=bases=0; i<RANGES; i++)
      for (j=0; j<range[i]; j++)
	splice_match_base[bases++]=match[i];
    while (bases<max_bases)
      splice_match_base[bases++]=match[RANGES-1];

    /* count the number of splice sequences */
    while (fgets(buf, BUFFER_LENGTH, spl_file) && buf[0]!='>') ;
    splice_seqs=0; 
    for (i=0; i<MAX_SPLICE_SEQS; i++) splice_bases[i]=0;
    do {
      for (bases=0; 
	   (i=(int)fgets(buf, BUFFER_LENGTH, spl_file)) && buf[0]!='>'; ) {
	for (j=0; buf[j] && !isspace(buf[j]); j++)
	  if (convert[buf[j]&0x7F]<0) {
	    sprintf(buf, "invalid character %c in splice file", buf[j]); 
	    giveup(buf);
	  }
	bases+=j;
      }
      splice_bases[splice_seqs++]=bases;
    } while (i && splice_seqs<MAX_SPLICE_SEQS);

    /* check validity of splice site sequences */
    for (i=0; i<splice_seqs; i++) {
      if (splice_bases[i]<32) {
        giveup("you probably have a wrong splice file;"
	       " some splice sequence(s) have less than 32bp?");
      }
    }
    
    /* number of splice sequence must be a multiple of 2 */
    if (splice_seqs<2 || (splice_seqs&1) == 1) {
      giveup("Incorrect number of splice sequences in splice file.");
    }
    
    if (verbose) {
      fprintf(stderr, "Number of splice sequences: %d\n", splice_seqs);
    }
    
    /* load splice site sequences, allocate data arrays */
    rewind(spl_file);
    while (fgets(buf, BUFFER_LENGTH, spl_file) && buf[0]!='>') ;
    for (i=0; i<splice_seqs; i++) {
      splice_seq[i]=(char*)malloc(sizeof(char)*splice_bases[i]);
      for (bases=0; fgets(buf, BUFFER_LENGTH, spl_file) && buf[0]!='>';  ) 
	for (j=0; buf[j] && !isspace(buf[j]); j++)
	  splice_seq[i][bases++]=convert[buf[j]&0x7F];
    }
    for (i=bases=0; i<splice_seqs; i++)
      if (bases<splice_bases[i]) bases=splice_bases[i];
    for (i=0; i<=thread_count; i++) {
      target_seq[i]=(char*)malloc(sizeof(char)*max_bases);
      splice_score_pool[i]=(int*)malloc(sizeof(int)*max_bases*bases);
      splice_direc_pool[i]=(char*)malloc(sizeof(char)*max_bases*bases);
    }
    work=work_splice;

    /* locating splice sites for each sequence */
    for (i=acc=0; i<count; i++) {
      if (seqs[i].left<seqs[i].right) {
	jobs[id]=i;
	fseek(seq_file, seqs[i].spos, SEEK_SET);
	for (bases=0; fgets(buf, BUFFER_LENGTH, seq_file) && buf[0]!='>';  ) 
	  for (j=0; buf[j] && !isspace(buf[j]); j++)
	    target_seq[id][bases++]=convert[buf[j]&0x7F];
	if (bases!=seqs[i].len)
	  giveup("how can bases!=seqs[i].len happen in Phase 5?"
		 " Report to programmer!");
	id=assign_job(id);
      }
      if (verbose && i%REPORT_FREQUENCY==0)
	fprintf(stderr, "%d\r", i);
    }
    pthread_mutex_lock(&job_lock);
    job_close=1;
    while (job_count>0)
      pthread_cond_wait(&job_done, &job_lock);
    job_close=0;
    pthread_mutex_unlock(&job_lock);
    if (verbose)
      fprintf(stderr, 
	      "         %d short or no insert sequences discarded.\n", acc);
    for (i=thread_count; i>=0; i--) {
      free(splice_direc_pool[i]);
      free(splice_score_pool[i]);
      free(target_seq[i]);
    }
    for (i=splice_seqs-1; i>=0; i--)
      free(splice_seq[i]);
    free(splice_match_base);
  }
  
  /*************************************************/
  /* Phase 5a: identify poly-A/T ends on sequences */
  /*************************************************/
  if (cdna) {
    if (verbose)
      fprintf(stderr, "Phase 5a: Identifying Poly-A/T ends...\n");

    /* identifying poly-A/T ends for each sequence */
    phred_seq=(char*)malloc(sizeof(char)*max_bases);
    for (i=acc=0; i<count; i++) {
      if (seqs[i].left<seqs[i].right) {
	fseek(seq_file, seqs[i].spos, SEEK_SET);
	for (bases=0; fgets(buf, BUFFER_LENGTH, seq_file) && buf[0]!='>';  ) 
	  for (j=0; buf[j] && !isspace(buf[j]); j++)
	    phred_seq[bases++]=convert[buf[j]&0x7F];
	if (bases!=seqs[i].len)
	  giveup("how can bases!=seqs[i].len happen in Phase 5a?"
		 " Report to programmer!");
	left=poly_at_left(&phred_seq[seqs[i].left],
			  seqs[i].right-seqs[i].left+1); 
	if (left) seqs[i].left+=left;
	right=poly_at_right(&phred_seq[seqs[i].right],
			    seqs[i].right-seqs[i].left+1);
	if (right) seqs[i].right-=right;
	if (seqs[i].right-seqs[i].left<minimum) {
	  seqs[i].left=seqs[i].right=0;
	  acc++;
	}
      }
      if (verbose && i%REPORT_FREQUENCY==0)
	fprintf(stderr, "%d\r", i);
    }
    if (verbose)
      fprintf(stderr, 
	      "         %d short sequences discarded due to poly-A/T trimming.\n", acc);
    free(phred_seq);
  }
  
  /************************************/
  /* Phase 6: remove vector sequences */
  /************************************/
  if (vec_file) {
    if (verbose)
      fprintf(stderr, "Phase 6: Kicking out vector sequences...\n");
    while (fgets(buf, BUFFER_LENGTH, vec_file) && buf[0]!='>') ;
    for (bases=0; fgets(buf, BUFFER_LENGTH, vec_file) && buf[0]!='>';  ) {
      for (j=0; buf[j] && !isspace(buf[j]); j++)
	if (convert[buf[j]&0x7F]<0) {
	  sprintf(buf, "invalid character %c in vector file", buf[j]); 
	  giveup(buf);
	}
      bases+=j;
    }
    if (bases<32)
      giveup("you probably have a wrong vector file; less than 32 bases?");
    vec_seq=(char*)malloc(sizeof(char)*bases);
    rewind(vec_file);
    while (fgets(buf, BUFFER_LENGTH, vec_file) && buf[0]!='>') ;
    for (bases=0; fgets(buf, BUFFER_LENGTH, vec_file) && buf[0]!='>';  ) 
      for (j=0; buf[j] && !isspace(buf[j]); j++)
	  vec_seq[bases++]=convert[buf[j]&0x7F];
    construct_vector_tags(vec_seq, bases);
    free(vec_seq);
    phred_seq=(char*)malloc(sizeof(char)*max_bases);
    for (i=acc=0; i<count; i++) {
      if (seqs[i].left<seqs[i].right) {
	fseek(seq_file, seqs[i].spos, SEEK_SET);
	for (bases=0; fgets(buf, BUFFER_LENGTH, seq_file) && buf[0]!='>';  ) 
	  for (j=0; buf[j] && !isspace(buf[j]); j++)
	    phred_seq[bases++]=convert[buf[j]&0x7F];
	if (bases!=seqs[i].len)
	  giveup("how can bases!=ptr->len happen in Phase 6?"
		 " Report to programmer!");
	bases=seqs[i].right-seqs[i].left+1;
	j=match_vector_tags(phred_seq+seqs[i].left, bases); 
	if (bases-j<minimum || (j*100)/bases>threshold) {  
	  seqs[i].left=seqs[i].right=0;
	  acc++;
	}
      }
      if (verbose && i%REPORT_FREQUENCY==0)
	fprintf(stderr, "%d\r", i);
    }
    if (verbose)
      fprintf(stderr, "         %d vector sequences discarded.\n", acc);
    free(phred_seq);
    destroy_vector_tags();
  }

  /******************************************************/
  /* Phase 7: produce output sequence and quality files */
  /******************************************************/
  if (verbose)
    fprintf(stderr, "Phase 7: Producing output sequence and quality files...\n");
  seq_out=fopen(seq_out_name, "w");
  qul_out=fopen(qul_out_name, "w");
  for (title=i=acc=0; i<count; i++) {
    if (seqs[i].qpos==-1) {
      if (title==0) {
	complain("the sequences below have no counterpart in "
		 "the quality input file");
	title=1;
      }
      sprintf(buf, ">%s", seqs[i].name);
      complain(buf);
    } else if (seqs[i].left < seqs[i].right) {
      sprintf(buf, ">%s %d %d %d %d %d\n",
	      seqs[i].name, c_min, c_max, c_med, 
	      seqs[i].left+1, seqs[i].right+1); 
      fputs(buf, seq_out);
      sprintf(buf, ">%s\n", seqs[i].name);
      fputs(buf, qul_out);
      fseek(seq_file, seqs[i].spos, SEEK_SET);
      while (fgets(buf, BUFFER_LENGTH, seq_file) && buf[0]!='>')
	fputs(buf, seq_out);
      fseek(qul_file, seqs[i].qpos, SEEK_SET);
      while (fgets(buf, BUFFER_LENGTH, qul_file) && buf[0]!='>')
	fputs(buf, qul_out);
      acc++;
    }
    if (verbose && i%REPORT_FREQUENCY==0)
      fprintf(stderr, "%d\r", i);
  }
  if (verbose)
    fprintf(stderr, "         %d good sequences written in"
	    " %s and %s.\n", acc, seq_out_name, qul_out_name);
  fclose(seq_out);
  fclose(qul_out);
  if (debug) {
    debug_file=fopen(debug_file_name, "w");
    for (i=0; i<count; i++) {
      if (seqs[i].left < seqs[i].right)
	fprintf(debug_file, "%s\tCLR\t%d\t%d", seqs[i].name,
		seqs[i].left+1, seqs[i].right+1);
      else
	fprintf(debug_file, "%s\tCLR\t%d\t%d", seqs[i].name, 0, 0);
      fprintf(debug_file, "\tCLB\t%d\t%d", seqs[i].CLB.left,
	      seqs[i].CLB.right); 
      fprintf(debug_file, "\tCLN\t%d\t%d", seqs[i].CLN.left,
	      seqs[i].CLN.right); 
      fprintf(debug_file, "\tCLZ\t%d\t%d", seqs[i].CLZ.left,
	      seqs[i].CLZ.right); 
      fprintf(debug_file, "\tCLV\t%d\t%d\n", seqs[i].CLV.left,
	      seqs[i].CLV.right); 
    }
    fclose(debug_file);
    if (verbose)
      fprintf(stderr, "         %d sequence cleavage information"
	      " written in %s.\n", count, debug_file_name);
  }

  /******************************************************/
  /* Phase 0.3: terminate all computing threads         */
  /******************************************************/
  shutdown=1;
  pthread_cond_broadcast(&job_waiting);
  for (i=0; i<thread_count; i++)
    pthread_join(threads[i], NULL);

  return 0;
}