+ some optimization
[qpalma.git] / tools / data_tools / filterReads.c
index 9398454..ae84946 100644 (file)
-////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////////
 // The purpose of this program is to read a gff and a    
 // solexa reads file and create a data set used by QPalma. 
 //
 //
 //
-////////////////////////////////////////////////////////////
+// Notes:
+//
+// - Both the read indices and the gff gene indices are one-based
+//
+//
+////////////////////////////////////////////////////////////////////////////////
 
 #include <sys/mman.h>
+#include <sys/stat.h>
 #include <stdio.h>
 #include <stdlib.h>
+#include <assert.h>
 #include <string.h>
+#include <unistd.h>
+#include <math.h>
 
+#include "debug_tools.h"
+#include "join.h"
 #include "datastructures.h"
 
+#define _FILE_OFFSET_BITS == 64
+
+const char* line_format = "%d\t%d\t%s\t%lu\t%c\t%d\t%d\t%d\t%d\t%s\t%s\t%s\n";
+
+const int read_size = 36;
+
+const int min_overlap = 1;
+const int max_overlap = 35;
+
+unsigned long read_nr = 1;
+unsigned long unfiltered_read_nr = 1;
+
 int parse_gff(char* filename,FILE* fid,struct gene*** allGenes);
+void sort_genes(struct gene*** allGenes, int numGenes);
+void process_reads(FILE* reads_fs,struct gene*** allGenes,int numGenes, FILE* out_fs, FILE* unfiltered_out_fs);
+void combine_info(int exon_stop, int exon_start, Read** upstream, int up_size, Read** downstream, int down_size, FILE* out_fs,const char* gene_id, int exon_idx);
+int join_reads(int exon_stop, int exon_start, Read* up_read, Read* down_read, FILE* out_fs,const char* gene_id, int exon_idx);
+int fitting(char* up_prb, char* down_prb, int u_off, int d_off, int u_size, int d_size);
+Tuple join_seq(char* new_seq, char* up_seq,int u_off, int u_size, char* down_seq, int d_off, int d_size, int d_range);
 
-void process_reads(FILE* reads_fs,struct gene*** allGenes,int numGenes);
+static char *info = "Usage is:\n./filterReads gff reads output";
 
-void combine_info(int exon_stop, int exon_start, void** upstream, int up_size, void** downstream, int down_size);
+/*
+ * Some constants specifying the exact behavior of the filter
+ *
+ */
 
-static char *info = "Usage is:\n./filterReads gff reads";
+//#define _FDEBUG_ 0
+//#define DEBUG_READ 38603
 
-int main(int argc, char* argv[]) {
 
-   if(argc != 3) {
-      printf("%s\n",info);
-      exit(EXIT_FAILURE);
-   }
+//
+/*
+ * TODO:
+ * - Check strand -> done simple (only if equal)
+ * - check for [AC] and similar entries -> done simple (see function
+ */
 
-   //static size_t page_size;
-   // page_size = (size_t) sysconf (_SC_PAGESIZE);
-   int status;
-   int filenameSize = 256;
-   char *gff_filename = malloc(sizeof(char)*filenameSize);
-   char *reads_filename = malloc(sizeof(char)*filenameSize);
+#ifdef _FDEBUG_
+   if(read_nr == DEBUG_READ) {
+      printf("read nr %lu",read_nr);
+      printf("pos: %d %d %d %d\n",p_start,exon_stop,exon_start,p_stop);
+      printf("u/d range: %d %d\n",up_range,down_range);
+      printf("u/d size: %d %d\n",u_size,d_size);
+      printf("u/d off: %d %d\n",u_off,d_off);
+      printf("add_pos/down_range-d_size: %d %d\n",additional_pos,(down_range - d_size));
 
-   strncpy(gff_filename,argv[1],filenameSize);
-   strncpy(reads_filename,argv[2],filenameSize);
+      printf("******************\n");
 
-   FILE *gff_fs = fopen(gff_filename,"r");
-   FILE *reads_fs = fopen(reads_filename,"r");
+      printf("%s\n",up_read->seq);
+      //printf("%s\n",new_up_seq);
 
-   if(gff_fs == NULL) {
-      printf("Error: Could not open file: %s",gff_filename);
-      exit(EXIT_FAILURE);
-   }
+      printf("******************\n");
 
-   if(reads_fs == NULL) {
-      printf("Error: Could not open file: %s",reads_filename);
-      exit(EXIT_FAILURE);
-   }
+      printf("%s\n",down_read->seq);
+      //printf("%s\n",new_down_seq);
 
-   struct gene** allGenes;
-   int numGenes = parse_gff(gff_filename,gff_fs,&allGenes);
-   status = fclose(gff_fs);
-   if(status != 0)
-      printf("closing of gff filestream failed!\n");
+      printf("******************\n");
+      printf("%s\n",new_seq);
+      printf("%s\n",new_prb);
+      printf("%s\n",new_cal_prb);
+      printf("%s\n",new_chastity);
+   }
+#endif // _FDEBUG_
 
-   process_reads(reads_fs,&allGenes,numGenes);
+int combined_reads = 0;
 
-   status += fclose(reads_fs);
-   if(status != 0)
-      printf("closing of filestreams failed!\n");
-      
-   //free(allGenes);
-   free(gff_filename);
-   free(reads_filename);
-   return 0;
-}
+char current_strand;
 
