]> git.donarmstrong.com Git - biopieces.git/blob - code_c/Maasha/src/bed2fixedstep.c
refactoring of assemble_pairs
[biopieces.git] / code_c / Maasha / src / bed2fixedstep.c
1 #include "common.h"
2 #include "barray.h"
3
4 #define BUFFER_SIZE 1024
5 #define BED_CHR_MAX 16
6 #define BED_QID_MAX 256
7 #define BARRAY_SIZE ( 1 << 16 )
8
9
10 static void usage()
11 {
12     fprintf( stderr,
13         "\n"
14         "bed2fixedstep - collapse overlapping BED entries with only one\n"
15         "chromosome using a score based on the last number following a _\n"
16         "in the 'name' column. if no such number is found 1 is used.\n"
17         "\n"
18         "Usage: bed2fixedstep < <BED file(s)> > <fixedstep file>\n\n"
19     );
20
21     exit( EXIT_FAILURE );
22 }
23
24
25 long get_score( char *str )
26 {
27     /* Martin A. Hansen, December 2008. */
28
29     /* Extract the last decimal number after _ 
30      * in a string and return that. If no number
31      * was found return 1. */
32
33     char *c;
34     long  score = 1;
35
36     if ( ( c = strrchr( str, '_' ) ) != NULL ) {
37         score = strtol( &c[ 1 ], NULL , 10 );
38     }
39
40     return score;
41 }
42
43
44 int main( int argc, char *argv[] )
45 {
46     char       buffer[ BUFFER_SIZE ];
47     char       chr[ BED_CHR_MAX ];
48     char       q_id[ BED_QID_MAX ];
49     size_t     beg   = 0;
50     size_t     end   = 0;
51     uint       score = 0;
52     size_t     pos   = 0;
53     size_t     i     = 0;
54     barray    *ba    = barray_new( BARRAY_SIZE );
55
56     if ( isatty( fileno( stdin ) ) ) {
57         usage();
58     }
59     
60     while ( fgets( buffer, sizeof( buffer ), stdin ) )
61     {
62 //        printf( "BUFFER: %s\n", buffer );
63
64         if ( sscanf( buffer, "%s\t%zu\t%zu\t%s", chr, &beg, &end, q_id ) == 4 )
65         {
66 //            printf( "chr: %s   beg: %zu   end: %zu   q_id: %s\n", chr, beg, end, q_id );
67
68             score = ( uint ) get_score( q_id );
69
70             barray_interval_inc( ba, beg, end - 1, score );
71         }
72     }
73
74 //    barray_print( ba );
75
76     pos = 0;
77     beg = 0;
78     end = 0;
79
80     while ( barray_interval_scan( ba, &pos, &beg, &end ) )
81     {
82 //        printf( "chr: %s   pos: %zu   beg: %zu   end: %zu\n", chr, pos, beg, end );
83
84         printf( "fixedStep chrom=%s start=%zu step=1\n", chr, beg + 1 );
85
86         for ( i = beg; i <= end; i++ ) {
87             printf( "%u\n", ba->array[ i ] );
88         }
89     }
90
91     return EXIT_SUCCESS;
92 }
93