+/*
+ *
+ *
+ */
 
-void process_reads(FILE* reads_fs,struct gene*** allGenes,int numGenes) {
+void process_reads(FILE* reads_fs,struct gene*** allGenes,int numGenes, FILE* out_fs, FILE* unfiltered_out_fs) {
    int status;
 
    int buffer_size= 64;
    int chr        = 0;
    int pos        = 0;
    char* seq      = malloc(sizeof(char)*buffer_size);
-   int id         = 0;
+   unsigned long id         = 0;
    char strand    = ' ';
    int mismatch   = 0;
-   int repetition = 0;
+   int occurrence = 0;
    int size       = 0;
    int cut        = 0;
    char* prb      = malloc(sizeof(char)*buffer_size);
@@ -88,232 +116,594 @@ void process_reads(FILE* reads_fs,struct gene*** allGenes,int numGenes) {
    char* chastity = malloc(sizeof(char)*buffer_size);
 
    int reads_fid = fileno(reads_fs);
-   size_t mmapAreaSize = 20000;
+   struct stat reads_stat;
+   if ( fstat(reads_fid,&reads_stat) == -1) {
+      perror("fstat");
+      exit(EXIT_FAILURE);
+   }
+   off_t reads_filesize = reads_stat.st_size;
+   printf("Reads file is of size %lu bytes\n",(unsigned long) reads_filesize);
+   int numReads = reads_filesize / 178.0;
+
+   void *reads_area = mmap (NULL,reads_filesize,PROT_READ,MAP_PRIVATE,reads_fid,0);
+   if (reads_area == MAP_FAILED) {
+      perror("mmap");
+      exit(EXIT_FAILURE);
+   }
+   close(reads_fid);
+   printf("Successfully mapped %lu bytes of reads file into memory\n",(unsigned long)reads_filesize);
+
+   char* lineBeginPtr = (char*) reads_area;
+   char* lineEndPtr = (char*) reads_area;
+   char* end_of_mapped_area = ((char*) reads_area) + reads_filesize;
 
-   void *reads_area = mmap (NULL,mmapAreaSize,PROT_READ|PROT_WRITE,MAP_PRIVATE,reads_fid,0);
-   if((long int) reads_area == -1)
-      printf("mmapping failed!\n");
+   while (*lineEndPtr != '\n' && lineEndPtr != end_of_mapped_area) lineEndPtr++;
+   lineEndPtr++;
 
-   void* linePtr = reads_area;
-   char* current_line = malloc(sizeof(char)*256);
+   char* current_line = malloc(sizeof(char)*512);
+   memset(current_line,0,512);
 
-   int SIZE = 500;
+   int SIZE = 5000;
    // initialize boundary arrays
-   void** upstream_end      = malloc(sizeof(void*)*SIZE);
-   void** upstream_overlap  = malloc(sizeof(void*)*SIZE);
-   void** downstream_start  = malloc(sizeof(void*)*SIZE);
-   void** downstream_overlap= malloc(sizeof(void*)*SIZE);
-   int ue,uo,ds,dov;
-   ue = uo = ds = dov = 0;
+   Read** upstream_overlap  = malloc(sizeof(Read*)*SIZE);
+   Read** downstream_overlap= malloc(sizeof(Read*)*SIZE);
+   int uov,dov;
+   uov = dov = 0;
 
    int skippedLinesCounter = 0;
 
+   int prev_exon_start = -1;
    int prev_exon_stop = -1;
    int cur_exon_start = -1;
 
-   int gene_idx;
-   for (gene_idx = 0; gene_idx < numGenes;) {
-      struct gene* currentGene = (*allGenes)[gene_idx];
+   unsigned long line_size = lineEndPtr - lineBeginPtr;
+   //printf("distance is %lu\n",line_size);
+   strncpy(current_line,lineBeginPtr,line_size);
+   current_line[line_size] = '\0';
+   //printf("%s test",current_line);
+
+   int gene_idx = 0;
+   int exon_idx = 1;
+   struct gene* currentGene = (*allGenes)[gene_idx];
+   char* gene_id = currentGene->id;
+
+   int skippedReadCtr = 0;
+   int uselessReadCtr = 0;
+   int exonicReadCtr = 0;
+
+   int currentOverlapCtr = 0;
+   int previousOverlapCtr = 0;
+
+   int multioccurReadCtr = 0;
+
+   Read* currentRead;
+   int up_idx, down_idx;
+
+   int readCtr = 0;
+   int wrong_strand_ctr = 0;
+   int read_within_gene_ctr = 0;
+   int read_outside_gene_ctr = 0;
+   int read_start, read_stop;
+   // start of the parsing loop 
+  
+   //static char *all_strands = "+-";
+   //static char *all_strands = "DP";
+   //int strand_idx;
+   //for(strand_idx=0;strand_idx<2;strand_idx++) {
+   //   char current_strand = all_strands[strand_idx];
+
+      while(1) {
+         if (gene_idx == numGenes || strcmp(current_line,"") == 0)
+            break;
+
+         gene_id = currentGene->id;
+
+         if (readCtr != 0 && readCtr % 1000000 == 0) {
+            printf("Processed %d/%d genes and %d/%d reads.\n",gene_idx,numGenes,readCtr,numReads);
+            printf("%d reads in total while %d reads where skipped.\n",readCtr,skippedLinesCounter);
+            printf("%d were totally intronic. %d were outside of genes and %d were occurring on several positions.\n",uselessReadCtr,skippedReadCtr,multioccurReadCtr);
+            printf("%d reads were useless in total\n",uselessReadCtr+skippedReadCtr+multioccurReadCtr);
+            printf("\t%d useless reads\n",uselessReadCtr);
+            printf("\t%d skipped reads\n",skippedReadCtr);
+            printf("\t%d multioccurring\n",multioccurReadCtr);
+            printf("\t%d wrong_strand\n",wrong_strand_ctr);
+            printf("%d within gene\n",read_within_gene_ctr);
+            printf("%d outside gene\n",read_outside_gene_ctr);
+            printf("%d reads were totally exonic\n",exonicReadCtr);
+            printf("%d reads overlap with prev. exon. %d reads overlap with current exon\n",previousOverlapCtr,currentOverlapCtr);
+            printf("%d reads where newly combined from two original reads\n",combined_reads);
+            printf("Total used reads: %d (some may not be combined)\n",exonicReadCtr+combined_reads);
+         }
 
-      int exon_idx;
-      for(exon_idx=1;exon_idx<currentGene->num_exons;exon_idx++) {
+         // pos of the reads is one-based
+         status = sscanf(current_line,line_format,&chr,&pos,seq,&id,&strand,&mismatch,&occurrence,&size,&cut,prb,cal_prb,chastity);
+         if (status < 12) {
+            skippedLinesCounter++;
+            goto next_read;
+         }
 
-         combine_info(prev_exon_stop,cur_exon_start,upstream_end,ue,downstream_overlap,dov);
-         combine_info(prev_exon_stop,cur_exon_start,upstream_overlap,uo,downstream_start,ds);
+         // if the read is occurring several times elsewhere then get rid of it 
+         if ( occurrence != 1 ) {
+            multioccurReadCtr++;
+            goto next_read;
+         }
 
-         prev_exon_stop = currentGene->exon_stops[exon_idx-1];
-         cur_exon_start = currentGene->exon_starts[exon_idx];
+         // define read start and stop positions
+         read_start = pos;
+         read_stop  = pos + read_size-1;
 
-         if (cur_exon_start - prev_exon_stop < 6)
-            continue;
+         if( strand != current_strand ) {
+            wrong_strand_ctr++;
+            goto next_read;
+         }
 
-         ue = uo = ds = dov = 0;
+         FA(strlen(seq) >= read_size);
 
-         label:
+         FA(currentGene != 0);
 
-         current_line = strncpy(current_line,linePtr,256);
-         if (strcmp(current_line,"") == 0)
-            goto end;
+         if ( currentGene->start <= read_start && read_stop <= currentGene->stop) { // read is within gene borders
+            read_within_gene_ctr++;
 
-         status = sscanf(current_line,"%d\t%d\t%s\t%d\t%c\t%d\t%d\t%d\t%d\t%s\t%s\t%s\n",
-         &chr,&pos,seq,&id,&strand,&mismatch,&repetition,&size,&cut,prb,cal_prb,chastity);
-         if (status < 12) {
-            //printf("skipped line is %s\n",current_line);
-            skippedLinesCounter++;
-         }
+            exon_label:
 
-         //printf("%d\t%d\t%s\t%d\t%c\t%d\t%d\t%d\t%d\t%s\t%s\t%s\n",
-         //chr,pos,seq,id,strand,mismatch,repetition,size,cut,prb,cal_prb,chastity);
-         //printf("read position: %d gene start/stop: %d-%d\n ",pos,currentGene->start,currentGene->stop);
-
-         if (currentGene->start <= pos && pos+35 <= currentGene->stop) {
-            //printf("gene boundaries: %d %d, pos: %d linePtr %d\n",currentGene->start,currentGene->stop,pos,linePtr);
-            // upstream ending
-            if (pos+35 == prev_exon_stop) {
-               upstream_end[ue] = linePtr;
-               ue++;
-            } else {
-
-               // upstream overlapping
-               if (prev_exon_stop - pos >= 6 && prev_exon_stop - pos <= 30) {
-                  upstream_overlap[uo] = linePtr;
-                  uo++;
+            if (exon_idx == currentGene->num_exons) {
+               gene_idx++;
+               exon_idx = 1;
+               currentGene = (*allGenes)[gene_idx];
+               while( (currentGene == 0 || currentGene->strand != current_strand) && gene_idx < numGenes) {
+                  currentGene = (*allGenes)[gene_idx];
+                  gene_idx++;
                }
+               continue;
             }
 
-            // downstream starting
-            if (pos == cur_exon_start) {
-               downstream_start[ds] = linePtr;
-               ds++;
-            } else {
+            prev_exon_start = currentGene->exon_starts[exon_idx-1];
+            prev_exon_stop = currentGene->exon_stops[exon_idx-1];
+            cur_exon_start = currentGene->exon_starts[exon_idx];
+
+            //printf("id: %s,exon_idx: %d intron: %d %d read start/stop: %d / %d\n",currentGene->id,exon_idx,prev_exon_stop,cur_exon_start,read_start,read_stop);
+
+            if ( (cur_exon_start - prev_exon_stop - 1) < min_overlap || cur_exon_start < read_start ) { // go to next exon
 
-               // downstream overlapping
-               if (cur_exon_start - pos >= 6 && cur_exon_start - pos <= 30 ) {
-                  downstream_overlap[dov] = linePtr;
-                  dov++;
+               if (uov != 0 && dov != 0)
+                  combine_info(prev_exon_stop,cur_exon_start,upstream_overlap,uov,downstream_overlap,dov,out_fs,gene_id,exon_idx);
+
+               for(up_idx=0;up_idx<uov;up_idx++) {
+                  free_read(upstream_overlap[up_idx]);
+                  free(upstream_overlap[up_idx]);
+               }
+
+               for(down_idx=0;down_idx<dov;down_idx++) {
+                  free_read(downstream_overlap[down_idx]);
+                  free(downstream_overlap[down_idx]);
                }
+
+               uov = dov = 0;
+
+               exon_idx++;
+               goto exon_label;
             }
 
-            while (*(char*)linePtr != '\n') linePtr++;
-            linePtr++;
-            goto label;
+            if ( prev_exon_start <= read_start && read_stop <= prev_exon_stop ) { // read is inside previous exon
 
-         } else {
+               // output of unused i.e. unspliced reads
+               fprintf(unfiltered_out_fs,"%lu\t%d\t%c\t%s\t%d\t%d\t%s\t%s\t%s\t%s\t%d\t%d\t%d\t%d\t%d\n",
+               unfiltered_read_nr,chr,strand,seq,0,read_size,prb,cal_prb,chastity,gene_id,read_start,-1,-1,read_stop,-1);
+               unfiltered_read_nr++;
+               
+               exonicReadCtr++;
+               goto next_read;
+            }
 
-            if (currentGene->stop < pos) {
-               //printf("read is too far downstream\n");
-               break;
+            if ( read_stop < prev_exon_stop ) { // go to next read 
+               //printf("%d\t%d\t%d\n",read_start,prev_exon_start,prev_exon_stop);
+               //if( exon_idx > 1) {
+               //   printf("%d\t%d\n", currentGene->exon_starts[exon_idx-2], currentGene->exon_stops[exon_idx-2]);
+               //   printf("---\n");
+               //}
+
+               uselessReadCtr++;
+               goto next_read;
+            }
+
+            // if this position is reached the read is somehow overlapping or
+            // exactly on the exon boundary.
+            if ( (prev_exon_stop - read_start + 1) >= min_overlap && (prev_exon_stop - read_start + 1) <= max_overlap ) { // read overlaps with previous exon boundary
+               //printf("%s\n",current_line);
+               previousOverlapCtr++;
+               currentRead = create_read(chr,read_start,seq,id,strand,mismatch,occurrence,size,cut,prb,cal_prb,chastity);
+               assert (uov < SIZE);
+               upstream_overlap[uov] = currentRead;
+               uov++;
+               goto next_read;
+            }
+         
+            if ( ( read_stop - cur_exon_start + 1) >= min_overlap && (read_stop - cur_exon_start + 1) <= max_overlap ) { // read overlaps with current exon boundary
+               //printf("%s\n",current_line);
+               currentOverlapCtr++;
+               currentRead = create_read(chr,read_start,seq,id,strand,mismatch,occurrence,size,cut,prb,cal_prb,chastity);
+               assert (dov < SIZE);
+               downstream_overlap[dov] = currentRead;
+               dov++;
+               goto next_read;
             }
 
-            //printf("read is too far upstream\n");
-            while (*(char*)linePtr != '\n') linePtr++;
-            linePtr++;
-            goto label;
+            uselessReadCtr++;
+            goto next_read; // read was not useful i.e. not overlapping/starting at exon boundaries
+
+         } else { // read is not within gene borders
+            read_outside_gene_ctr++;
+
+            if (uov != 0 && dov != 0)
+               combine_info(prev_exon_stop,cur_exon_start,upstream_overlap,uov,downstream_overlap,dov,out_fs,gene_id,exon_idx);
+
+            for(up_idx=0;up_idx<uov;up_idx++) {
+               free_read(upstream_overlap[up_idx]);
+               free(upstream_overlap[up_idx]);
+            }
+
+            for(down_idx=0;down_idx<dov;down_idx++) {
+               free_read(downstream_overlap[down_idx]);
+               free(downstream_overlap[down_idx]);
+            }
+
+            uov = dov = 0;
+
+            if ( currentGene->stop < read_stop ) { // go to next gene
+               gene_idx++;
+               exon_idx = 1;
+               currentGene = (*allGenes)[gene_idx];
+               while( currentGene == 0 && gene_idx < numGenes) {
+                  currentGene = (*allGenes)[gene_idx];
+                  gene_idx++;
+               }
+               //printf("currentGene->start / currentGene->stop %d/%d pos is %d\n",currentGene->start,currentGene->stop,pos);
+               continue;
+            }
+
+            if ( read_start < currentGene->start ) { // go to next read
+               skippedReadCtr++;
+               
+               next_read:
+               
+               lineBeginPtr = lineEndPtr;
+               while (*(char*)lineEndPtr != '\n' && lineEndPtr != end_of_mapped_area) lineEndPtr++;
+               lineEndPtr++;
+               readCtr += 1;
+               current_line = strncpy(current_line,lineBeginPtr,lineEndPtr-lineBeginPtr);
+               current_line[lineEndPtr-lineBeginPtr] = '\0';
+               continue;
+            }
          }
       }
 
-      gene_idx++;
+   //} // end of for all strands
+
+   if (uov != 0 && dov != 0)
+      combine_info(prev_exon_stop,cur_exon_start,upstream_overlap,uov,downstream_overlap,dov,out_fs,gene_id,exon_idx);
+
+   for(up_idx=0;up_idx<uov;up_idx++) {
+      free_read(upstream_overlap[up_idx]);
+      free(upstream_overlap[up_idx]);
    }
 
-   end:
+   for(down_idx=0;down_idx<dov;down_idx++) {
+      free_read(downstream_overlap[down_idx]);
+      free(downstream_overlap[down_idx]);
+   }
+
+   uov = dov = 0;
 
-   free(upstream_end);
    free(upstream_overlap);
-   free(downstream_start);
    free(downstream_overlap);
 
-   printf("skipped %d lines.\n",skippedLinesCounter);
-
-   status = munmap(reads_area,mmapAreaSize);
+   printf("Processed %d reads in total while %d reads where skipped.\n",readCtr,skippedLinesCounter);
+   printf("%d were totally intronic. %d were outside of genes and %d were occurring on several positions.\n",uselessReadCtr,skippedReadCtr,multioccurReadCtr);
+   printf("%d reads were useless in total\n",uselessReadCtr+skippedReadCtr+multioccurReadCtr);
+   printf("\t%d useless reads\n",uselessReadCtr);
+   printf("\t%d skipped reads\n",skippedReadCtr);
+   printf("\t%d multioccurring\n",multioccurReadCtr);
+   printf("\t%d wrong_strand\n",wrong_strand_ctr);
+   printf("%d reads were totally exonic\n",exonicReadCtr);
+   printf("%d reads overlap with prev. exon. %d reads overlap with current exon\n",previousOverlapCtr,currentOverlapCtr);
+   printf("%d reads where newly combined from two original reads\n",combined_reads);
+   printf("Total used reads: %d (some may not be combined)\n",exonicReadCtr+combined_reads);
+
+   status = munmap(reads_area,reads_filesize);
    if(status != 0)
-      printf("munmap failed!\n");
+      perror("munmap");
 
+   free(current_line);
    free(seq);
    free(prb);
    free(cal_prb);
    free(chastity);
 }
 
-void combine_info(int exon_stop, int exon_start, void** upstream, int up_size, void** downstream, int down_size) {
-   //printf("up_/down_size %d %d\n",up_size,down_size);
 
-   if (up_size == 0 || down_size == 0 || exon_stop == -1)
-      return;
+void combine_info(int exon_stop, int exon_start, Read** upstream, int up_size, Read** downstream, int down_size, FILE* out_fs,const char* gene_id, int exon_idx) {
+   int up_idx, down_idx, success;
 
-   int up_idx, down_idx, status;
-   char* upstream_line = malloc(sizeof(char)*256);
-   char* downstream_line = malloc(sizeof(char)*256);
+   char* up_used_flag = calloc(up_size,sizeof(char));
+   char* down_used_flag = calloc(down_size,sizeof(char));
 
-   int buffer_size= 64;
+   Read* currentUpRead;
+   Read* currentDownRead;
 
-   int up_chr        = 0;
-   int up_pos        = 0;
-   char* up_seq      = malloc(sizeof(char)*buffer_size);
-   int up_id         = 0;
-   char up_strand    = ' ';
-   int up_mismatch   = 0;
-   int up_repetition = 0;
-   int up_sz       = 0;
-   int up_cut        = 0;
-   char* up_prb      = malloc(sizeof(char)*buffer_size);
-   char* up_cal_prb  = malloc(sizeof(char)*buffer_size);
-   char* up_chastity = malloc(sizeof(char)*buffer_size);
-
-   int down_chr        = 0;
-   int down_pos        = 0;
-   char* down_seq      = malloc(sizeof(char)*buffer_size);
-   int down_id         = 0;
-   char down_strand    = ' ';
-   int down_mismatch   = 0;
-   int down_repetition = 0;
-   int down_sz         = 0;
-   int down_cut        = 0;
-   char* down_prb      = malloc(sizeof(char)*buffer_size);
-   char* down_cal_prb  = malloc(sizeof(char)*buffer_size);
-   char* down_chastity = malloc(sizeof(char)*buffer_size);
-
-   int new_chr        = 0;
-   int new_pos        = 0;
-   char* new_seq      = malloc(sizeof(char)*buffer_size);
-   int new_id         = 0;
-   char new_strand    = ' ';
-   char* new_prb        = malloc(sizeof(char)*buffer_size);
-   char* new_cal_prb    = malloc(sizeof(char)*buffer_size);
-   char* new_chastity   = malloc(sizeof(char)*buffer_size);
-
-   up_idx=0;
-   down_idx=0;
-   while(1) {
-      //printf("up_/down_idx %d %d\n",up_idx,down_idx);
-
-      if (up_idx == up_size || down_idx == down_size)
-         break;
-
-      strncpy(upstream_line,upstream[up_idx],256);
-      status = sscanf(upstream_line,"%d\t%d\t%s\t%d\t%c\t%d\t%d\t%d\t%d\t%s\t%s\t%s\n",
-      &up_chr,&up_pos,up_seq,&up_id,&up_strand,&up_mismatch,&up_repetition,&up_sz,
-      &up_cut,up_prb,up_cal_prb,up_chastity);
-      
-      strncpy(downstream_line,downstream[down_idx],256);
-      status = sscanf(downstream_line,"%d\t%d\t%s\t%d\t%c\t%d\t%d\t%d\t%d\t%s\t%s\t%s\n",
-      &down_chr,&down_pos,down_seq,&down_id,&down_strand,&down_mismatch,&down_repetition,&down_sz,
-      &down_cut,down_prb,down_cal_prb,down_chastity);
-
-      new_prb[0] = '\0';
-      new_cal_prb[0] = '\0';
-      new_chastity[0] = '\0';
-         
-      // is downstream overlapping
-      if (up_pos+35 == exon_stop) {
-         int overlap = exon_start - down_pos;
-         //printf("overlap is %d\n",overlap);
-         //printf("pos are: %d %d\n",up_pos,down_pos);
+   for(up_idx=0;up_idx<up_size;up_idx++) {
+      if( up_used_flag[up_idx] == 1)
+         continue;
 
-         strncat(new_prb,up_prb+(36-overlap),overlap);
-         strncat(new_cal_prb,up_cal_prb+(36-overlap),overlap);
-         strncat(new_chastity,up_chastity+(36-overlap),overlap);
+      currentUpRead = upstream[up_idx];
 
-         strncat(new_prb,down_prb+overlap,36-overlap);
-         strncat(new_cal_prb,down_cal_prb+overlap,36-overlap);
-         strncat(new_chastity,down_chastity+overlap,36-overlap);
+      for(down_idx=0;down_idx<down_size;down_idx++) {
 
-         //printf("up_prb: %s\n",up_prb);
-         //printf("down_prb: %s\n",down_prb);
-         //printf("new_prb: %s\n",new_prb);
+         if( up_used_flag[up_idx] == 1 || down_used_flag[down_idx] == 1)
+            continue;
 
-      // is upstream overlapping
-      } else {
+         currentDownRead = downstream[down_idx];
 
-      }
+         if(currentUpRead->strand != currentDownRead->strand)
+            continue;
+
+         success = join_reads(exon_stop,exon_start,currentUpRead,currentDownRead,out_fs,gene_id,exon_idx);
          
-      up_idx++;
-      down_idx++;
+         if(success == 1) {
+            up_used_flag[up_idx] = 1;
+            down_used_flag[down_idx] = 1;
+         }
+      }
+   }
+
+   free(up_used_flag);
+   free(down_used_flag);
+}
+
+/*
+ * Now we join the candidate reads wherever possible according to the following
+ * scheme:
+ *
+ * ACGTACGTCA GTXXXXXXXXAG ACGTAGACGT
+ * p1       e1             e2       p2  
+ *
+ * 
+ *
+ *
+ */
+
+int join_reads(int exon_stop, int exon_start, Read* up_read, Read* down_read, FILE* out_fs,const char* gene_id, int exon_idx) {
+   // range of possible sequence length on exon side
+   int up_read_start = up_read->pos;
+   //int up_read_stop  = up_read->pos+read_size-1;
+
+   int down_read_start = down_read->pos;
+   int down_read_stop  = down_read->pos+read_size-1;
+
+   int up_range   = exon_stop - up_read_start + 1;
+   int down_range = down_read_stop - exon_start + 1;
+   int retval;
+
+   int u_size, d_size;
+   u_size = d_size = -1;
+
+   if(up_range+down_range < read_size)
+      return 0;
+
+   if (read_nr % 2 != 0) {
+      d_size = down_range;
+      u_size = read_size - d_size;
+   } else {
+      u_size = up_range;
+      d_size = read_size - u_size;
+   }
+
+   if( u_size > up_range || d_size > down_range)
+      return 0;
+
+   const int p_start  = exon_stop  - u_size + 1;
+   const int p_stop   = exon_start + d_size - 1;
+
+   int u_off = p_start - up_read_start;
+   int d_off = exon_start - down_read_start;
+
+   FA(u_off >= 0);
+   FA(d_off >= 0);
+
+   FA( exon_stop - p_start + p_stop - exon_start + 2 == read_size);
+   FA( u_size + d_size == read_size );
+
+   // seems reasonable up to here
+
+   int buf_size = 4*read_size;
+   char* new_seq = malloc(sizeof(char)*buf_size);
+   memset(new_seq,'z',sizeof(char)*buf_size);
+
+   Tuple jinfo = join_seq(new_seq,up_read->seq,u_off,u_size,down_read->seq,d_off,d_size,down_range);
+
+   int cut_pos = jinfo.first;
+   int additional_pos = jinfo.second;
+
+   buf_size = read_size+1+additional_pos;
+
+   char* new_prb        = malloc(sizeof(char)*buf_size);
+   char* new_cal_prb    = malloc(sizeof(char)*buf_size);
+   char* new_chastity   = malloc(sizeof(char)*buf_size);
+
+   if( jinfo.first == -1 ) {
+      retval = 0;
+      goto free;
+   }
+
+   if( additional_pos > (down_range - d_size) ) {
+      retval = 0;
+      goto free;
+   }
+
+   strncpy(new_prb, up_read->prb+u_off, u_size);
+   strncpy(new_prb+u_size, down_read->prb+d_off, d_size+additional_pos);
+   new_prb[read_size+additional_pos] = '\0';
+
+   strncpy(new_cal_prb, up_read->cal_prb+u_off, u_size);
+   strncpy(new_cal_prb+u_size, down_read->cal_prb+d_off, d_size+additional_pos);
+   new_cal_prb[read_size+additional_pos] = '\0';
+
+   strncpy(new_chastity, up_read->chastity+u_off, u_size);
+   strncpy(new_chastity+u_size, down_read->chastity+d_off, d_size+additional_pos);
+   new_chastity[read_size+additional_pos] = '\0';
+
+
+   int status = 1; //fitting(up_read->prb,down_read->prb,u_off,d_off,u_size,d_size);
+
+   if(status != 1) {
+      retval = 0;
+      goto free;
+   }
+
+   retval = status;
+
+   //fprintf(out_fs,"%d\t%d\t%c\t%s\t%d\t%d\t%s\t%s\t%s\t%s\t%d\t%d\t%d\t%d\t%s\t%s\n",
+   //   read_nr,up_read->chr,up_read->strand,new_seq,cut_pos,read_size,new_prb,new_cal_prb,new_chastity,gene_id,p_start,exon_stop,exon_start,p_stop,up_read->seq,down_read->seq);
+
+   //fprintf(out_fs,"%lu\t%d\t%c\t%s\t%d\t%d\t%s\t%s\t%s\t%s\t%d\t%d\t%d\t%d\t%d\n",
+   //   read_nr,up_read->chr,up_read->strand,new_seq,cut_pos,read_size,new_prb,new_cal_prb,new_chastity,gene_id,p_start,exon_stop,exon_start,p_stop,u_size);
+
+   fprintf(out_fs,"%lu\t%d\t%c\t%s\t%d\t%d\t%s\t%s\t%s\t%s\t%d\t%d\t%d\t%d\t%d\n",
+      read_nr,up_read->chr,up_read->strand,new_seq,cut_pos,read_size,new_prb,new_cal_prb,new_chastity,gene_id,p_start,exon_stop,exon_start,p_stop,u_size);
+
+   read_nr++;
+   combined_reads++;
+
+   free:
+   free(new_seq);
+   free(new_prb);
+   free(new_cal_prb);
+   free(new_chastity);
+
+   return retval;
+}
+
+
+void print_read(Read* cRead) {
+   printf(line_format,
+   cRead->chr, cRead->pos, cRead->seq, cRead->id,
+   cRead->strand, cRead->mismatch, cRead->occurrence,
+   cRead->size, cRead->cut, cRead->prb, cRead->cal_prb,
+   cRead->chastity);
+}
+
+
+void open_file(const char* filename, const char* mode, FILE** fs) {
+   *fs = fopen(filename,mode);
+   if(*fs == NULL) {
+      printf("Error: Could not open file: %s",filename);
+      exit(EXIT_FAILURE);
    }
 }
 
 /*
- * TODO
- * - Check strand
- * - check repetition
+ * The program expects 7 arguments, namely:
+ *
+ * - The strand to be used
+ * - The filename of the gff file
+ * - The filename of the reads file
+ * - The name of the spliced reads ouput file
+ * - The name of the unspliced reads ouput file
+ * - The offset for counting new spliced reads
+ * - The offset for counting new unspliced reads
  *
  */
+
+int main(int argc, char* argv[]) {
+
+   if(argc != 8) {
+      printf("%s\n",info);
+      exit(EXIT_FAILURE);
+   }
+
+   int status;
+   int filenameSize = 256;
+   char* gff_filename = malloc(sizeof(char)*filenameSize);
+
+   current_strand = argv[1][0];
+   printf("current strand is %c\n",current_strand);
+   strncpy(gff_filename,argv[2],filenameSize);
+
+   FILE *gff_fs;
+   FILE *reads_fs;
+   FILE *out_fs;
+   FILE *unfiltered_out_fs;
+
+   // open file streams for all needed input/output files
+   open_file(argv[2],"r",&gff_fs);
+   open_file(argv[3],"r",&reads_fs);
+   open_file(argv[4],"w",&out_fs);
+   open_file(argv[5],"w",&unfiltered_out_fs);
+
+   read_nr = strtoul(argv[6],NULL,10);
+   read_nr++;
+
+   unfiltered_read_nr = strtoul(argv[7],NULL,10);
+   unfiltered_read_nr++;
+
+   // allocate and load all genes and then close the gff file stream
+   struct gene** allGenes;
+   int numGenes = parse_gff(gff_filename,gff_fs,&allGenes);
+   status = fclose(gff_fs);
+   free(gff_filename);
+   if(status != 0)
+      printf("closing of gff filestream failed!\n");
+
+   printf("Successfully parsed gff file! Found %d genes.\n",numGenes);
+
+   // check if allGenes is sorted. if not throw away those genes that do not
+   // occur in the sorted order
+   int g_idx;
+   struct gene* currentGene = 0;
+   int nulled_genes=0;
+   int old_gene_stop = -1;
+   for(g_idx=0;g_idx<numGenes;g_idx++) {
+      currentGene = allGenes[g_idx];
+
+      if (! (currentGene->start < currentGene->stop))
+         printf("Invalid positions for gene %s!\n",currentGene->id);
+
+      if (! (old_gene_stop <  currentGene->start ) ) {
+         old_gene_stop = currentGene->stop;
+         allGenes[g_idx] = 0;
+         nulled_genes++;
+         continue;
+      }
+      old_gene_stop = currentGene->stop;
+   }
+
+   printf("Found %d unordered genes.\n",nulled_genes);
+   int gidx, eidx;
+   int exon_cov = 0;
+   for(gidx=0;gidx<numGenes;gidx++) {
+      if (allGenes[gidx] == 0)
+         continue;
+
+      for(eidx=0;eidx<allGenes[gidx]->num_exons;eidx++) {
+         exon_cov += allGenes[gidx]->exon_stops[eidx] - allGenes[gidx]->exon_starts[eidx];
+   }}
+   printf("Exon coverage is %f\n",(double)exon_cov/30432563);
+
+   // now that we loaded all neccessary data we start to process the reads
+   process_reads(reads_fs,&allGenes,numGenes,out_fs,unfiltered_out_fs);
+
+   // free all allocated ressources
+   for(g_idx=0;g_idx<numGenes;g_idx++) {
+      if(allGenes[g_idx] != 0) {
+         free_gene(allGenes[g_idx]);
+         free(allGenes[g_idx]);
+      }
+   }
+   free(allGenes);
+
+   status = fclose(reads_fs);
+   status = fclose(out_fs);
+   if(status != 0)
+      perror("fclose");
+      
+   return 0;
+}