]> git.donarmstrong.com Git - biopieces.git/blob - code_perl/Maasha/Biopieces.pm
added ucscMakeTracks -b run to remove_ucsc_tracks
[biopieces.git] / code_perl / Maasha / Biopieces.pm
1 package Maasha::Biopieces;
2
3
4 # Copyright (C) 2007-2008 Martin A. Hansen.
5
6 # This program is free software; you can redistribute it and/or
7 # modify it under the terms of the GNU General Public License
8 # as published by the Free Software Foundation; either version 2
9 # of the License, or (at your option) any later version.
10
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19
20 # http://www.gnu.org/copyleft/gpl.html
21
22
23 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> DESCRIPTION <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
24
25
26 # Routines for manipulation, parsing and emitting of human/machine readable biopieces records.
27
28
29 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
30
31
32 use strict;
33 use Data::Dumper;
34 use Getopt::Long qw( :config bundling );
35 use Time::HiRes qw( gettimeofday );
36 use Storable qw( dclone );
37 use Maasha::Config;
38 use Maasha::Common;
39 use Maasha::Fasta;
40 use Maasha::Align;
41 use Maasha::Matrix;
42 use Maasha::Match;
43 use Maasha::EMBL;
44 use Maasha::Stockholm;
45 use Maasha::Seq;
46 use Maasha::Patscan;
47 use Maasha::Plot;
48 use Maasha::Calc;
49 use Maasha::UCSC;
50 use Maasha::NCBI;
51 use Maasha::GFF;
52 use Maasha::TwoBit;
53 use Maasha::Solid;
54 use Maasha::Solexa;
55 use Maasha::SQL;
56 use Maasha::Gwiki;
57
58 use vars qw( @ISA @EXPORT_OK );
59
60 require Exporter;
61
62 @ISA = qw( Exporter );
63
64 @EXPORT_OK = qw(
65     read_stream
66     write_stream
67     get_record
68     put_record
69 );
70
71 use constant {
72     SEQ_NAME => 0,
73     SEQ      => 1,
74 };
75
76
77 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> SIGNAL HANDLER <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
78
79
80 $SIG{ '__DIE__' } = \&sig_handler;
81 $SIG{ 'INT' }     = \&sig_handler;
82 $SIG{ 'TERM' }    = \&sig_handler;
83
84
85 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> GLOBALS <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
86
87
88 my ( $script, $BP_TMP );
89
90 $script  = Maasha::Common::get_scriptname();
91 $BP_TMP  = Maasha::Common::get_tmpdir();
92
93
94 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> LOG <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
95
96
97 my $log_global = Maasha::Common::append_open( "$ENV{ 'BP_LOG' }/biopieces.log" );
98 my $log_local  = Maasha::Common::append_open( "$ENV{ 'HOME' }/.biopieces.log" );
99
100 $log_global->autoflush( 1 );
101 $log_local->autoflush( 1 );
102
103 &log( $log_global, $script, \@ARGV );
104 &log( $log_local, $script, \@ARGV );
105
106 close $log_global;
107 close $log_local;
108
109
110 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> RUN SCRIPT <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
111
112
113 run_script( $script );
114
115
116 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> SUBROUTINES <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
117
118
119 sub log
120 {
121     # Martin A. Hansen, January 2008.
122
123     # Log messages to logfile.
124
125     my ( $fh,       # filehandle to logfile
126          $script,   # script name
127          $argv,     # reference to @ARGV
128        ) = @_;
129
130     # Returns nothing.
131
132     my ( $time_stamp, $user );
133
134     $time_stamp = Maasha::Common::time_stamp();
135
136     $user = $ENV{ 'USER' };
137
138     $script = "biopieces" if $script eq "-e";
139
140     print $fh "$time_stamp\t$user\t$script ", join( " ", @{ $argv } ), "\n";
141 }
142
143
144 sub run_script
145 {
146     # Martin A. Hansen, August 2007.
147
148     # Run a specific script.
149
150     my ( $script,   # script name
151        ) = @_;
152
153     # Returns nothing.
154
155     my ( $t0, $t1, $options, $in, $out );
156
157     $t0 = gettimeofday();
158
159     $options = get_options( $script );
160
161     $options->{ "SCRIPT" } = $script;
162
163     if ( $script ne "list_biopieces" and $script ne "list_genomes" ) {
164         $script = "print_usage" if ( -t STDIN and keys %{ $options } <= 1 or $options->{ 'help' } );
165     }
166
167     $in  = read_stream( $options->{ "stream_in" } );
168     $out = write_stream( $options->{ "stream_out" } );
169
170     if    ( $script eq "print_usage" )              { script_print_usage(               $in, $out, $options ) }
171     elsif ( $script eq "list_biopieces" )           { script_list_biopieces(            $in, $out, $options ) }
172     elsif ( $script eq "list_genomes" )             { script_list_genomes(              $in, $out, $options ) }
173     elsif ( $script eq "read_fasta" )               { script_read_fasta(                $in, $out, $options ) }
174     elsif ( $script eq "read_tab" )                 { script_read_tab(                  $in, $out, $options ) }
175     elsif ( $script eq "read_psl" )                 { script_read_psl(                  $in, $out, $options ) }
176     elsif ( $script eq "read_bed" )                 { script_read_bed(                  $in, $out, $options ) }
177     elsif ( $script eq "read_fixedstep" )           { script_read_fixedstep(            $in, $out, $options ) }
178     elsif ( $script eq "read_blast_tab" )           { script_read_blast_tab(            $in, $out, $options ) }
179     elsif ( $script eq "read_embl" )                { script_read_embl(                 $in, $out, $options ) }
180     elsif ( $script eq "read_stockholm" )           { script_read_stockholm(            $in, $out, $options ) }
181     elsif ( $script eq "read_phastcons" )           { script_read_phastcons(            $in, $out, $options ) }
182     elsif ( $script eq "read_soft" )                { script_read_soft(                 $in, $out, $options ) }
183     elsif ( $script eq "read_gff" )                 { script_read_gff(                  $in, $out, $options ) }
184     elsif ( $script eq "read_2bit" )                { script_read_2bit(                 $in, $out, $options ) }
185     elsif ( $script eq "read_solexa" )              { script_read_solexa(               $in, $out, $options ) }
186     elsif ( $script eq "read_solid" )               { script_read_solid(                $in, $out, $options ) }
187     elsif ( $script eq "read_mysql" )               { script_read_mysql(                $in, $out, $options ) }
188     elsif ( $script eq "read_ucsc_config" )         { script_read_ucsc_config(          $in, $out, $options ) }
189     elsif ( $script eq "assemble_tag_contigs" )     { script_assemble_tag_contigs(      $in, $out, $options ) }
190     elsif ( $script eq "format_genome" )            { script_format_genome(             $in, $out, $options ) }
191     elsif ( $script eq "length_seq" )               { script_length_seq(                $in, $out, $options ) }
192     elsif ( $script eq "uppercase_seq" )            { script_uppercase_seq(             $in, $out, $options ) }
193     elsif ( $script eq "shuffle_seq" )              { script_shuffle_seq(               $in, $out, $options ) }
194     elsif ( $script eq "analyze_seq" )              { script_analyze_seq(               $in, $out, $options ) }
195     elsif ( $script eq "analyze_tags" )             { script_analyze_tags(              $in, $out, $options ) }
196     elsif ( $script eq "complexity_seq" )           { script_complexity_seq(            $in, $out, $options ) }
197     elsif ( $script eq "oligo_freq" )               { script_oligo_freq(                $in, $out, $options ) }
198     elsif ( $script eq "create_weight_matrix" )     { script_create_weight_matrix(      $in, $out, $options ) }
199     elsif ( $script eq "calc_bit_scores" )          { script_calc_bit_scores(           $in, $out, $options ) }
200     elsif ( $script eq "calc_fixedstep" )           { script_calc_fixedstep(            $in, $out, $options ) }
201     elsif ( $script eq "reverse_seq" )              { script_reverse_seq(               $in, $out, $options ) }
202     elsif ( $script eq "complement_seq" )           { script_complement_seq(            $in, $out, $options ) }
203     elsif ( $script eq "remove_indels" )            { script_remove_indels(             $in, $out, $options ) }
204     elsif ( $script eq "transliterate_seq" )        { script_transliterate_seq(         $in, $out, $options ) }
205     elsif ( $script eq "transliterate_vals" )       { script_transliterate_vals(        $in, $out, $options ) }
206     elsif ( $script eq "translate_seq" )            { script_translate_seq(             $in, $out, $options ) }
207     elsif ( $script eq "extract_seq" )              { script_extract_seq(               $in, $out, $options ) }
208     elsif ( $script eq "get_genome_seq" )           { script_get_genome_seq(            $in, $out, $options ) }
209     elsif ( $script eq "get_genome_align" )         { script_get_genome_align(          $in, $out, $options ) }
210     elsif ( $script eq "get_genome_phastcons" )     { script_get_genome_phastcons(      $in, $out, $options ) }
211     elsif ( $script eq "fold_seq" )                 { script_fold_seq(                  $in, $out, $options ) }
212     elsif ( $script eq "split_seq" )                { script_split_seq(                 $in, $out, $options ) }
213     elsif ( $script eq "split_bed" )                { script_split_bed(                 $in, $out, $options ) }
214     elsif ( $script eq "align_seq" )                { script_align_seq(                 $in, $out, $options ) }
215     elsif ( $script eq "tile_seq" )                 { script_tile_seq(                  $in, $out, $options ) }
216     elsif ( $script eq "invert_align" )             { script_invert_align(              $in, $out, $options ) }
217     elsif ( $script eq "patscan_seq" )              { script_patscan_seq(               $in, $out, $options ) }
218     elsif ( $script eq "create_blast_db" )          { script_create_blast_db(           $in, $out, $options ) }
219     elsif ( $script eq "blast_seq" )                { script_blast_seq(                 $in, $out, $options ) }
220     elsif ( $script eq "blat_seq" )                 { script_blat_seq(                  $in, $out, $options ) }
221     elsif ( $script eq "soap_seq" )                 { script_soap_seq(                  $in, $out, $options ) }
222     elsif ( $script eq "match_seq" )                { script_match_seq(                 $in, $out, $options ) }
223     elsif ( $script eq "create_vmatch_index" )      { script_create_vmatch_index(       $in, $out, $options ) }
224     elsif ( $script eq "vmatch_seq" )               { script_vmatch_seq(                $in, $out, $options ) }
225     elsif ( $script eq "write_fasta" )              { script_write_fasta(               $in, $out, $options ) }
226     elsif ( $script eq "write_align" )              { script_write_align(               $in, $out, $options ) }
227     elsif ( $script eq "write_blast" )              { script_write_blast(               $in, $out, $options ) }
228     elsif ( $script eq "write_tab" )                { script_write_tab(                 $in, $out, $options ) }
229     elsif ( $script eq "write_bed" )                { script_write_bed(                 $in, $out, $options ) }
230     elsif ( $script eq "write_psl" )                { script_write_psl(                 $in, $out, $options ) }
231     elsif ( $script eq "write_fixedstep" )          { script_write_fixedstep(           $in, $out, $options ) }
232     elsif ( $script eq "write_2bit" )               { script_write_2bit(                $in, $out, $options ) }
233     elsif ( $script eq "write_solid" )              { script_write_solid(               $in, $out, $options ) }
234     elsif ( $script eq "write_ucsc_config" )        { script_write_ucsc_config(         $in, $out, $options ) }
235     elsif ( $script eq "head_records" )             { script_head_records(              $in, $out, $options ) }
236     elsif ( $script eq "remove_keys" )              { script_remove_keys(               $in, $out, $options ) }
237     elsif ( $script eq "remove_adaptor" )           { script_remove_adaptor(            $in, $out, $options ) }
238     elsif ( $script eq "remove_mysql_tables" )      { script_remove_mysql_tables(       $in, $out, $options ) }
239     elsif ( $script eq "remove_ucsc_tracks" )       { script_remove_ucsc_tracks(        $in, $out, $options ) }
240     elsif ( $script eq "rename_keys" )              { script_rename_keys(               $in, $out, $options ) }
241     elsif ( $script eq "uniq_vals" )                { script_uniq_vals(                 $in, $out, $options ) }
242     elsif ( $script eq "merge_vals" )               { script_merge_vals(                $in, $out, $options ) }
243     elsif ( $script eq "merge_records" )            { script_merge_records(             $in, $out, $options ) }
244     elsif ( $script eq "grab" )                     { script_grab(                      $in, $out, $options ) }
245     elsif ( $script eq "compute" )                  { script_compute(                   $in, $out, $options ) }
246     elsif ( $script eq "flip_tab" )                 { script_flip_tab(                  $in, $out, $options ) }
247     elsif ( $script eq "add_ident" )                { script_add_ident(                 $in, $out, $options ) }
248     elsif ( $script eq "count_records" )            { script_count_records(             $in, $out, $options ) }
249     elsif ( $script eq "random_records" )           { script_random_records(            $in, $out, $options ) }
250     elsif ( $script eq "sort_records" )             { script_sort_records(              $in, $out, $options ) }
251     elsif ( $script eq "count_vals" )               { script_count_vals(                $in, $out, $options ) }
252     elsif ( $script eq "plot_histogram" )           { script_plot_histogram(            $in, $out, $options ) }
253     elsif ( $script eq "plot_lendist" )             { script_plot_lendist(              $in, $out, $options ) }
254     elsif ( $script eq "plot_chrdist" )             { script_plot_chrdist(              $in, $out, $options ) }
255     elsif ( $script eq "plot_karyogram" )           { script_plot_karyogram(            $in, $out, $options ) }
256     elsif ( $script eq "plot_matches" )             { script_plot_matches(              $in, $out, $options ) }
257     elsif ( $script eq "plot_seqlogo" )             { script_plot_seqlogo(              $in, $out, $options ) }
258     elsif ( $script eq "plot_phastcons_profiles" )  { script_plot_phastcons_profiles(   $in, $out, $options ) }
259     elsif ( $script eq "analyze_bed" )              { script_analyze_bed(               $in, $out, $options ) }
260     elsif ( $script eq "analyze_vals" )             { script_analyze_vals(              $in, $out, $options ) }
261     elsif ( $script eq "length_vals" )              { script_length_vals(               $in, $out, $options ) }
262     elsif ( $script eq "sum_vals" )                 { script_sum_vals(                  $in, $out, $options ) }
263     elsif ( $script eq "mean_vals" )                { script_mean_vals(                 $in, $out, $options ) }
264     elsif ( $script eq "median_vals" )              { script_median_vals(               $in, $out, $options ) }
265     elsif ( $script eq "max_vals" )                 { script_max_vals(                  $in, $out, $options ) }
266     elsif ( $script eq "min_vals" )                 { script_min_vals(                  $in, $out, $options ) }
267     elsif ( $script eq "upload_to_ucsc" )           { script_upload_to_ucsc(            $in, $out, $options ) }
268
269     close $in if defined $in;
270     close $out;
271
272     $t1 = gettimeofday();
273
274     print STDERR "Program: $script" . ( " " x ( 25 - length( $script ) ) ) . sprintf( "Run time: %.4f\n", ( $t1 - $t0 ) ) if $options->{ 'verbose' };
275 }
276
277
278 sub get_options
279 {
280     # Martin A. Hansen, February 2008.
281
282     # Gets options from commandline and checks these vigerously.
283
284     my ( $script,     # name of script
285        ) = @_;
286
287     # Returns hash
288
289     my ( %options, @options, $opt, @genomes, $real );
290
291     if ( $script eq "print_usage" )
292     {
293         @options = qw(
294             data_in|i=s
295         );
296     }
297     elsif ( $script eq "read_fasta" )
298     {
299         @options = qw(
300             data_in|i=s
301             num|n=s
302         );
303     }
304     elsif ( $script eq "read_tab" )
305     {
306         @options = qw(
307             data_in|i=s
308             delimit|d=s
309             cols|c=s
310             keys|k=s
311             skip|s=s
312             num|n=s
313         );
314     }
315     elsif ( $script eq "read_psl" )
316     {
317         @options = qw(
318             data_in|i=s
319             num|n=s
320         );
321     }
322     elsif ( $script eq "read_bed" )
323     {
324         @options = qw(
325             data_in|i=s
326             num|n=s
327         );
328     }
329     elsif ( $script eq "read_fixedstep" )
330     {
331         @options = qw(
332             data_in|i=s
333             num|n=s
334         );
335     }
336     elsif ( $script eq "read_blast_tab" )
337     {
338         @options = qw(
339             data_in|i=s
340             num|n=s
341         );
342     }
343     elsif ( $script eq "read_embl" )
344     {
345         @options = qw(
346             data_in|i=s
347             num|n=s
348             keys|k=s
349             feats|f=s
350             quals|q=s
351         );
352     }
353     elsif ( $script eq "read_stockholm" )
354     {
355         @options = qw(
356             data_in|i=s
357             num|n=s
358         );
359     }
360     elsif ( $script eq "read_phastcons" )
361     {
362         @options = qw(
363             data_in|i=s
364             num|n=s
365             min|m=s
366             dist|d=s
367             threshold|t=f
368             gap|g=s
369         );
370     }
371     elsif ( $script eq "read_soft" )
372     {
373         @options = qw(
374             data_in|i=s
375             samples|s=s
376             num|n=s
377         );
378     }
379     elsif ( $script eq "read_gff" )
380     {
381         @options = qw(
382             data_in|i=s
383             num|n=s
384         );
385     }
386     elsif ( $script eq "read_2bit" )
387     {
388         @options = qw(
389             data_in|i=s
390             num|n=s
391             no_mask|N
392         );
393     }
394     elsif ( $script eq "read_solexa" )
395     {
396         @options = qw(
397             data_in|i=s
398             num|n=s
399             format|f=s
400             quality|q=s
401         );
402     }
403     elsif ( $script eq "read_solid" )
404     {
405         @options = qw(
406             data_in|i=s
407             num|n=s
408             quality|q=s
409         );
410     }
411     elsif ( $script eq "read_mysql" )
412     {
413         @options = qw(
414             database|d=s
415             query|q=s
416             user|u=s
417             password|p=s
418         );
419     }
420     elsif ( $script eq "read_ucsc_config" )
421     {
422         @options = qw(
423             data_in|i=s
424             num|n=s
425         );
426     }
427     elsif ( $script eq "format_genome" )
428     {
429         @options = qw(
430             no_stream|x
431             dir|d=s
432             genome|g=s
433             formats|f=s
434         );
435     }
436     elsif ( $script eq "length_seq" )
437     {
438         @options = qw(
439             no_stream|x
440             data_out|o=s
441         );
442     }
443     elsif ( $script eq "oligo_freq" )
444     {
445         @options = qw(
446             word_size|w=s
447             all|a
448         );
449     }
450     elsif ( $script eq "create_weight_matrix" )
451     {
452         @options = qw(
453             percent|p
454         );
455     }
456     elsif ( $script eq "calc_fixedstep" )
457     {
458         @options = qw(
459             score|S
460             log10|L
461         );
462     }
463     elsif ( $script eq "transliterate_seq" )
464     {
465         @options = qw(
466             search|s=s
467             replace|r=s
468             delete|d=s
469         );
470     }
471     elsif ( $script eq "transliterate_vals" )
472     {
473         @options = qw(
474             keys|k=s
475             search|s=s
476             replace|r=s
477             delete|d=s
478         );
479     }
480     elsif ( $script eq "translate_seq" )
481     {
482         @options = qw(
483             frames|f=s
484         );
485     }
486     elsif ( $script eq "extract_seq" )
487     {
488         @options = qw(
489             beg|b=s
490             end|e=s
491             len|l=s
492         );
493     }
494     elsif ( $script eq "get_genome_seq" )
495     {
496         @options = qw(
497             genome|g=s
498             chr|c=s
499             beg|b=s
500             end|e=s
501             len|l=s
502             flank|f=s
503             mask|m
504         );
505     }
506     elsif ( $script eq "get_genome_align" )
507     {
508         @options = qw(
509             genome|g=s
510             chr|c=s
511             beg|b=s
512             end|e=s
513             len|l=s
514             strand|s=s
515         );
516     }
517     elsif ( $script eq "get_genome_phastcons" )
518     {
519         @options = qw(
520             genome|g=s
521             chr|c=s
522             beg|b=s
523             end|e=s
524             len|l=s
525             flank|f=s
526         );
527     }
528     elsif ( $script eq "split_seq" )
529     {
530         @options = qw(
531             word_size|w=s
532             uniq|u
533         );
534     }
535     elsif ( $script eq "split_bed" )
536     {
537         @options = qw(
538             window_size|w=s
539             step_size|s=s
540         );
541     }
542     elsif ( $script eq "tile_seq" )
543     {
544         @options = qw(
545             identity|i=s
546             supress_indels|s
547         );
548     }
549     elsif ( $script eq "invert_align" )
550     {
551         @options = qw(
552             soft|s
553         );
554     }
555     elsif ( $script eq "patscan_seq" )
556     {
557         @options = qw(
558             patterns|p=s
559             patterns_in|P=s
560             comp|c
561             max_hits|h=s
562             max_misses|m=s
563             genome|g=s
564         );
565     }
566     elsif ( $script eq "create_blast_db" )
567     {
568         @options = qw(
569             no_stream|x
570             database|d=s
571         );
572     }
573     elsif ( $script eq "blast_seq" )
574     {
575         @options = qw(
576             database|d=s
577             genome|g=s
578             program|p=s
579             e_val|e=f
580             filter|f
581             cpus|c=s
582             no_filter|F
583         );
584     }
585     elsif ( $script eq "blat_seq" )
586     {
587         @options = qw(
588             genome|g=s
589             tile_size|t=s
590             step_size|s=s
591             min_identity|m=s
592             min_score|M=s
593             one_off|o=s
594             ooc|c
595         );
596     }
597     elsif ( $script eq "soap_seq" )
598     {
599         @options = qw(
600             in_file|i=s
601             genome|g=s
602             seed_size|s=s
603             mismatches|m=s
604             gap_size|G=s
605             cpus|c=s
606         );
607     }
608     elsif ( $script eq "match_seq" )
609     {
610         @options = qw(
611             word_size|w=s
612             direction|d=s
613         );
614     }
615     elsif ( $script eq "create_vmatch_index" )
616     {
617         @options = qw(
618             index_name|i=s
619             prefix_length|p=s
620             no_stream|x
621         );
622     }
623     elsif ( $script eq "vmatch_seq" )
624     {
625         @options = qw(
626             genome|g=s
627             index_name|i=s
628             count|c
629             max_hits|m=s
630             hamming_dist|h=s
631             edit_dist|e=s
632         );
633     }
634     elsif ( $script eq "write_fasta" )
635     {
636         @options = qw(
637             wrap|w=s
638             no_stream|x
639             data_out|o=s
640             compress|Z
641         );
642     }
643     elsif ( $script eq "write_align" )
644     {
645         @options = qw(
646             wrap|w=s
647             no_stream|x
648             no_ruler|R
649             no_consensus|C
650             data_out|o=s
651         );
652     }
653     elsif ( $script eq "write_blast" )
654     {
655         @options = qw(
656             no_stream|x
657             data_out|o=s
658             comment|c
659             compress|Z
660         );
661     }
662     elsif ( $script eq "write_tab" )
663     {
664         @options = qw(
665             no_stream|x
666             data_out|o=s
667             delimit|d=s
668             keys|k=s
669             no_keys|K=s
670             comment|c
671             compress|Z
672         );
673     }
674     elsif ( $script eq "write_bed" )
675     {
676         @options = qw(
677             no_stream|x
678             data_out|o=s
679             compress|Z
680         );
681     }
682     elsif ( $script eq "write_psl" )
683     {
684         @options = qw(
685             no_stream|x
686             data_out|o=s
687             compress|Z
688         );
689     }
690     elsif ( $script eq "write_fixedstep" )
691     {
692         @options = qw(
693             no_stream|x
694             data_out|o=s
695             compress|Z
696         );
697     }
698     elsif ( $script eq "write_2bit" )
699     {
700         @options = qw(
701             no_stream|x
702             data_out|o=s
703             no_mask|N
704         );
705     }
706     elsif ( $script eq "write_solid" )
707     {
708         @options = qw(
709             wrap|w=s
710             no_stream|x
711             data_out|o=s
712             compress|Z
713         );
714     }
715     elsif ( $script eq "write_ucsc_config" )
716     {
717         @options = qw(
718             no_stream|x
719             data_out|o=s
720         );
721     }
722     elsif ( $script eq "plot_seqlogo" )
723     {
724         @options = qw(
725             no_stream|x
726             data_out|o=s
727         );
728     }
729     elsif ( $script eq "plot_phastcons_profiles" )
730     {
731         @options = qw(
732             no_stream|x
733             data_out|o=s
734             genome|g=s
735             mean|m
736             median|M
737             flank|f=s
738             terminal|t=s
739             title|T=s
740             xlabel|X=s
741             ylabel|Y=s
742         );
743     }
744     elsif ( $script eq "analyze_vals" )
745     {
746         @options = qw(
747             no_stream|x
748             keys|k=s
749         );
750     }
751     elsif ( $script eq "head_records" )
752     {
753         @options = qw(
754             num|n=s
755         );
756     }
757     elsif ( $script eq "remove_keys" )
758     {
759         @options = qw(
760             keys|k=s
761             save_keys|K=s
762         );
763     }
764     elsif ( $script eq "remove_adaptor" )
765     {
766         @options = qw(
767             adaptor|a=s
768             mismatches|m=s
769             remove|r=s
770             offset|o=s
771         );
772     }
773     elsif ( $script eq "remove_mysql_tables" )
774     {
775         @options = qw(
776             database|d=s
777             tables|t=s
778             keys|k=s
779             user|u=s
780             password|p=s
781             no_stream|x
782         );
783     }
784     elsif ( $script eq "remove_ucsc_tracks" )
785     {
786         @options = qw(
787             database|d=s
788             tracks|t=s
789             keys|k=s
790             config_file|c=s
791             user|u=s
792             password|p=s
793             no_stream|x
794         );
795     }
796     elsif ( $script eq "rename_keys" )
797     {
798         @options = qw(
799             keys|k=s
800         );
801     }
802     elsif ( $script eq "uniq_vals" )
803     {
804         @options = qw(
805             key|k=s
806             invert|i
807         );
808     }
809     elsif ( $script eq "merge_vals" )
810     {
811         @options = qw(
812             keys|k=s
813             delimit|d=s
814         );
815     }
816     elsif ( $script eq "merge_records" )
817     {
818         @options = qw(
819             keys|k=s
820             merge|m=s
821         );
822     }
823     elsif ( $script eq "grab" )
824     {
825         @options = qw(
826             patterns|p=s
827             patterns_in|P=s
828             regex|r=s
829             eval|e=s
830             exact_in|E=s
831             invert|i
832             case_insensitive|c
833             keys|k=s
834             keys_only|K
835             vals_only|V
836         );
837     }
838     elsif ( $script eq "compute" )
839     {
840         @options = qw(
841             eval|e=s
842         );
843     }
844     elsif ( $script eq "add_ident" )
845     {
846         @options = qw(
847             prefix|p=s
848             key|k=s
849         );
850     }
851     elsif ( $script eq "count_records" )
852     {
853         @options = qw(
854             no_stream|x
855             data_out|o=s
856         );
857     }
858     elsif ( $script eq "random_records" )
859     {
860         @options = qw(
861             num|n=s
862         );
863     }
864     elsif ( $script eq "sort_records" )
865     {
866         @options = qw(
867             reverse|r
868             keys|k=s
869         );
870     }
871     elsif ( $script eq "count_vals" )
872     {
873         @options = qw(
874             keys|k=s
875         );
876     }
877     elsif ( $script eq "plot_histogram" )
878     {
879         @options = qw(
880             no_stream|x
881             data_out|o=s
882             terminal|t=s
883             title|T=s
884             xlabel|X=s
885             ylabel|Y=s
886             key|k=s
887             sort|s=s
888         );
889     }
890     elsif ( $script eq "plot_lendist" )
891     {
892         @options = qw(
893             no_stream|x
894             data_out|o=s
895             terminal|t=s
896             title|T=s
897             xlabel|X=s
898             ylabel|Y=s
899             key|k=s
900         );
901     }
902     elsif ( $script eq "plot_chrdist" )
903     {
904         @options = qw(
905             no_stream|x
906             data_out|o=s
907             terminal|t=s
908             title|T=s
909             xlabel|X=s
910             ylabel|Y=s
911         );
912     }
913     elsif ( $script eq "plot_karyogram" )
914     {
915         @options = qw(
916             no_stream|x
917             data_out|o=s
918             genome|g=s
919             feat_color|f=s
920         );
921     }
922     elsif ( $script eq "plot_matches" )
923     {
924         @options = qw(
925             no_stream|x
926             data_out|o=s
927             terminal|t=s
928             title|T=s
929             xlabel|X=s
930             ylabel|Y=s
931             direction|d=s
932         );
933     }
934     elsif ( $script eq "length_vals" )
935     {
936         @options = qw(
937             keys|k=s
938         );
939     }
940     elsif ( $script eq "sum_vals" )
941     {
942         @options = qw(
943             no_stream|x
944             data_out|o=s
945             keys|k=s
946         );
947     }
948     elsif ( $script eq "mean_vals" )
949     {
950         @options = qw(
951             no_stream|x
952             data_out|o=s
953             keys|k=s
954         );
955     }
956     elsif ( $script eq "median_vals" )
957     {
958         @options = qw(
959             no_stream|x
960             data_out|o=s
961             keys|k=s
962         );
963     }
964     elsif ( $script eq "max_vals" )
965     {
966         @options = qw(
967             no_stream|x
968             data_out|o=s
969             keys|k=s
970         );
971     }
972     elsif ( $script eq "min_vals" )
973     {
974         @options = qw(
975             no_stream|x
976             data_out|o=s
977             keys|k=s
978         );
979     }
980     elsif ( $script eq "upload_to_ucsc" )
981     {
982         @options = qw(
983             no_stream|x
984             database|d=s
985             table|t=s
986             short_label|s=s
987             long_label|l=s
988             group|g=s
989             priority|p=f
990             use_score|u
991             visibility|V=s
992             color|c=s
993             chunk_size|C=s
994         );
995     }
996
997     push @options, qw(
998         stream_in|I=s
999         stream_out|O=s
1000         verbose|v
1001         help|?
1002     );
1003
1004 #    print STDERR Dumper( \@options );
1005     
1006     GetOptions(
1007         \%options,
1008         @options,
1009     );
1010
1011 #    print STDERR Dumper( \%options );
1012
1013     if ( -t STDIN && scalar( keys %options ) == 0 or $options{ "help" } ) {
1014         return wantarray ? %options : \%options;
1015     }
1016
1017     $options{ "cols" }      = [ split ",", $options{ "cols" } ]      if defined $options{ "cols" };
1018     $options{ "keys" }      = [ split ",", $options{ "keys" } ]      if defined $options{ "keys" };
1019     $options{ "no_keys" }   = [ split ",", $options{ "no_keys" } ]   if defined $options{ "no_keys" };
1020     $options{ "save_keys" } = [ split ",", $options{ "save_keys" } ] if defined $options{ "save_keys" };
1021     $options{ "quals" }     = [ split ",", $options{ "quals" } ]     if defined $options{ "quals" };
1022     $options{ "feats" }     = [ split ",", $options{ "feats" } ]     if defined $options{ "feats" };
1023     $options{ "frames" }    = [ split ",", $options{ "frames" } ]    if defined $options{ "frames" };
1024     $options{ "formats" }   = [ split ",", $options{ "formats" } ]   if defined $options{ "formats" };
1025     $options{ "samples" }   = [ split ",", $options{ "samples" } ]   if defined $options{ "samples" };
1026     $options{ "tables" }    = [ split ",", $options{ "tables" } ]    if defined $options{ "tables" };
1027     $options{ "tracks" }    = [ split ",", $options{ "tracks" } ]    if defined $options{ "tracks" };
1028     
1029     # ---- check arguments ----
1030
1031     if ( $options{ 'data_in' } )
1032     {
1033         $options{ "files" } = getopt_files( $options{ 'data_in' } );
1034
1035         Maasha::Common::error( qq(Argument to --data_in must be a valid file or fileglob expression) ) if scalar @{ $options{ "files" } } == 0;
1036     }
1037
1038     map { Maasha::Common::error( qq(Argument to --cols must be a whole numbers - not "$_") ) if $_ !~ /^\d+$/ } @{ $options{ "cols" } } if $options{ "cols" };
1039
1040     # print STDERR Dumper( \%options );
1041
1042     $real = "beg|end|word_size|wrap|chunk_size|tile_size|len|prefix_length|mismatches|offset|num|skip|cpus|window_size|step_size";
1043
1044     foreach $opt ( keys %options )
1045     {
1046         if ( $opt =~ /stream_in|pattern_in|exact_in/ and not -f $options{ $opt } )
1047         {
1048             Maasha::Common::error( qq(Argument to --$opt must be a valid file or fileglob expression - not "$options{ $opt }") );
1049         }
1050         elsif ( $opt =~ /$real/ and $options{ $opt } !~ /^\d+$/ )
1051         {
1052             Maasha::Common::error( qq(Argument to --$opt must be a whole number - not "$options{ $opt }") );
1053         }
1054         elsif ( $opt =~ /max_hits|max_hits|max_misses|dist|edit_dist|flank|gap|hamming_dist|priority/ and $options{ $opt } !~ /^-?\d+$/ )
1055         {
1056             Maasha::Common::error( qq(Argument to --$opt must be an integer - not "$options{ $opt }") );
1057         }
1058         elsif ( $opt =~ /identity|threshold/ and $options{ $opt } !~ /^-?(?:\d+(?:\.\d*)?|\.\d+)$/ )
1059         {
1060             Maasha::Common::error( qq(Argument to --$opt must be a decimal number - not "$options{ $opt }") );
1061         }
1062         elsif ( $opt =~ /e_val/ and $options{ $opt } !~ /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/ )
1063         {
1064             Maasha::Common::error( qq(Argument to --$opt must be a float - not "$options{ $opt }") );
1065         }
1066         elsif ( $opt =~ /strand/ and $options{ $opt } !~ /^(\+|-)$/ )
1067         {
1068             Maasha::Common::error( qq(Argument to --$opt must be "+" or "-" - not "$options{ $opt }") );
1069         }
1070         elsif ( $opt eq "genome" and $script ne "format_genome" )
1071         {
1072             @genomes = Maasha::Common::ls_dirs( "$ENV{ 'BP_DATA' }/genomes" );
1073             map { $_ =~ s/.*\/(.+)$/$1/ } @genomes;
1074
1075             if ( not grep { $_ =~ /^$options{ $opt }$/ } @genomes ) {
1076                 Maasha::Common::error( qq(Genome $options{ $opt } not found in "$ENV{ 'BP_DATA' }/genomes/") );
1077             }
1078         }
1079         elsif ( $opt eq "terminal" and not $options{ $opt } =~ /^(svg|post|dumb|x11)/ )
1080         {
1081             Maasha::Common::error( qq(Bad --$opt argument "$options{ $opt }") );
1082         }
1083         elsif ( $opt eq "table" and $options{ $opt } =~ /(-|\.)/ )
1084         {
1085             Maasha::Common::error( qq(Character '$1' is not allowed in table name: $options{ $opt }) );
1086         }
1087         elsif ( $opt eq "merge" and $options{ $opt } !~ /^(AandB|AorB|BorA|AnotB|BnotA)$/ )
1088         {
1089             Maasha::Common::error( qq(Argument to --$opt must be AandB, AorB, BorA, AnotB, or BnotA - not "$options{ $opt }") );
1090         }
1091         elsif ( $opt eq "format" and $script eq "read_solexa" and $options{ $opt } !~ /octal|decimal/ )
1092         {
1093             Maasha::Common::error( qq(Argument to --$opt must be octal or decimal - not "$options{ $opt }") );
1094         }
1095         elsif ( $opt eq "remove" and $script eq "remove_adaptor" and $options{ $opt } !~ /before|after|skip/ )
1096         {
1097             Maasha::Common::error( qq(Argument to --$opt must be before, after, or skip - not "$options{ $opt }") );
1098         }
1099     }
1100
1101     Maasha::Common::error( qq(no --database specified) )                if $script eq "create_blast_db"     and not $options{ "database" };
1102     Maasha::Common::error( qq(no --index_name specified) )              if $script =~ /create_vmatch_index/ and not $options{ "index_name" };
1103     Maasha::Common::error( qq(no --database or --genome specified) )    if $script eq "blast_seq" and not $options{ "genome" } and not $options{ "database" };
1104     Maasha::Common::error( qq(both --database and --genome specified) ) if $script eq "blast_seq" and $options{ "genome" } and $options{ "database" };
1105     Maasha::Common::error( qq(no --index_name or --genome specified) )  if $script eq "vmatch_seq" and not $options{ "genome" } and not $options{ "index_name" };
1106     Maasha::Common::error( qq(both --index and --genome specified) )    if $script eq "vmatch_seq" and $options{ "genome" } and $options{ "index_name" };
1107     Maasha::Common::error( qq(no --in_file or --genome specified) )     if $script eq "soap_seq" and not $options{ "genome" } and not $options{ "in_file" };
1108     Maasha::Common::error( qq(both --in_file and --genome specified) )  if $script eq "soap_seq" and $options{ "genome" } and $options{ "in_file" };
1109     Maasha::Common::error( qq(no --genome specified) )                  if $script =~ /format_genome|get_genome_seq|get_genome_align|get_genome_phastcons|blat_seq|plot_phastcons_profiles|plot_karyogram/ and not $options{ "genome" };
1110     Maasha::Common::error( qq(no --key specified) )                     if $script =~ /plot_lendist|plot_histogram/ and not $options{ "key" };
1111     Maasha::Common::error( qq(no --keys speficied) )                    if $script =~ /sort_records|count_vals|sum_vals|mean_vals|median_vals|length_vals/ and not $options{ "keys" };
1112
1113     if ( $script eq "upload_to_ucsc" )
1114     {
1115         Maasha::Common::error( qq(no --database specified) ) if not $options{ "database" };
1116         Maasha::Common::error( qq(no --table specified) )    if not $options{ "table" };
1117     }
1118
1119     return wantarray ? %options : \%options;
1120 }
1121
1122
1123 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> SCRIPTS  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
1124
1125
1126 sub script_print_usage
1127 {
1128     # Martin A. Hansen, January 2008.
1129
1130     # Retrieves usage information from file and
1131     # prints this nicely formatted.
1132
1133     my ( $in,        # handle to in stream
1134          $out,       # handle to out stream
1135          $options,   # options hash
1136        ) = @_;
1137
1138     # Returns nothing.
1139
1140     my ( $file, $wiki, $lines );
1141
1142     if ( $options->{ 'data_in' } ) {
1143         $file = $options->{ 'data_in' };
1144     } else {
1145         $file = join "", $ENV{ 'BP_DIR' }, "/bp_usage/", $options->{ 'SCRIPT' }, ".wiki";
1146     }
1147
1148     $wiki = Maasha::Gwiki::gwiki_read( $file );
1149
1150     if ( not $options->{ "help" } ) {
1151         @{ $wiki } = grep { $_->[ 0 ]->{ 'SECTION' } =~ /Biopiece|Synopsis|Usage|Options|Help/ } @{ $wiki };
1152     }
1153
1154     $lines = Maasha::Gwiki::gwiki2ascii( $wiki );
1155
1156     print STDERR "$_\n" foreach @{ $lines };
1157
1158     exit;
1159 }
1160
1161
1162 sub script_list_biopieces
1163 {
1164     # Martin A. Hansen, January 2008.
1165
1166     # Prints the synopsis from the usage for each of the biopieces.
1167
1168     my ( $in,        # handle to in stream
1169          $out,       # handle to out stream
1170          $options,   # options hash
1171        ) = @_;
1172
1173     # Returns nothing.
1174
1175     my ( @files, $file, $wiki, $program, $synopsis );
1176
1177     @files = Maasha::Common::ls_files( "$ENV{ 'BP_DIR' }/bp_usage" );
1178
1179     foreach $file ( sort @files )
1180     {
1181         if ( $file =~ /\/([a-z0-9_]+)\.wiki$/ )
1182         {
1183             $program = $1;
1184
1185             $wiki = Maasha::Gwiki::gwiki_read( $file );
1186
1187             @{ $wiki } = grep { $_->[ 0 ]->{ 'SECTION' } =~ /Synopsis/ }  @{ $wiki };
1188             @{ $wiki } = grep { $_->[ 0 ]->{ 'FORMAT' }  =~ /paragraph/ } @{ $wiki };
1189
1190             $synopsis = $wiki->[ 0 ]->[ 0 ]->{ 'TEXT' };
1191             $synopsis =~ s/!(\w)/$1/g;
1192
1193             printf( "%-30s%s\n", $program, $synopsis );
1194         }
1195     }
1196
1197     exit;
1198 }
1199
1200
1201 sub script_list_genomes
1202 {
1203     # Martin A. Hansen, January 2008.
1204
1205     # Prints the synopsis from the usage for each of the biopieces.
1206
1207     my ( $in,        # handle to in stream
1208          $out,       # handle to out stream
1209          $options,   # options hash
1210        ) = @_;
1211
1212     # Returns nothing.
1213
1214     my ( @genomes, $genome, @formats, $format, %hash, %found, @row );
1215
1216     @genomes = Maasha::Common::ls_dirs( "$ENV{ 'BP_DATA' }/genomes" );
1217
1218     foreach $genome ( @genomes )
1219     {
1220         next if $genome =~ /\.$/;
1221
1222         @formats = Maasha::Common::ls_dirs( $genome );
1223
1224         foreach $format ( @formats )
1225         {
1226             if ( $format =~ /\/([^\/]+)\/(\w+)$/ )
1227             {
1228                 $hash{ $1 }{ $2 } = 1;
1229
1230                 $found{ $2 } = 1;
1231             }
1232         }
1233     }
1234
1235     @row = "Genome";
1236
1237     map { push @row, $_ } sort keys %found;
1238
1239     print join( "\t", @row ), "\n";
1240
1241     foreach $genome ( sort keys %hash )
1242     {
1243         @row = $genome;
1244
1245         foreach $format ( sort keys %found )
1246         {
1247             if ( exists $hash{ $genome }{ $format } ) {
1248                 push @row, "yes";
1249             } else {
1250                 push @row, "no";
1251             }
1252         }
1253
1254         print join( "\t", @row ), "\n";
1255     }
1256 }
1257
1258
1259 sub script_read_fasta
1260 {
1261     # Martin A. Hansen, August 2007.
1262
1263     # Read sequences from FASTA file.
1264
1265     my ( $in,        # handle to in stream
1266          $out,       # handle to out stream
1267          $options,   # options hash
1268        ) = @_;
1269
1270     # Returns nothing.
1271
1272     my ( $record, $file, $data_in, $entry, $num );
1273
1274     while ( $record = get_record( $in ) ) {
1275         put_record( $record, $out );
1276     }
1277
1278     $num = 1;
1279
1280     foreach $file ( @{ $options->{ "files" } } )
1281     {
1282         $data_in = Maasha::Common::read_open( $file );
1283
1284         while ( $entry = Maasha::Fasta::get_entry( $data_in ) ) 
1285         {
1286             if ( defined $entry->[ SEQ_NAME ] and $entry->[ SEQ ] )
1287             {
1288                 $record = {
1289                     SEQ_NAME => $entry->[ SEQ_NAME ],
1290                     SEQ      => $entry->[ SEQ ],
1291                     SEQ_LEN  => length $entry->[ SEQ ],
1292                 };
1293
1294                 put_record( $record, $out );
1295             }
1296
1297             goto NUM if $options->{ "num" } and $num == $options->{ "num" };
1298
1299             $num++;
1300         }
1301
1302         close $data_in;
1303     }
1304
1305     NUM:
1306
1307     close $data_in if $data_in;
1308 }
1309
1310
1311 sub script_read_tab
1312 {
1313     # Martin A. Hansen, August 2007.
1314
1315     # Read table or table columns from stream or file.
1316
1317     my ( $in,        # handle to in stream
1318          $out,       # handle to out stream
1319          $options,   # options hash
1320        ) = @_;
1321
1322     # Returns nothing.
1323
1324     my ( $file, $line, @fields, @fields2, $i, $record, $data_in, $skip, $num );
1325
1326     $options->{ 'delimit' } ||= '\s+';
1327
1328     while ( $record = get_record( $in ) ) {
1329         put_record( $record, $out );
1330     }
1331
1332     $skip = $options->{ 'skip' } ||= 0;
1333     $num = 1;
1334
1335     foreach $file ( @{ $options->{ "files" } } )
1336     {
1337         $data_in = Maasha::Common::read_open( $file );
1338
1339         while ( $line = <$data_in> ) 
1340         {
1341             if ( $skip )
1342             {
1343                 $skip--;
1344                 next;
1345             }
1346
1347             next if $line =~ /^#|^$/;
1348
1349             chomp $line;
1350
1351             undef $record;
1352             undef @fields2;
1353
1354             @fields = split /$options->{'delimit'}/, $line;
1355
1356             if ( $options->{ "cols" } ) {
1357                 map { push @fields2, $fields[ $_ ] } @{ $options->{ "cols" } };
1358             } else {
1359                 @fields2 = @fields;
1360             }
1361
1362             for ( $i = 0; $i < @fields2; $i++ )
1363             {
1364                 if ( $options->{ "keys" }->[ $i ] ) {
1365                     $record->{ $options->{ "keys" }->[ $i ] } = $fields2[ $i ];
1366                 } else {
1367                     $record->{ "V" . $i } = $fields2[ $i ];
1368                 }
1369             }
1370
1371             put_record( $record, $out );
1372
1373             goto NUM if $options->{ "num" } and $num == $options->{ "num" };
1374
1375             $num++;
1376         }
1377
1378         close $data_in;
1379     }
1380
1381     NUM:
1382
1383     close $data_in if $data_in;
1384 }
1385
1386
1387 sub script_read_psl
1388 {
1389     # Martin A. Hansen, August 2007.
1390
1391     # Read psl table from stream or file.
1392
1393     my ( $in,        # handle to in stream
1394          $out,       # handle to out stream
1395          $options,   # options hash
1396        ) = @_;
1397
1398     # Returns nothing.
1399
1400     my ( $record, $file, $data_in, $num );
1401
1402     while ( $record = get_record( $in ) ) {
1403         put_record( $record, $out );
1404     }
1405
1406     $num = 1;
1407
1408     foreach $file ( @{ $options->{ "files" } } )
1409     {
1410         $data_in = Maasha::Common::read_open( $file );
1411
1412         while ( $record = Maasha::UCSC::psl_get_entry( $data_in ) ) 
1413         {
1414             put_record( $record, $out );
1415
1416             goto NUM if $options->{ "num" } and $num == $options->{ "num" };
1417
1418             $num++;
1419         }
1420     }
1421
1422     NUM:
1423 }
1424
1425
1426 sub script_read_bed
1427 {
1428     # Martin A. Hansen, August 2007.
1429
1430     # Read bed table from stream or file.
1431
1432     my ( $in,        # handle to in stream
1433          $out,       # handle to out stream
1434          $options,   # options hash
1435        ) = @_;
1436
1437     # Returns nothing.
1438
1439     my ( $file, $record, $entry, $data_in, $num );
1440
1441     while ( $record = get_record( $in ) ) {
1442         put_record( $record, $out );
1443     }
1444
1445     $num = 1;
1446
1447     foreach $file ( @{ $options->{ "files" } } )
1448     {
1449         $data_in = Maasha::Common::read_open( $file );
1450
1451         while ( $entry = Maasha::UCSC::bed_get_entry( $data_in ) )
1452         {
1453             put_record( $entry, $out );
1454
1455             goto NUM if $options->{ "num" } and $num == $options->{ "num" };
1456
1457             $num++;
1458         }
1459
1460         close $data_in;
1461     }
1462
1463     NUM:
1464
1465     close $data_in if $data_in;
1466 }
1467
1468
1469 sub script_read_fixedstep
1470 {
1471     # Martin A. Hansen, Juli 2008.
1472
1473     # Read fixedstep wiggle format from stream or file.
1474
1475     my ( $in,        # handle to in stream
1476          $out,       # handle to out stream
1477          $options,   # options hash
1478        ) = @_;
1479
1480     # Returns nothing.
1481
1482     my ( $file, $record, $entry, $head, $chr, $chr_beg, $step, $data_in, $num );
1483
1484     while ( $record = get_record( $in ) ) {
1485         put_record( $record, $out );
1486     }
1487
1488     $num = 1;
1489
1490     foreach $file ( @{ $options->{ "files" } } )
1491     {
1492         $data_in = Maasha::Common::read_open( $file );
1493
1494         while ( $entry = Maasha::UCSC::fixedstep_get_entry( $data_in ) )
1495         {
1496             $head = shift @{ $entry };
1497
1498             if ( $head =~ /^chrom=([^ ]+) start=(\d+) step=(\d+)$/ )
1499             {
1500                 $record->{ "REC_TYPE" } = "fixed_step";
1501                 $record->{ "CHR" }      = $1;
1502                 $record->{ "CHR_BEG" }  = $2;
1503                 $record->{ "STEP" }     = $3;
1504                 $record->{ "VALS" }     = join ";", @{ $entry };
1505             }
1506
1507             put_record( $record, $out );
1508
1509             goto NUM if $options->{ "num" } and $num == $options->{ "num" };
1510
1511             $num++;
1512         }
1513
1514         close $data_in;
1515     }
1516
1517     NUM:
1518
1519     close $data_in if $data_in;
1520 }
1521
1522
1523 sub script_read_blast_tab
1524 {
1525     # Martin A. Hansen, September 2007.
1526
1527     # Read tabular BLAST output from NCBI blast run with -m8 or -m9.
1528
1529     my ( $in,        # handle to in stream
1530          $out,       # handle to out stream
1531          $options,   # options hash
1532        ) = @_;
1533
1534     # Returns nothing.
1535
1536     my ( $file, $line, @fields, $strand, $record, $data_in, $num );
1537
1538     while ( $record = get_record( $in ) ) {
1539         put_record( $record, $out );
1540     }
1541
1542     $num = 1;
1543
1544     foreach $file ( @{ $options->{ "files" } } )
1545     {
1546         $data_in = Maasha::Common::read_open( $file );
1547
1548         while ( $line = <$data_in> )
1549         {
1550             chomp $line;
1551
1552             next if $line =~ /^#/;
1553
1554             @fields = split /\t/, $line;
1555
1556             $record->{ "REC_TYPE" }   = "BLAST";
1557             $record->{ "Q_ID" }       = $fields[ 0 ];
1558             $record->{ "S_ID" }       = $fields[ 1 ];
1559             $record->{ "IDENT" }      = $fields[ 2 ];
1560             $record->{ "ALIGN_LEN" }  = $fields[ 3 ];
1561             $record->{ "MISMATCHES" } = $fields[ 4 ];
1562             $record->{ "GAPS" }       = $fields[ 5 ];
1563             $record->{ "Q_BEG" }      = $fields[ 6 ] - 1; # BLAST is 1-based
1564             $record->{ "Q_END" }      = $fields[ 7 ] - 1; # BLAST is 1-based
1565             $record->{ "S_BEG" }      = $fields[ 8 ] - 1; # BLAST is 1-based
1566             $record->{ "S_END" }      = $fields[ 9 ] - 1; # BLAST is 1-based
1567             $record->{ "E_VAL" }      = $fields[ 10 ];
1568             $record->{ "BIT_SCORE" }  = $fields[ 11 ];
1569
1570             if ( $record->{ "S_BEG" } > $record->{ "S_END" } )
1571             {
1572                 $record->{ "STRAND" } = '-';
1573
1574                 ( $record->{ "S_BEG" }, $record->{ "S_END" } ) = ( $record->{ "S_END" }, $record->{ "S_BEG" } );
1575             }
1576             else
1577             {
1578                 $record->{ "STRAND" } = '+';
1579             }
1580
1581             put_record( $record, $out );
1582
1583             goto NUM if $options->{ "num" } and $num == $options->{ "num" };
1584
1585             $num++;
1586         }
1587
1588         close $data_in;
1589     }
1590
1591     NUM:
1592
1593     close $data_in if $data_in;
1594 }
1595
1596
1597 sub script_read_embl
1598 {
1599     # Martin A. Hansen, August 2007.
1600
1601     # Read EMBL format.
1602
1603     my ( $in,        # handle to in stream
1604          $out,       # handle to out stream
1605          $options,   # options hash
1606        ) = @_;
1607
1608     # Returns nothing.
1609
1610     my ( %options2, $file, $data_in, $num, $entry, $record );
1611
1612     map { $options2{ "keys" }{ $_ } = 1 }  @{ $options->{ "keys" } };
1613     map { $options2{ "feats" }{ $_ } = 1 } @{ $options->{ "feats" } };
1614     map { $options2{ "quals" }{ $_ } = 1 } @{ $options->{ "quals" } };
1615
1616     while ( $record = get_record( $in ) ) {
1617         put_record( $record, $out );
1618     }
1619
1620     $num = 1;
1621
1622     foreach $file ( @{ $options->{ "files" } } )
1623     {
1624         $data_in = Maasha::Common::read_open( $file );
1625
1626         while ( $entry = Maasha::EMBL::get_embl_entry( $data_in ) ) 
1627         {
1628             $record = Maasha::EMBL::parse_embl_entry( $entry, \%options2 );
1629
1630             my ( $feat, $feat2, $qual, $qual_val, $record_copy );
1631
1632             $record_copy = dclone $record;
1633
1634             delete $record_copy->{ "FT" };
1635
1636             put_record( $record_copy, $out );
1637
1638             delete $record_copy->{ "SEQ" };
1639
1640             foreach $feat ( keys %{ $record->{ "FT" } } )
1641             {
1642                 $record_copy->{ "FEAT_TYPE" } = $feat;
1643
1644                 foreach $feat2 ( @{ $record->{ "FT" }->{ $feat } } )
1645                 {
1646                     foreach $qual ( keys %{ $feat2 } )
1647                     {
1648                         $qual_val = join "; ", @{ $feat2->{ $qual } };
1649
1650                         $qual =~ s/^_//;
1651                         $qual = uc $qual;
1652
1653                         $record_copy->{ $qual } = $qual_val;
1654                     }
1655
1656                     put_record( $record_copy, $out );
1657                 }
1658             }
1659
1660             goto NUM if $options->{ "num" } and $num == $options->{ "num" };
1661
1662             $num++;
1663         }
1664
1665         close $data_in;
1666     }
1667
1668     NUM:
1669
1670     close $data_in if $data_in;
1671 }
1672
1673
1674 sub script_read_stockholm
1675 {
1676     # Martin A. Hansen, August 2007.
1677
1678     # Read Stockholm format.
1679
1680     my ( $in,        # handle to in stream
1681          $out,       # handle to out stream
1682          $options,   # options hash
1683        ) = @_;
1684
1685     # Returns nothing.
1686
1687     my ( $data_in, $file, $num, $entry, $record, $record_anno, $record_align, $key, $seq );
1688
1689     while ( $record = get_record( $in ) ) {
1690         put_record( $record, $out );
1691     }
1692
1693     $num = 1;
1694
1695     foreach $file ( @{ $options->{ "files" } } )
1696     {
1697         $data_in = Maasha::Common::read_open( $file );
1698
1699         while ( $entry = Maasha::Stockholm::get_stockholm_entry( $data_in ) ) 
1700         {
1701             $record = Maasha::Stockholm::parse_stockholm_entry( $entry );
1702
1703             undef $record_anno;
1704
1705             foreach $key ( keys %{ $record->{ "GF" } } ) {
1706                 $record_anno->{ $key } = $record->{ "GF" }->{ $key };
1707             }
1708
1709             $record_anno->{ "ALIGN" } = $num;
1710
1711             put_record( $record_anno, $out );
1712
1713             foreach $seq ( @{ $record->{ "ALIGN" } } )
1714             {
1715                 undef $record_align;
1716             
1717                 $record_align = {
1718                     SEQ_NAME  => $seq->[ 0 ],
1719                     SEQ       => $seq->[ 1 ],
1720                 };
1721             
1722                 put_record( $record_align, $out );
1723             }
1724
1725             goto NUM if $options->{ "num" } and $num == $options->{ "num" };
1726
1727             $num++;
1728         }
1729
1730         close $data_in;
1731     }
1732
1733     NUM:
1734
1735     close $data_in if $data_in;
1736 }
1737
1738
1739 sub script_read_phastcons
1740 {
1741     # Martin A. Hansen, December 2007.
1742
1743     # Read PhastCons format.
1744
1745     my ( $in,        # handle to in stream
1746          $out,       # handle to out stream
1747          $options,   # options hash
1748        ) = @_;
1749
1750     # Returns nothing.
1751
1752     my ( $data_in, $file, $num, $entry, @records, $record );
1753
1754     $options->{ "min" }       ||= 10;
1755     $options->{ "dist" }      ||= 25;
1756     $options->{ "threshold" } ||= 0.8;
1757     $options->{ "gap" }       ||= 5;
1758
1759     while ( $record = get_record( $in ) ) {
1760         put_record( $record, $out );
1761     }
1762
1763     $num = 1;
1764
1765     foreach $file ( @{ $options->{ "files" } } )
1766     {
1767         $data_in = Maasha::Common::read_open( $file );
1768
1769         while ( $entry = Maasha::UCSC::fixedstep_get_entry( $data_in ) ) 
1770         {
1771             @records = Maasha::UCSC::phastcons_parse_entry( $entry, $options );
1772
1773             foreach $record ( @records )
1774             {
1775                 $record->{ "REC_TYPE" } = "BED";
1776                 $record->{ "BED_LEN" }  = $record->{ "CHR_END" } - $record->{ "CHR_BEG" } + 1;
1777
1778                 put_record( $record, $out );
1779
1780                 goto NUM if $options->{ "num" } and $num == $options->{ "num" };
1781
1782                 $num++;
1783             }
1784         }
1785
1786         close $data_in;
1787     }
1788
1789     NUM:
1790
1791     close $data_in if $data_in;
1792 }
1793
1794
1795 sub script_read_soft
1796 {
1797     # Martin A. Hansen, December 2007.
1798
1799     # Read soft format.
1800     # http://www.ncbi.nlm.nih.gov/geo/info/soft2.html
1801
1802     my ( $in,        # handle to in stream
1803          $out,       # handle to out stream
1804          $options,   # options hash
1805        ) = @_;
1806
1807     # Returns nothing.
1808
1809     my ( $data_in, $file, $num, $records, $record, $soft_index, $fh, @platforms, $plat_table, @samples, $sample, $old_end, $skip );
1810
1811     while ( $record = get_record( $in ) ) {
1812         put_record( $record, $out );
1813     }
1814
1815     $num = 1;
1816
1817     foreach $file ( @{ $options->{ "files" } } )
1818     {
1819         print STDERR "Creating index for file: $file\n" if $options->{ "verbose" };
1820
1821         $soft_index = Maasha::NCBI::soft_index_file( $file );
1822
1823         $fh         = Maasha::Common::read_open( $file );
1824
1825         @platforms  = grep { $_->{ "SECTION" } =~ /PLATFORM/ } @{ $soft_index };
1826
1827         print STDERR "Getting platform tables for file: $file\n" if $options->{ "verbose" };
1828
1829         $plat_table = Maasha::NCBI::soft_get_platform( $fh, $platforms[ 0 ]->{ "LINE_BEG" }, $platforms[ -1 ]->{ "LINE_END" } );
1830
1831         @samples    = grep { $_->{ "SECTION" } =~ /SAMPLE/ } @{ $soft_index };
1832
1833         $old_end    = $platforms[ -1 ]->{ "LINE_END" };
1834
1835         foreach $sample ( @samples )
1836         {
1837             $skip = 0;
1838             $skip = 1 if ( $options->{ "samples" } and grep { $sample->{ "SECTION" } !~ /$_/ } @{ $options->{ "samples" } } );
1839
1840             print STDERR "Getting samples for dataset: $sample->{ 'SECTION' }\n" if $options->{ "verbose" } and not $skip;
1841
1842             $records = Maasha::NCBI::soft_get_sample( $fh, $plat_table, $sample->{ "LINE_BEG" } - $old_end - 1, $sample->{ "LINE_END" } - $old_end - 1, $skip );
1843
1844             foreach $record ( @{ $records } )
1845             {
1846                 put_record( $record, $out );
1847
1848                 goto NUM if $options->{ "num" } and $num == $options->{ "num" };
1849
1850                 $num++;
1851             }
1852
1853             $old_end = $sample->{ "LINE_END" };
1854         }
1855
1856         close $fh;
1857     }
1858
1859     NUM:
1860
1861     close $data_in if $data_in;
1862     close $fh if $fh;
1863 }
1864
1865
1866 sub script_read_gff
1867 {
1868     # Martin A. Hansen, February 2008.
1869
1870     # Read soft format.
1871     # http://www.ncbi.nlm.nih.gov/geo/info/soft2.html
1872
1873     my ( $in,        # handle to in stream
1874          $out,       # handle to out stream
1875          $options,   # options hash
1876        ) = @_;
1877
1878     # Returns nothing.
1879
1880     my ( $data_in, $file, $fh, $num, $record, $entry );
1881
1882     while ( $record = get_record( $in ) ) {
1883         put_record( $record, $out );
1884     }
1885
1886     $num = 1;
1887
1888     foreach $file ( @{ $options->{ "files" } } )
1889     {
1890         $fh = Maasha::Common::read_open( $file );
1891
1892         while ( $entry = Maasha::GFF::get_entry( $fh ) )
1893         {
1894             put_record( $entry, $out );
1895
1896             goto NUM if $options->{ "num" } and $num == $options->{ "num" };
1897
1898             $num++;
1899         }
1900
1901         close $fh;
1902     }
1903
1904     NUM:
1905
1906     close $data_in if $data_in;
1907 }
1908
1909
1910 sub script_read_2bit
1911 {
1912     # Martin A. Hansen, March 2008.
1913
1914     # Read sequences from 2bit file.
1915
1916     my ( $in,        # handle to in stream
1917          $out,       # handle to out stream
1918          $options,   # options hash
1919        ) = @_;
1920
1921     # Returns nothing.
1922
1923     my ( $record, $file, $data_in, $mask, $toc, $line, $num );
1924
1925     $mask = 1 if not $options->{ "no_mask" };
1926
1927     while ( $record = get_record( $in ) ) {
1928         put_record( $record, $out );
1929     }
1930
1931     $num = 1;
1932
1933     foreach $file ( @{ $options->{ "files" } } )
1934     {
1935         $data_in = Maasha::Common::read_open( $file );
1936
1937         $toc = Maasha::TwoBit::twobit_get_TOC( $data_in );
1938
1939         foreach $line ( @{ $toc } )
1940         {
1941             $record->{ "SEQ_NAME" } = $line->[ 0 ];
1942             $record->{ "SEQ" }      = Maasha::TwoBit::twobit_get_seq( $data_in, $line->[ 1 ], undef, undef, $mask );
1943             $record->{ "SEQ_LEN" }  = length $record->{ "SEQ" };
1944
1945             put_record( $record, $out );
1946
1947             goto NUM if $options->{ "num" } and $num == $options->{ "num" };
1948
1949             $num++;
1950         }
1951
1952         close $data_in;
1953     }
1954
1955     NUM:
1956
1957     close $data_in if $data_in;
1958 }
1959
1960
1961 sub script_read_solexa
1962 {
1963     # Martin A. Hansen, March 2008.
1964
1965     # Read Solexa sequence reads from file.
1966
1967     my ( $in,        # handle to in stream
1968          $out,       # handle to out stream
1969          $options,   # options hash
1970        ) = @_;
1971
1972     # Returns nothing.
1973
1974     my ( $record, $file, $data_in, $entry, $num, @seqs, @scores, $i );
1975
1976     $options->{ "format" }  ||= "octal";
1977     $options->{ "quality" } ||= 20;
1978
1979     while ( $record = get_record( $in ) ) {
1980         put_record( $record, $out );
1981     }
1982
1983     $num = 1;
1984
1985     foreach $file ( @{ $options->{ "files" } } )
1986     {
1987         $data_in = Maasha::Common::read_open( $file );
1988
1989         if ( $options->{ "format" } eq "octal" )
1990         {
1991             while ( $entry = Maasha::Solexa::solexa_get_entry_octal( $data_in ) )
1992             {
1993                 $record = Maasha::Solexa::solexa2biopiece( $entry, $options->{ "quality" } );
1994
1995                 put_record( $record, $out );
1996
1997                 goto NUM if $options->{ "num" } and $num == $options->{ "num" };
1998
1999                 $num++;
2000             }
2001         }
2002         else
2003         {
2004             while ( $entry = Maasha::Solexa::solexa_get_entry_decimal( $data_in ) )
2005             {
2006                 $record = Maasha::Solexa::solexa2biopiece( $entry, $options->{ "quality" } );
2007
2008                 put_record( $record, $out );
2009
2010                 goto NUM if $options->{ "num" } and $num == $options->{ "num" };
2011
2012                 $num++;
2013             }
2014         }
2015
2016         close $data_in;
2017     }
2018
2019     NUM:
2020
2021     close $data_in if $data_in;
2022 }
2023
2024
2025 sub script_read_solid
2026 {
2027     # Martin A. Hansen, April 2008.
2028
2029     # Read Solid sequence from file.
2030
2031     my ( $in,        # handle to in stream
2032          $out,       # handle to out stream
2033          $options,   # options hash
2034        ) = @_;
2035
2036     # Returns nothing.
2037
2038     my ( $record, $file, $data_in, $line, $num, $seq_name, $seq_cs, $seq_qual, @scores, @seqs, $i );
2039
2040     $options->{ "quality" } ||= 15;
2041
2042     while ( $record = get_record( $in ) ) {
2043         put_record( $record, $out );
2044     }
2045
2046     $num = 1;
2047
2048     foreach $file ( @{ $options->{ "files" } } )
2049     {
2050         $data_in = Maasha::Common::read_open( $file );
2051
2052         while ( $line = <$data_in> )
2053         {
2054             chomp $line;
2055
2056             ( $seq_name, $seq_cs, $seq_qual ) = split /\t/, $line;
2057
2058             @scores = split /,/, $seq_qual;
2059             @seqs   = split //, Maasha::Solid::color_space2seq( $seq_cs );
2060
2061             for ( $i = 0; $i < @seqs; $i++ ) {
2062                 $seqs[ $i ] = lc $seqs[ $i ] if $scores[ $i ] < $options->{ "quality" };
2063             }
2064
2065             $record = {
2066                 REC_TYPE   => 'SOLID',
2067                 SEQ_NAME   => $seq_name,
2068                 SEQ_CS     => $seq_cs,
2069                 SEQ_QUAL   => join( ";", @scores ),
2070                 SEQ_LEN    => length $seq_cs,
2071                 SEQ        => join( "", @seqs ),
2072                 SCORE_MEAN => sprintf( "%.2f", Maasha::Calc::mean( \@scores ) ),
2073             };
2074
2075             put_record( $record, $out );
2076
2077             goto NUM if $options->{ "num" } and $num == $options->{ "num" };
2078
2079             $num++;
2080         }
2081
2082         close $data_in;
2083     }
2084
2085     NUM:
2086
2087     close $data_in if $data_in;
2088 }
2089
2090
2091 sub script_read_mysql
2092 {
2093     # Martin A. Hansen, May 2008.
2094
2095     # Read a MySQL query into stream.
2096
2097     my ( $in,        # handle to in stream
2098          $out,       # handle to out stream
2099          $options,   # options hash
2100        ) = @_;
2101
2102     # Returns nothing.
2103
2104     my ( $record, $dbh, $results );
2105
2106     $options->{ "user" }     ||= Maasha::UCSC::ucsc_get_user();
2107     $options->{ "password" } ||= Maasha::UCSC::ucsc_get_password();
2108
2109     while ( $record = get_record( $in ) ) {
2110         put_record( $record, $out );
2111     }
2112
2113     $dbh = Maasha::SQL::connect( $options->{ "database" }, $options->{ "user" }, $options->{ "password" } );
2114
2115     $results = Maasha::SQL::query_hashref_list( $dbh, $options->{ "query" } );
2116
2117     Maasha::SQL::disconnect( $dbh );
2118
2119     map { put_record( $_ ) } @{ $results };
2120 }
2121
2122
2123 sub script_read_ucsc_config
2124 {
2125     # Martin A. Hansen, November 2008.
2126
2127     # Read track entries from UCSC Genome Browser '.ra' files.
2128
2129     my ( $in,        # handle to in stream
2130          $out,       # handle to out stream
2131          $options,   # options hash
2132        ) = @_;
2133
2134     # Returns nothing.
2135
2136     my ( $record, $file, $data_in, $entry, $num );
2137
2138     while ( $record = get_record( $in ) ) {
2139         put_record( $record, $out );
2140     }
2141
2142     $num = 1;
2143
2144     foreach $file ( @{ $options->{ "files" } } )
2145     {
2146         $data_in = Maasha::Common::read_open( $file );
2147
2148         while ( $record = Maasha::UCSC::ucsc_config_get_entry( $data_in ) ) 
2149         {
2150             $record->{ 'REC_TYPE' } = "UCSC Config";
2151
2152             put_record( $record, $out );
2153
2154             goto NUM if $options->{ "num" } and $num == $options->{ "num" };
2155
2156             $num++;
2157         }
2158
2159         close $data_in;
2160     }
2161
2162     NUM:
2163
2164     close $data_in if $data_in;
2165 }
2166
2167
2168 sub script_assemble_tag_contigs
2169 {
2170     # Martin A. Hansen, November 2008.
2171
2172     # Assemble tags from the stream into
2173     # tag contigs.
2174
2175     my ( $in,        # handle to in stream
2176          $out,       # handle to out stream
2177          $options,   # options hash
2178        ) = @_;
2179
2180     # Returns nothing.
2181
2182     my ( $record, $new_record, %fh_hash, $fh_out, $chr, $array, $pos, $beg, $end, $score, $file, $id );
2183
2184     while ( $record = get_record( $in ) ) 
2185     {
2186         $record->{ "CHR" }     = $record->{ "S_ID" }  if not defined $record->{ "CHR" };
2187         $record->{ "CHR_BEG" } = $record->{ "S_BEG" } if not defined $record->{ "CHR_BEG" };
2188         $record->{ "CHR_END" } = $record->{ "S_END" } if not defined $record->{ "CHR_END" };
2189
2190         if ( $record->{ "CHR" } and defined $record->{ "CHR_BEG" } and $record->{ "CHR_END" } )
2191         {
2192             $fh_hash{ $record->{ "CHR" } } = Maasha::Common::write_open( "$BP_TMP/$record->{ 'CHR' }" ) if not exists $fh_hash{ $record->{ "CHR" } };
2193
2194             $fh_out = $fh_hash{ $record->{ "CHR" } };
2195         
2196             Maasha::UCSC::bed_put_entry( $record, $fh_out, 5 );
2197         }
2198     }
2199
2200     map { close $_ } keys %fh_hash;
2201
2202     foreach $chr ( sort keys %fh_hash )
2203     {
2204         $array = tag_contigs_assemble( "$BP_TMP/$chr" );
2205
2206         $pos = 0;
2207         $id  = 0;
2208
2209         while ( ( $beg, $end, $score ) = tag_contigs_scan( $array, $pos ) and $beg )
2210         {
2211             $new_record = {
2212                 CHR     => $chr,
2213                 CHR_BEG => $beg,
2214                 CHR_END => $end - 1,
2215                 Q_ID    => sprintf( "TC%06d", $id ),
2216                 SCORE   => $score,
2217                 STRAND  => $record->{ 'STRAND' } || '+',
2218             };
2219
2220             put_record( $new_record, $out );
2221
2222             $pos = $end;
2223             $id++;
2224         }
2225
2226         unlink "$BP_TMP/$chr";
2227     }
2228 }
2229
2230
2231 sub tag_contigs_assemble
2232 {
2233     # Martin A. Hansen, November 2008.
2234
2235     # Given a BED file with entries from only one
2236     # chromosome assembles tag contigs from these
2237     # ignoring strand information. Only tags with
2238     # a score higher than the clone count over
2239     # genomic loci (the SCORE field) is included
2240     # in the tag contigs.
2241
2242     #       -----------              tags
2243     #          -------------
2244     #               ----------
2245     #                     ----------
2246     #       ========================  tag contig
2247
2248
2249     my ( $path,   # full path to BED file
2250        ) = @_;
2251
2252     # Returns an arrayref.
2253
2254     my ( $fh, $entry, $clones, $score, @array );
2255
2256     $fh = Maasha::Common::read_open( $path );
2257
2258     while ( $entry = Maasha::UCSC::bed_get_entry( $fh ) )
2259     {
2260         if ( $entry->{ 'Q_ID' } =~ /(\d+)$/ )
2261         {
2262             $clones = $1;
2263
2264             $score = int( $clones / $entry->{ 'SCORE' } );
2265         
2266             map { $array[ $_ ] += $score } $entry->{ 'CHR_BEG' } .. $entry->{ 'CHR_END' } if $score >= 1;
2267         }
2268     }
2269
2270     close $fh;
2271
2272     return wantarray ? @array : \@array;
2273 }
2274
2275
2276 sub tag_contigs_scan
2277 {
2278     # Martin A. Hansen, November 2008.
2279     
2280     # Scans an array with tag contigs and locates
2281     # the next contig from a given position. The
2282     # score of the tag contig is determined as the
2283     # maximum value of the tag contig. If a tag contig
2284     # is found a triple is returned with beg, end and score
2285     # otherwise an empty triple is returned.
2286
2287     my ( $array,   # array to scan
2288          $beg,     # position to start scanning from
2289        ) = @_;
2290
2291     # Returns an arrayref.
2292
2293     my ( $end, $score );
2294
2295     $score = 0;
2296
2297     while ( $beg < scalar @{ $array } and not $array->[ $beg ] ) { $beg++ }
2298
2299     $end = $beg;
2300
2301     while ( $array->[ $end ] )
2302     {
2303         $score = Maasha::Calc::max( $score, $array->[ $end ] );
2304     
2305         $end++
2306     }
2307
2308     if ( $score > 0 ) {
2309         return wantarray ? ( $beg, $end, $score ) : [ $beg, $end, $score ];
2310     } else {
2311         return wantarray ? () : [];
2312     }
2313 }
2314
2315
2316 sub script_format_genome
2317 {
2318     # Martin A. Hansen, Juli 2008.
2319
2320     # Format a genome to speficed formats.
2321
2322     my ( $in,        # handle to in stream
2323          $out,       # handle to out stream
2324          $options,   # options hash
2325        ) = @_;
2326
2327     # Returns nothing.
2328
2329     my ( $dir, $genome, $fasta_dir, $phastcons_dir, $vals, $fh_out, $record, $format, $index, $entry );
2330
2331     $dir    = $options->{ 'dir' } || $ENV{ 'BP_DATA' };
2332     $genome = $options->{ 'genome' };
2333
2334     Maasha::Common::error( "Directory: $dir does not exist" ) if not -d $dir;
2335     Maasha::Common::dir_create_if_not_exists( "$dir/genomes" );
2336     Maasha::Common::dir_create_if_not_exists( "$dir/genomes/$genome" );
2337
2338     if ( grep { $_ =~ /fasta|blast|vmatch/i } @{ $options->{ "formats" } } )
2339     {
2340         if ( -f "$dir/genomes/$genome/fasta/$genome.fna" )
2341         {
2342             $fasta_dir = "$dir/genomes/$genome/fasta";
2343         }
2344         else
2345         {
2346             Maasha::Common::dir_create_if_not_exists( "$dir/genomes/$genome/fasta" );
2347
2348             $fasta_dir = "$dir/genomes/$genome/fasta";
2349
2350             $fh_out = Maasha::Common::write_open( "$fasta_dir/$genome.fna" );
2351         }
2352     }
2353     elsif ( grep { $_ =~ /phastcons/i } @{ $options->{ "formats" } } )
2354     {
2355         Maasha::Common::dir_create_if_not_exists( "$dir/genomes/$genome/phastcons" );
2356     
2357         $phastcons_dir = "$dir/genomes/$genome/phastcons";
2358
2359         $fh_out = Maasha::Common::write_open( "$phastcons_dir/$genome.pp" );
2360     }
2361
2362     while ( $record = get_record( $in ) ) 
2363     {
2364         if ( $fh_out and $entry = record2fasta( $record ) )
2365         {
2366             Maasha::Fasta::put_entry( $entry, $fh_out, $options->{ "wrap" } );
2367         }
2368         elsif ( $fh_out and $record->{ "CHR" } and $record->{ "CHR_BEG" } and $record->{ "STEP" } and $record->{ "VALS" } )
2369         {
2370             print $fh_out "fixedStep chrom=$record->{ 'CHR' } start=$record->{ 'CHR_BEG' } step=$record->{ 'STEP' }\n";
2371
2372             $vals = $record->{ 'VALS' };
2373
2374             $vals =~ tr/,/\n/;
2375
2376             print $fh_out "$vals\n";
2377         }
2378
2379         put_record( $record, $out ) if not $options->{ "no_stream" };
2380     }
2381
2382     foreach $format ( @{ $options->{ 'formats' } } )
2383     {
2384         if    ( $format =~ /^fasta$/i )     { Maasha::Fasta::fasta_index( "$fasta_dir/$genome.fna", "$dir/genomes/$genome/fasta/$genome.index" ) }
2385         elsif ( $format =~ /^blast$/i )     { Maasha::NCBI::blast_index( "$genome.fna", $fasta_dir, "$dir/genomes/$genome/blast", "dna", $genome ) }
2386         elsif ( $format =~ /^blat$/i )      { print STDERR "BLAT FORMAT NOT IMPLEMENTED" }
2387         elsif ( $format =~ /^vmatch$/i )    { Maasha::Match::vmatch_index( "$genome.fna", $fasta_dir, "$dir/genomes/$genome/vmatch", $BP_TMP ) }
2388         elsif ( $format =~ /^phastcons$/i ) { Maasha::UCSC::phastcons_index( "$genome.pp", $phastcons_dir ) }
2389     }
2390
2391     close $fh_out if $fh_out;
2392 }
2393
2394
2395 sub script_length_seq
2396 {
2397     # Martin A. Hansen, August 2007.
2398
2399     # Determine the length of sequences in stream.
2400
2401     my ( $in,        # handle to in stream
2402          $out,       # handle to out stream
2403          $options,   # options hash
2404        ) = @_;
2405
2406     # Returns nothing.
2407
2408     my ( $record, $total );
2409
2410     while ( $record = get_record( $in ) ) 
2411     {
2412         if ( $record->{ "SEQ" } )
2413         {
2414             $record->{ "SEQ_LEN" } = length $record->{ "SEQ" };
2415             $total += $record->{ "SEQ_LEN" };
2416         }
2417
2418         put_record( $record, $out ) if not $options->{ "no_stream" };
2419     }
2420
2421     put_record( { TOTAL_SEQ_LEN => $total }, $out );
2422 }
2423
2424
2425 sub script_uppercase_seq
2426 {
2427     # Martin A. Hansen, August 2007.
2428
2429     # Uppercases sequences in stream.
2430
2431     my ( $in,    # handle to in stream
2432          $out,   # handle to out stream
2433        ) = @_;
2434
2435     # Returns nothing.
2436
2437     my ( $record );
2438
2439     while ( $record = get_record( $in ) ) 
2440     {
2441         $record->{ "SEQ" } = uc $record->{ "SEQ" } if $record->{ "SEQ" };
2442
2443         put_record( $record, $out );
2444     }
2445 }
2446
2447
2448 sub script_shuffle_seq
2449 {
2450     # Martin A. Hansen, December 2007.
2451
2452     # Shuffle sequences in stream.
2453
2454     my ( $in,    # handle to in stream
2455          $out,   # handle to out stream
2456        ) = @_;
2457
2458     # Returns nothing.
2459
2460     my ( $record );
2461
2462     while ( $record = get_record( $in ) ) 
2463     {
2464         $record->{ "SEQ" } = Maasha::Seq::seq_shuffle( $record->{ "SEQ" } ) if $record->{ "SEQ" };
2465
2466         put_record( $record, $out );
2467     }
2468 }
2469
2470
2471 sub script_analyze_seq
2472 {
2473     # Martin A. Hansen, August 2007.
2474
2475     # Analyze sequence composition of sequences in stream.
2476
2477     my ( $in,     # handle to in stream
2478          $out,    # handle to out stream
2479        ) = @_;
2480
2481     # Returns nothing.
2482
2483     my ( $record, $analysis );
2484
2485     while ( $record = get_record( $in ) ) 
2486     {
2487         if ( $record->{ "SEQ" } )
2488         {
2489             $analysis = Maasha::Seq::seq_analyze( $record->{ "SEQ" } );
2490
2491             map { $record->{ $_ } = $analysis->{ $_ } } keys %{ $analysis };
2492         }
2493
2494         put_record( $record, $out );
2495     }
2496 }
2497
2498
2499 sub script_analyze_tags
2500 {
2501     # Martin A. Hansen, August 2008.
2502
2503     # Analyze sequence tags in stream.
2504
2505     my ( $in,     # handle to in stream
2506          $out,    # handle to out stream
2507        ) = @_;
2508
2509     # Returns nothing.
2510
2511     my ( $record, $analysis, %len_hash, %clone_hash, $clones, $key, $tag_record );
2512
2513     while ( $record = get_record( $in ) ) 
2514     {
2515         if ( $record->{ "SEQ_NAME" } and $record->{ "SEQ" } )
2516         {
2517             if ( $record->{ "SEQ_NAME" } =~ /_(\d+)$/ )
2518             {
2519                 $clones = $1;
2520
2521                 $len_hash{ length( $record->{ "SEQ" } ) }++;
2522                 $clone_hash{ length( $record->{ "SEQ" } ) } += $clones;
2523             }
2524         }
2525         elsif ( $record->{ "Q_ID" } and $record->{ "BED_LEN" } )
2526         {
2527             if ( $record->{ "Q_ID" } =~ /_(\d+)$/ )
2528             {
2529                 $clones = $1;
2530
2531                 $len_hash{ $record->{ "BED_LEN" } }++;
2532                 $clone_hash{ $record->{ "BED_LEN" } } += $clones;
2533             }
2534         }
2535     }
2536
2537     foreach $key ( sort { $a <=> $b } keys %len_hash )
2538     {
2539         $tag_record->{ "TAG_LEN" }    = $key;
2540         $tag_record->{ "TAG_COUNT" }  = $len_hash{ $key };
2541         $tag_record->{ "TAG_CLONES" } = $clone_hash{ $key };
2542  
2543         put_record( $tag_record, $out );
2544     }
2545 }
2546
2547
2548 sub script_complexity_seq
2549 {
2550     # Martin A. Hansen, May 2008.
2551
2552     # Generates an index calculated as the most common di-residue over
2553     # the sequence length for all sequences in stream.
2554
2555     my ( $in,     # handle to in stream
2556          $out,    # handle to out stream
2557        ) = @_;
2558
2559     # Returns nothing.
2560
2561     my ( $record, $index );
2562
2563     while ( $record = get_record( $in ) ) 
2564     {
2565         $record->{ "SEQ_COMPLEXITY" } = sprintf( "%.2f", Maasha::Seq::seq_complexity( $record->{ "SEQ" } ) ) if $record->{ "SEQ" };
2566
2567         put_record( $record, $out );
2568     }
2569 }
2570
2571
2572 sub script_oligo_freq
2573 {
2574     # Martin A. Hansen, August 2007.
2575
2576     # Determine the length of sequences in stream.
2577
2578     my ( $in,        # handle to in stream
2579          $out,       # handle to out stream
2580          $options,   # options hash
2581        ) = @_;
2582
2583     # Returns nothing.
2584
2585     my ( $record, %oligos, @freq_table );
2586
2587     $options->{ "word_size" } ||= 7;
2588
2589     while ( $record = get_record( $in ) ) 
2590     {
2591         if ( $record->{ "SEQ" } )
2592         {
2593             map { $oligos{ $_ }++ } Maasha::Seq::seq2oligos( \$record->{ "SEQ" }, $options->{ "word_size" } );
2594
2595             if ( not $options->{ "all" } )
2596             {
2597                 @freq_table = Maasha::Seq::oligo_freq( \%oligos );
2598
2599                 map { put_record( $_, $out ) } @freq_table;
2600             
2601                 undef %oligos;
2602             }
2603         }
2604
2605         put_record( $record, $out );
2606     }
2607
2608     if ( $options->{ "all" } )
2609     {
2610         @freq_table = Maasha::Seq::oligo_freq( \%oligos );
2611
2612         map { put_record( $_, $out ) } @freq_table;
2613     }
2614 }
2615
2616
2617 sub script_create_weight_matrix
2618 {
2619     # Martin A. Hansen, August 2007.
2620
2621     # Creates a weight matrix from an alignmnet.
2622
2623     my ( $in,        # handle to in stream
2624          $out,       # handle to out stream
2625          $options,   # options hash
2626        ) = @_;
2627
2628     # Returns nothing.
2629
2630     my ( $record, $count, $i, $res, %freq_hash, %res_hash, $freq );
2631
2632     $count = 0;
2633     
2634     while ( $record = get_record( $in ) ) 
2635     {
2636         if ( $record->{ "SEQ" } )
2637         {
2638             for ( $i = 0; $i < length $record->{ "SEQ" }; $i++ )
2639             {
2640                 $res = substr $record->{ "SEQ" }, $i, 1;
2641
2642                 $freq_hash{ $i }{ $res }++;
2643                 $res_hash{ $res } = 1;
2644             }
2645
2646             $count++;
2647         }
2648         else
2649         {
2650             put_record( $record, $out );
2651         }
2652     }
2653
2654     foreach $res ( sort keys %res_hash )
2655     {
2656         undef $record;
2657
2658         $record->{ "V0" } = $res;
2659
2660         for ( $i = 0; $i < keys %freq_hash; $i++ )
2661         {
2662             $freq = $freq_hash{ $i }{ $res } || 0;
2663
2664             if ( $options->{ "percent" } ) {
2665                 $freq = sprintf( "%.0f", 100 * $freq / $count ) if $freq > 0;
2666             }
2667
2668             $record->{ "V" . ( $i + 1 ) } = $freq;
2669         }
2670
2671         put_record( $record, $out );
2672     }
2673 }
2674
2675
2676 sub script_calc_bit_scores
2677 {
2678     # Martin A. Hansen, March 2007.
2679
2680     # Calculates the bit scores for each position from an alignmnet in the stream.
2681
2682     my ( $in,        # handle to in stream
2683          $out,       # handle to out stream
2684        ) = @_;
2685
2686     # Returns nothing.
2687
2688     my ( $record, $type, $count, $i, $res, %freq_hash, $bit_max, $bit_height, $bit_diff );
2689
2690     $count = 0;
2691
2692     while ( $record = get_record( $in ) ) 
2693     {
2694         if ( $record->{ "SEQ" } )
2695         {
2696             $type = Maasha::Seq::seq_guess_type( $record->{ "SEQ" } ) if not $type;
2697
2698             for ( $i = 0; $i < length $record->{ "SEQ" }; $i++ )
2699             {
2700                 $res = substr $record->{ "SEQ" }, $i, 1;
2701
2702                 next if $res =~ /-|_|~|\./;
2703
2704                 $freq_hash{ $i }{ $res }++;
2705             }
2706
2707             $count++;
2708         }
2709         else
2710         {
2711             put_record( $record, $out );
2712         }
2713     }
2714
2715     undef $record;
2716
2717     if ( $type eq "protein" ) {
2718         $bit_max = 4;
2719     } else {
2720         $bit_max = 2;
2721     }
2722
2723     for ( $i = 0; $i < keys %freq_hash; $i++ )
2724     {
2725         $bit_height = Maasha::Seq::seqlogo_calc_bit_height( $freq_hash{ $i }, $count );
2726
2727         $bit_diff = $bit_max - $bit_height;
2728
2729         $record->{ "V" . ( $i ) } = sprintf( "%.2f", $bit_diff );
2730     }
2731
2732     put_record( $record, $out );
2733 }
2734
2735
2736 sub script_calc_fixedstep
2737 {
2738     # Martin A. Hansen, September 2008.
2739
2740     # Calculates fixedstep entries from data in the stream.
2741
2742     my ( $in,        # handle to in stream
2743          $out,       # handle to out stream
2744          $options,   # options hash
2745        ) = @_;
2746
2747     # Returns nothing.
2748
2749     my ( $record, %fh_hash, $fh_in, $fh_out, $chr, $chr, $beg, $end, $q_id, $block, $entry, $clones, $beg_block, $max, $i );
2750
2751     while ( $record = get_record( $in ) ) 
2752     {
2753         $record->{ "CHR" }     = $record->{ "S_ID" }  if not defined $record->{ "CHR" };
2754         $record->{ "CHR_BEG" } = $record->{ "S_BEG" } if not defined $record->{ "CHR_BEG" };
2755         $record->{ "CHR_END" } = $record->{ "S_END" } if not defined $record->{ "CHR_END" };
2756
2757         if ( $record->{ "CHR" } and defined $record->{ "CHR_BEG" } and $record->{ "CHR_END" } )
2758         {
2759             $fh_hash{ $record->{ "CHR" } } = Maasha::Common::write_open( "$BP_TMP/$record->{ 'CHR' }" ) if not exists $fh_hash{ $record->{ "CHR" } };
2760
2761             $fh_out = $fh_hash{ $record->{ "CHR" } };
2762         
2763             Maasha::UCSC::bed_put_entry( $record, $fh_out, 5 );
2764         }
2765     }
2766
2767     map { close $_ } keys %fh_hash;
2768
2769     foreach $chr ( sort keys %fh_hash )
2770     {
2771         #Maasha::Common::run( "bedSort", "$BP_TMP/$chr $BP_TMP/$chr" );
2772         Maasha::Common::run( "bed_sort", "--sort 3 --cols 5 $BP_TMP/$chr > $BP_TMP/$chr.sort" );
2773
2774         rename "$BP_TMP/$chr.sort", "$BP_TMP/$chr";
2775
2776         $fh_in = Maasha::Common::read_open( "$BP_TMP/$chr" );
2777
2778         undef $block;
2779
2780         while ( $entry = Maasha::UCSC::bed_get_entry( $fh_in, 5 ) )
2781         {
2782             $chr  = $entry->{ 'CHR' };
2783             $beg  = $entry->{ 'CHR_BEG' };
2784             $end  = $entry->{ 'CHR_END' };
2785             $q_id = $entry->{ 'Q_ID' };
2786             
2787             if ( $options->{ "score" } ) {
2788                 $clones = $entry->{ 'SCORE' };
2789             } elsif ( $q_id =~ /_(\d+)$/ ) {
2790                 $clones = $1;
2791             } else {
2792                 $clones = 1;
2793             }
2794
2795             if ( $block )
2796             {
2797                 if ( $beg > $max )
2798                 {
2799                     map { $_ = sprintf( "%.4f", Maasha::Calc::log10( $_ ) ) } @{ $block } if $options->{ "log10" };
2800
2801                     $record->{ "CHR" }      = $chr;
2802                     $record->{ "CHR_BEG" }  = $beg_block;
2803                     $record->{ "STEP" }     = 1;
2804                     $record->{ "VALS" }     = join ";", @{ $block };
2805                     $record->{ "REC_TYPE" } = "fixed_step";
2806
2807                     put_record( $record, $out );
2808
2809                     undef $block;
2810                 }
2811                 else
2812                 {
2813                     for ( $i = $beg - $beg_block; $i < ( $beg - $beg_block ) + ( $end - $beg ); $i++ ) {
2814                         $block->[ $i ] += $clones;
2815                     }
2816
2817                     $max = Maasha::Calc::max( $max, $end );
2818                 }
2819             }
2820
2821             if ( not $block )
2822             {
2823                 $beg_block = $beg;
2824                 $max       = $end;
2825
2826                 for ( $i = 0; $i < ( $end - $beg ); $i++ ) {
2827                     $block->[ $i ] += $clones;
2828                 }
2829             }
2830         }
2831
2832         close $fh_in;
2833
2834         map { $_ = sprintf( "%.4f", Maasha::Calc::log10( $_ ) ) } @{ $block } if $options->{ "log10" };
2835
2836         $record->{ "CHR" }      = $chr;
2837         $record->{ "CHR_BEG" }  = $beg_block;
2838         $record->{ "STEP" }     = 1;
2839         $record->{ "VALS" }     = join ";", @{ $block };
2840         $record->{ "REC_TYPE" } = "fixed_step";
2841
2842         put_record( $record, $out );
2843
2844         unlink "$BP_TMP/$chr";
2845     }
2846 }
2847
2848
2849 sub script_reverse_seq
2850 {
2851     # Martin A. Hansen, August 2007.
2852
2853     # Reverse sequence in record.
2854
2855     my ( $in,    # handle to in stream
2856          $out,   # handle to out stream
2857        ) = @_;
2858
2859     # Returns nothing.
2860
2861     my ( $record );
2862
2863     while ( $record = get_record( $in ) ) 
2864     {
2865         if ( $record->{ "SEQ" } ) {
2866             $record->{ "SEQ" } = reverse $record->{ "SEQ" };
2867         }
2868
2869         put_record( $record, $out );
2870     }
2871 }
2872
2873
2874 sub script_complement_seq
2875 {
2876     # Martin A. Hansen, August 2007.
2877
2878     # Complement sequence in record.
2879
2880     my ( $in,     # handle to in stream
2881          $out,    # handle to out stream
2882        ) = @_;
2883
2884     # Returns nothing.
2885
2886     my ( $record, $type );
2887
2888     while ( $record = get_record( $in ) ) 
2889     {
2890         if ( $record->{ "SEQ" } )
2891         {
2892             if ( not $type ) {
2893                 $type = Maasha::Seq::seq_guess_type( $record->{ "SEQ" } );
2894             }
2895             
2896             if ( $type eq "rna" ) {
2897                 Maasha::Seq::rna_comp( \$record->{ "SEQ" } );
2898             } elsif ( $type eq "dna" ) {
2899                 Maasha::Seq::dna_comp( \$record->{ "SEQ" } );
2900             }
2901         }
2902
2903         put_record( $record, $out );
2904     }
2905 }
2906
2907
2908 sub script_remove_indels
2909 {
2910     # Martin A. Hansen, August 2007.
2911
2912     # Remove indels from sequences in stream.
2913
2914     my ( $in,     # handle to in stream
2915          $out,    # handle to out stream
2916        ) = @_;
2917
2918     # Returns nothing.
2919
2920     my ( $record );
2921
2922     while ( $record = get_record( $in ) ) 
2923     {
2924         $record->{ 'SEQ' } =~ tr/-~.//d if $record->{ "SEQ" };
2925
2926         put_record( $record, $out );
2927     }
2928 }
2929
2930
2931 sub script_transliterate_seq
2932 {
2933     # Martin A. Hansen, August 2007.
2934
2935     # Transliterate chars from sequence in record.
2936
2937     my ( $in,        # handle to in stream
2938          $out,       # handle to out stream
2939          $options,   # options hash
2940        ) = @_;
2941
2942     # Returns nothing.
2943
2944     my ( $record, $search, $replace, $delete );
2945
2946     $search  = $options->{ "search" }  || "";
2947     $replace = $options->{ "replace" } || "";
2948     $delete  = $options->{ "delete" }  || "";
2949
2950     while ( $record = get_record( $in ) ) 
2951     {
2952         if ( $record->{ "SEQ" } )
2953         {
2954             if ( $search and $replace ) {
2955                 eval "\$record->{ 'SEQ' } =~ tr/$search/$replace/";
2956             } elsif ( $delete ) {
2957                 eval "\$record->{ 'SEQ' } =~ tr/$delete//d";
2958             }
2959         }
2960
2961         put_record( $record, $out );
2962     }
2963 }
2964
2965
2966 sub script_transliterate_vals
2967 {
2968     # Martin A. Hansen, April 2008.
2969
2970     # Transliterate chars from values in record.
2971
2972     my ( $in,        # handle to in stream
2973          $out,       # handle to out stream
2974          $options,   # options hash
2975        ) = @_;
2976
2977     # Returns nothing.
2978
2979     my ( $record, $search, $replace, $delete, $key );
2980
2981     $search  = $options->{ "search" }  || "";
2982     $replace = $options->{ "replace" } || "";
2983     $delete  = $options->{ "delete" }  || "";
2984
2985     while ( $record = get_record( $in ) ) 
2986     {
2987         foreach $key ( @{ $options->{ "keys" } } )
2988         {
2989             if ( exists $record->{ $key } )
2990             {
2991                 if ( $search and $replace ) {
2992                     eval "\$record->{ $key } =~ tr/$search/$replace/";
2993                 } elsif ( $delete ) {
2994                     eval "\$record->{ $key } =~ tr/$delete//d";
2995                 }
2996             }
2997         }
2998
2999         put_record( $record, $out );
3000     }
3001 }
3002
3003
3004 sub script_translate_seq
3005 {
3006     # Martin A. Hansen, February 2008.
3007
3008     # Translate DNA sequence into protein sequence.
3009
3010     my ( $in,        # handle to in stream
3011          $out,       # handle to out stream
3012          $options,   # options hash
3013        ) = @_;
3014
3015     # Returns nothing.
3016
3017     my ( $record, $frame, %new_record );
3018
3019     $options->{ "frames" } ||= [ 1, 2, 3, -1, -2, -3 ];
3020
3021     while ( $record = get_record( $in ) ) 
3022     {
3023         if ( $record->{ "SEQ" } )
3024         {
3025             if ( Maasha::Seq::seq_guess_type( $record->{ "SEQ" } ) eq "dna" )
3026             {
3027                 foreach $frame ( @{ $options->{ "frames" } } )
3028                 {
3029                     %new_record = %{ $record };
3030
3031                     $new_record{ "SEQ" }     = Maasha::Seq::translate( $record->{ "SEQ" }, $frame );
3032                     $new_record{ "SEQ_LEN" } = length $new_record{ "SEQ" };
3033                     $new_record{ "FRAME" }   = $frame;
3034
3035                     put_record( \%new_record, $out );
3036                 }
3037             }
3038         }
3039         else
3040         {
3041             put_record( $record, $out );
3042         }
3043     }
3044 }
3045
3046
3047 sub script_extract_seq
3048 {
3049     # Martin A. Hansen, August 2007.
3050
3051     # Extract subsequences from sequences in record.
3052
3053     my ( $in,        # handle to in stream
3054          $out,       # handle to out stream
3055          $options,   # options hash
3056        ) = @_;
3057
3058     # Returns nothing.
3059
3060     my ( $beg, $end, $len, $record );
3061
3062     if ( not defined $options->{ "beg" } or $options->{ "beg" } < 0 ) {
3063         $beg = 0;
3064     } else {
3065         $beg = $options->{ "beg" } - 1;   # correcting for start offset
3066     }
3067
3068     if ( defined $options->{ "end" } and $options->{ "end" } - 1 < $beg ) {
3069         $end = $beg - 1;
3070     } elsif ( defined $options->{ "end" } ) {
3071         $end = $options->{ "end" } - 1;   # correcting for start offset
3072     }
3073
3074     $len = $options->{ "len" };
3075
3076 #    print "beg->$beg,  end->$end,  len->$len\n";
3077
3078     while ( $record = get_record( $in ) ) 
3079     {
3080         if ( $record->{ "SEQ" } )
3081         {
3082             if ( defined $beg and defined $end )
3083             {
3084                 if ( $end - $beg + 1 > length $record->{ "SEQ" } ) {
3085                     $record->{ "SEQ" } = substr $record->{ "SEQ" }, $beg;
3086                 } else {
3087                     $record->{ "SEQ" } = substr $record->{ "SEQ" }, $beg, $end - $beg + 1;
3088                 }
3089             }
3090             elsif ( defined $beg and defined $len )
3091             {
3092                 if ( $len > length $record->{ "SEQ" } ) {
3093                     $record->{ "SEQ" } = substr $record->{ "SEQ" }, $beg;
3094                 } else {
3095                     $record->{ "SEQ" } = substr $record->{ "SEQ" }, $beg, $len;
3096                 }
3097             }
3098             elsif ( defined $beg )
3099             {
3100                 $record->{ "SEQ" } = substr $record->{ "SEQ" }, $beg;
3101             }
3102         }
3103
3104         $record->{ "SEQ_LEN" } = length $record->{ "SEQ" };
3105
3106         put_record( $record, $out );
3107     }
3108 }
3109
3110
3111 sub script_get_genome_seq
3112 {
3113     # Martin A. Hansen, December 2007.
3114
3115     # Gets a subsequence from a genome.
3116
3117     my ( $in,        # handle to in stream
3118          $out,       # handle to out stream
3119          $options,   # options hash
3120        ) = @_;
3121
3122     # Returns nothing.
3123
3124     my ( $record, $genome, $genome_file, $index_file, $index, $fh, $index_head, $index_beg, $index_len, $beg, $len, %lookup_hash, @begs, @lens, $i );
3125
3126     $options->{ "flank" } ||= 0;
3127
3128     if ( $options->{ "genome" } ) 
3129     {
3130         $genome      = $options->{ "genome" };
3131
3132         $genome_file = "$ENV{ 'BP_DATA' }/genomes/$genome/fasta/$genome.fna";
3133         $index_file  = "$ENV{ 'BP_DATA' }/genomes/$genome/fasta/$genome.index";
3134
3135         $fh          = Maasha::Common::read_open( $genome_file );
3136         $index       = Maasha::Fasta::index_retrieve( $index_file );
3137
3138         shift @{ $index }; # Get rid of the file size info
3139
3140         map { $lookup_hash{ $_->[ 0 ] } = [ $_->[ 1 ], $_->[ 2 ] ] } @{ $index };
3141
3142         if ( exists $lookup_hash{ $options->{ "chr" } } and defined $options->{ "beg" } and ( defined $options->{ "end" } or defined $options->{ "len" } ) )
3143         {
3144             ( $index_beg, $index_len ) = @{ $lookup_hash{ $options->{ "chr" } } };
3145
3146             $beg = $index_beg + $options->{ "beg" } - 1;
3147
3148             if ( $options->{ "len" } ) {
3149                 $len = $options->{ "len" };
3150             } elsif ( $options->{ "end" } ) {
3151                 $len = ( $options->{ "end" } - $options->{ "beg" } + 1 );
3152             }   
3153             
3154             $beg -= $options->{ "flank" };
3155             $len += 2 * $options->{ "flank" };
3156
3157             if ( $beg <= $index_beg )
3158             {
3159                 $len -= $index_beg - $beg;
3160                 $beg = $index_beg;
3161             }
3162
3163             $len = $index_beg + $index_len - $beg if $beg + $len > $index_beg + $index_len;
3164
3165             next if $beg > $index_beg + $index_len;
3166
3167             $record->{ "CHR" }     = $options->{ "chr" };
3168             $record->{ "CHR_BEG" } = $beg - $index_beg;
3169             $record->{ "CHR_END" } = $record->{ "CHR_BEG" } + $len - 1;
3170             
3171             $record->{ "SEQ" }     = Maasha::Common::file_read( $fh, $beg, $len );
3172             $record->{ "SEQ_LEN" } = $len;
3173
3174             put_record( $record, $out );
3175         }   
3176     }
3177
3178     while ( $record = get_record( $in ) ) 
3179     {
3180         if ( $options->{ "genome" } and not $record->{ "SEQ" } )
3181         {
3182             if ( $record->{ "REC_TYPE" } eq "BED" and exists $lookup_hash{ $record->{ "CHR" } } )
3183             {
3184                 ( $index_beg, $index_len ) = @{ $lookup_hash{ $record->{ "CHR" } } };
3185             
3186                 $beg = $record->{ "CHR_BEG" } + $index_beg;
3187                 $len = $record->{ "CHR_END" } - $record->{ "CHR_BEG" } + 1;
3188             }
3189             elsif ( $record->{ "REC_TYPE" } eq "PSL" and exists $lookup_hash{ $record->{ "S_ID" } } )
3190             {
3191                 ( $index_beg, $index_len ) = @{ $lookup_hash{ $record->{ "S_ID" } } };
3192             
3193                 $beg = $record->{ "S_BEG" } + $index_beg;
3194                 $len = $record->{ "S_END" } - $record->{ "S_BEG" } + 1;
3195             }
3196             elsif ( $record->{ "REC_TYPE" } eq "BLAST" and exists $lookup_hash{ $record->{ "S_ID" } } )
3197             {
3198                 ( $index_beg, $index_len ) = @{ $lookup_hash{ $record->{ "S_ID" } } };
3199             
3200                 $beg = $record->{ "S_BEG" } + $index_beg;
3201                 $len = $record->{ "S_END" } - $record->{ "S_BEG" } + 1;
3202             }
3203
3204             $beg -= $options->{ "flank" };
3205             $len += 2 * $options->{ "flank" };
3206
3207             if ( $beg <= $index_beg )
3208             {
3209                 $len -= $index_beg - $beg;
3210                 $beg = $index_beg;
3211             }
3212
3213             $len = $index_beg + $index_len - $beg if $beg + $len > $index_beg + $index_len;
3214
3215             next if $beg > $index_beg + $index_len;
3216
3217             $record->{ "CHR_BEG" } = $beg - $index_beg;
3218             $record->{ "CHR_END" } = $record->{ "CHR_BEG" } + $len - 1;
3219
3220             $record->{ "SEQ" } = Maasha::Common::file_read( $fh, $beg, $len );
3221
3222             if ( $record->{ "STRAND" } and $record->{ "STRAND" } eq "-" )
3223             {
3224                 Maasha::Seq::dna_comp( \$record->{ "SEQ" } );
3225                 $record->{ "SEQ" } = reverse $record->{ "SEQ" };
3226             }
3227
3228             if ( $options->{ "mask" } )
3229             {
3230                 if ( $record->{ "BLOCKCOUNT" } > 1 ) # uppercase hit block segments and lowercase the rest.
3231                 {
3232                     $record->{ "SEQ" } = lc $record->{ "SEQ" };
3233                 
3234                     @begs = split ",", $record->{ "Q_BEGS" };
3235                     @lens = split ",", $record->{ "BLOCKSIZES" };
3236
3237                     for ( $i = 0; $i < @begs; $i++ ) {
3238                         substr $record->{ "SEQ" }, $begs[ $i ], $lens[ $i ], uc substr $record->{ "SEQ" }, $begs[ $i ], $lens[ $i ];
3239                     }
3240                 }
3241             }
3242         }
3243
3244         put_record( $record, $out );
3245     }
3246
3247     close $fh if $fh;                                                                                                                                          
3248 }
3249
3250
3251 sub script_get_genome_align
3252 {
3253     # Martin A. Hansen, April 2008.
3254
3255     # Gets a subalignment from a multiple genome alignment.
3256
3257     my ( $in,        # handle to in stream
3258          $out,       # handle to out stream
3259          $options,   # options hash
3260        ) = @_;
3261
3262     # Returns nothing.
3263
3264     my ( $record, $maf_track, $align, $align_num, $beg, $end, $len, $entry );
3265
3266     $options->{ "strand" } ||= "+";
3267
3268     $align_num = 1;
3269
3270     $maf_track = Maasha::Config::maf_track( $options->{ "genome" } );
3271
3272     if ( $options->{ "chr" } and $options->{ "beg" } and ( $options->{ "end" } or $options->{ "len" } ) )
3273     {
3274         $beg = $options->{ "beg" } - 1;
3275         
3276         if ( $options->{ "end" } ) {
3277             $end = $options->{ "end" };
3278         } elsif ( $options->{ "len" } ) {
3279             $end = $beg + $options->{ "len" };
3280         }
3281
3282         $align = Maasha::UCSC::maf_extract( $BP_TMP, $options->{ "genome" }, $maf_track, $options->{ "chr" }, $beg, $end, $options->{ "strand" } );
3283
3284         foreach $entry ( @{ $align } )
3285         {
3286             $entry->{ "CHR" }     = $record->{ "CHR" };
3287             $entry->{ "CHR_BEG" } = $record->{ "CHR_BEG" };
3288             $entry->{ "CHR_END" } = $record->{ "CHR_END" };
3289             $entry->{ "STRAND" }  = $record->{ "STRAND" } || '+';
3290             $entry->{ "Q_ID" }    = $record->{ "Q_ID" };
3291             $entry->{ "SCORE" }   = $record->{ "SCORE" };
3292
3293             put_record( $entry, $out );
3294         }
3295     }
3296
3297     while ( $record = get_record( $in ) ) 
3298     {
3299         if ( $record->{ "REC_TYPE" } eq "BED" )
3300         {
3301             $align = Maasha::UCSC::maf_extract( $BP_TMP, $options->{ "genome" }, $maf_track, $record->{ "CHR" }, $record->{ "CHR_BEG" }, $record->{ "CHR_END" }, $record->{ "STRAND" } );
3302         }
3303         elsif ( $record->{ "REC_TYPE" } eq "PSL" )
3304         {
3305             $align = Maasha::UCSC::maf_extract( $BP_TMP, $options->{ "genome" }, $maf_track, $record->{ "S_ID" }, $record->{ "S_BEG" }, $record->{ "S_END" }, $record->{ "STRAND" } );
3306         }
3307         elsif ( $record->{ "REC_TYPE" } eq "BLAST" )
3308         {
3309             $align = Maasha::UCSC::maf_extract( $BP_TMP, $options->{ "genome" }, $maf_track, $record->{ "S_ID" }, $record->{ "S_BEG" }, $record->{ "S_END" }, $record->{ "STRAND" } );
3310         }
3311
3312         foreach $entry ( @{ $align } )
3313         {
3314             $entry->{ "CHR" }     = $record->{ "CHR" };
3315             $entry->{ "CHR_BEG" } = $record->{ "CHR_BEG" };
3316             $entry->{ "CHR_END" } = $record->{ "CHR_END" };
3317             $entry->{ "STRAND" }  = $record->{ "STRAND" };
3318             $entry->{ "Q_ID" }    = $record->{ "Q_ID" };
3319             $entry->{ "SCORE" }   = $record->{ "SCORE" };
3320
3321             put_record( $entry, $out );
3322         }
3323
3324         $align_num++;
3325     }
3326 }
3327
3328
3329 sub script_get_genome_phastcons
3330 {
3331     # Martin A. Hansen, February 2008.
3332
3333     # Get phastcons scores from genome intervals.
3334
3335     my ( $in,        # handle to in stream
3336          $out,       # handle to out stream
3337          $options,   # options hash
3338        ) = @_;
3339
3340     # Returns nothing.
3341
3342     my ( $phastcons_file, $phastcons_index, $index, $fh_phastcons, $scores, $record );
3343
3344     $options->{ "flank" } ||= 0;
3345
3346     $phastcons_file  = Maasha::Config::genome_phastcons( $options->{ "genome" } );
3347     $phastcons_index = Maasha::Config::genome_phastcons_index( $options->{ "genome" } );
3348
3349     $index           = Maasha::UCSC::fixedstep_index_retrieve( $phastcons_index );
3350     $fh_phastcons    = Maasha::Common::read_open( $phastcons_file );
3351
3352     if ( defined $options->{ "chr" } and defined $options->{ "beg" } and ( defined $options->{ "end" } or defined $options->{ "len" } ) )
3353     {
3354         $options->{ "beg" } -= 1;   # request is 1-based
3355         $options->{ "end" } -= 1;   # request is 1-based
3356
3357         if ( $options->{ "len" } ) {
3358             $options->{ "end" } = $options->{ "beg" } + $options->{ "len" } - 1;
3359         }
3360
3361         $scores = Maasha::UCSC::fixedstep_index_lookup( $index, $fh_phastcons, $options->{ "chr" }, $options->{ "beg" }, $options->{ "end" }, $options->{ "flank" } );
3362
3363         $record->{ "CHR" }       = $options->{ "chr" };
3364         $record->{ "CHR_BEG" }   = $options->{ "beg" } - $options->{ "flank" };
3365         $record->{ "CHR_END" }   = $options->{ "end" } + $options->{ "flank" };
3366         
3367         $record->{ "PHASTCONS" }   = join ",", @{ $scores };
3368         $record->{ "PHAST_COUNT" } = scalar @{ $scores };  # DEBUG
3369
3370         put_record( $record, $out );
3371     }   
3372
3373     while ( $record = get_record( $in ) ) 
3374     {
3375         if ( $record->{ "REC_TYPE" } eq "BED" )
3376         {
3377             $scores = Maasha::UCSC::fixedstep_index_lookup( $index, $fh_phastcons, $record->{ "CHR" }, $record->{ "CHR_BEG" }, $record->{ "CHR_END" }, $options->{ "flank" } );
3378         }
3379         elsif ( $record->{ "REC_TYPE" } eq "PSL" )
3380         {
3381             $scores = Maasha::UCSC::fixedstep_index_lookup( $index, $fh_phastcons, $record->{ "S_ID" }, $record->{ "S_BEG" }, $record->{ "S_END" }, $options->{ "flank" } );
3382         }
3383         elsif ( $record->{ "REC_TYPE" } eq "BLAST" )
3384         {
3385             $scores = Maasha::UCSC::fixedstep_index_lookup( $index, $fh_phastcons, $record->{ "S_ID" }, $record->{ "S_BEG" }, $record->{ "S_END" }, $options->{ "flank" } );
3386         }
3387
3388         $record->{ "PHASTCONS" } = join ",", @{ $scores } if @{ $scores };
3389 #        $record->{ "PHAST_COUNT" } = @{ $scores } if @{ $scores };  # DEBUG
3390
3391         put_record( $record, $out );
3392     }
3393
3394     close $fh_phastcons if $fh_phastcons;                                                                                                                                          
3395 }
3396
3397
3398 sub script_fold_seq
3399 {
3400     # Martin A. Hansen, December 2007.
3401
3402     # Folds sequences in stream into secondary structures.
3403
3404     my ( $in,     # handle to in stream
3405          $out,    # handle to out stream
3406        ) = @_;
3407
3408     # Returns nothing.
3409
3410     my ( $record, $type, $struct, $index );
3411
3412     while ( $record = get_record( $in ) ) 
3413     {
3414         if ( $record->{ "SEQ" } )
3415         {
3416             if ( not $type ) {
3417                 $type = Maasha::Seq::seq_guess_type( $record->{ "SEQ" } );
3418             }
3419             
3420             if ( $type ne "protein" )
3421             {
3422                 ( $struct, $index ) = Maasha::Seq::fold_struct_rnafold( $record->{ "SEQ" } );
3423                 $record->{ "SEC_STRUCT" }  = $struct;
3424                 $record->{ "FREE_ENERGY" } = $index;
3425                 $record->{ "SCORE" }       = abs int $index;
3426                 $record->{ "SIZE" }        = length $struct;
3427                 $record->{ "CONF" }        = "1," x $record->{ "SIZE" };
3428             }
3429         }
3430
3431         put_record( $record, $out );
3432     }
3433 }
3434
3435
3436 sub script_split_seq
3437 {
3438     # Martin A. Hansen, August 2007.
3439
3440     # Split a sequence in stream into words.
3441
3442     my ( $in,        # handle to in stream
3443          $out,       # handle to out stream
3444          $options,   # options hash
3445        ) = @_;
3446
3447     # Returns nothing.
3448
3449     my ( $record, $new_record, $i, $subseq, %lookup );
3450
3451     $options->{ "word_size" } ||= 7;
3452
3453     while ( $record = get_record( $in ) ) 
3454     {
3455         if ( $record->{ "SEQ_NAME" } and $record->{ "SEQ" } )
3456         {
3457             for ( $i = 0; $i < length( $record->{ "SEQ" } ) - $options->{ "word_size" } + 1; $i++ )
3458             {
3459                 $subseq = substr $record->{ "SEQ" }, $i, $options->{ "word_size" };
3460
3461                 if ( $options->{ "uniq" } and not $lookup{ $subseq } )
3462                 {
3463                     $new_record->{ "SEQ_NAME" } = $record->{ "SEQ_NAME" } . "[" . ( $i + 1 ) . "-" . ( $i + $options->{ "word_size" } ) . "]";
3464                     $new_record->{ "SEQ" }      = $subseq;
3465
3466                     put_record( $new_record, $out );
3467
3468                     $lookup{ $subseq } = 1;
3469                 }
3470                 else
3471                 {
3472                     $new_record->{ "SEQ_NAME" } = $record->{ "SEQ_NAME" } . "[" . ( $i + 1 ) . "-" . ( $i + $options->{ "word_size" } ) . "]";
3473                     $new_record->{ "SEQ" }      = $subseq;
3474
3475                     put_record( $new_record, $out );
3476                 }
3477             }
3478         }
3479         else
3480         {
3481             put_record( $record, $out );
3482         }
3483     }
3484 }
3485
3486
3487 sub script_split_bed
3488 {
3489     # Martin A. Hansen, June 2008.
3490
3491     # Split a BED record into overlapping windows.
3492
3493     my ( $in,        # handle to in stream
3494          $out,       # handle to out stream
3495          $options,   # options hash
3496        ) = @_;
3497
3498     # Returns nothing.
3499
3500     my ( $record, $new_record, $i );
3501
3502     $options->{ "window_size" } ||= 20;
3503     $options->{ "step_size" }   ||= 1;
3504
3505     while ( $record = get_record( $in ) ) 
3506     {
3507         if ( $record->{ "CHR" } and $record->{ "CHR_BEG" } and $record->{ "CHR_END" } )
3508         {
3509             $record->{ "BED_LEN" } = $record->{ "CHR_END" } - $record->{ "CHR_BEG" } + 1;
3510
3511             for ( $i = 0; $i < $record->{ "BED_LEN" } - $options->{ "window_size" }; $i += $options->{ "step_size" } )
3512             {
3513                 $new_record->{ "REC_TYPE" } = "BED";
3514                 $new_record->{ "CHR" }      = $record->{ "CHR" };
3515                 $new_record->{ "CHR_BEG" }  = $record->{ "CHR_BEG" } + $i;
3516                 $new_record->{ "CHR_END" }  = $record->{ "CHR_BEG" } + $i + $options->{ "window_size" };
3517                 $new_record->{ "BED_LEN" }  = $options->{ "window_size" };
3518                 $new_record->{ "Q_ID" }     = $record->{ "Q_ID" } . "_$i";
3519                 $new_record->{ "SCORE" }    = $record->{ "SCORE" };
3520                 $new_record->{ "STRAND" }   = $record->{ "STRAND" };
3521
3522                 put_record( $new_record, $out );
3523             }
3524         }
3525         else
3526         {
3527             put_record( $record, $out );
3528         }
3529     }
3530 }
3531
3532
3533 sub script_align_seq
3534 {
3535     # Martin A. Hansen, August 2007.
3536
3537     # Align sequences in stream.
3538
3539     my ( $in,    # handle to in stream
3540          $out,   # handle to out stream
3541        ) = @_;
3542
3543     # Returns nothing.
3544
3545     my ( $record, @entries, $entry );
3546
3547     while ( $record = get_record( $in ) ) 
3548     {
3549         if ( $record->{ "SEQ_NAME" } and $record->{ "SEQ" } ) {
3550             push @entries, [ $record->{ "SEQ_NAME" }, $record->{ "SEQ" } ];
3551         } elsif ( $record->{ "Q_ID" } and $record->{ "SEQ" } ) {
3552             push @entries, [ $record->{ "Q_ID" }, $record->{ "SEQ" } ];
3553         } else {
3554             put_record( $record, $out );
3555         }
3556     }
3557
3558     @entries = Maasha::Align::align( \@entries );
3559
3560     foreach $entry ( @entries )
3561     {
3562         if ( $entry->[ SEQ_NAME ] and $entry->[ SEQ ] )
3563         {
3564             $record = {
3565                 SEQ_NAME => $entry->[ SEQ_NAME ],
3566                 SEQ      => $entry->[ SEQ ],
3567             };
3568
3569             put_record( $record, $out );
3570         }
3571     }
3572 }
3573
3574
3575 sub script_tile_seq
3576 {
3577     # Martin A. Hansen, February 2008.
3578
3579     # Using the first sequence in stream as reference, tile
3580     # all subsequent sequences based on pairwise alignments.
3581
3582     my ( $in,        # handle to in stream
3583          $out,       # handle to out stream
3584          $options,   # options hash
3585        ) = @_;
3586
3587     # Returns nothing.
3588
3589     my ( $record, $first, $ref_entry, @entries );
3590
3591     $first = 1;
3592
3593     while ( $record = get_record( $in ) ) 
3594     {
3595         if ( $record->{ "SEQ_NAME" } and $record->{ "SEQ" } )
3596         {
3597             if ( $first )
3598             {
3599                 $ref_entry = [ $record->{ "SEQ_NAME" }, $record->{ "SEQ" } ];
3600
3601                 $first = 0;
3602             }
3603             else
3604             {
3605                 push @entries, [ $record->{ "SEQ_NAME" }, $record->{ "SEQ" } ];
3606             }
3607         }
3608         else
3609         {
3610             put_record( $record, $out );
3611         }
3612     }
3613
3614     @entries = Maasha::Align::align_tile( $ref_entry, \@entries, $options );
3615
3616     map { put_record( { SEQ_NAME => $_->[ SEQ_NAME ], SEQ => $_->[ SEQ ] }, $out ) } @entries;
3617 }
3618
3619
3620 sub script_invert_align
3621 {
3622     # Martin A. Hansen, February 2008.
3623
3624     # Inverts an alignment showing only non-mathing residues
3625     # using the first sequence as reference.
3626
3627     my ( $in,        # handle to in stream
3628          $out,       # handle to out stream
3629          $options,   # options hash
3630        ) = @_;
3631
3632     # Returns nothing.
3633
3634     my ( $record, @entries );
3635
3636     while ( $record = get_record( $in ) ) 
3637     {
3638         if ( $record->{ "SEQ_NAME" } and $record->{ "SEQ" } )
3639         {
3640             push @entries, [ $record->{ "SEQ_NAME" }, $record->{ "SEQ" } ];
3641         }
3642         else
3643         {
3644             put_record( $record, $out );
3645         }
3646     }
3647
3648     Maasha::Align::align_invert( \@entries, $options->{ "soft" } );
3649
3650     map { put_record( { SEQ_NAME => $_->[ SEQ_NAME ], SEQ => $_->[ SEQ ] }, $out ) } @entries;
3651 }
3652
3653
3654 sub script_patscan_seq
3655 {
3656     # Martin A. Hansen, August 2007.
3657
3658     # Locates patterns in sequences using scan_for_matches.
3659
3660     my ( $in,        # handle to in stream
3661          $out,       # handle to out stream
3662          $options,   # options hash
3663        ) = @_;
3664
3665     # Returns nothing.
3666
3667     my ( $genome_file, @args, $arg, $type, $seq_file, $pat_file, $out_file, $fh_in, $fh_out, $record, $patterns, $pattern, $entry, $result, %head_hash, $i );
3668
3669     if ( $options->{ "patterns" } ) {
3670         $patterns = Maasha::Patscan::parse_patterns( $options->{ "patterns" } );
3671     } elsif ( -f $options->{ "patterns_in" } ) {
3672         $patterns = Maasha::Patscan::read_patterns( $options->{ "patterns_in" } );
3673     }
3674
3675     $genome_file = "$ENV{ 'BP_DATA' }/genomes/$options->{ 'genome' }/fasta/$options->{ 'genome' }.fna" if $options->{ 'genome' };
3676
3677     push @args, "-c"                            if $options->{ "comp" };
3678     push @args, "-m $options->{ 'max_hits' }"   if $options->{ 'max_hits' };
3679     push @args, "-n $options->{ 'max_misses' }" if $options->{ 'max_hits' };
3680
3681     $seq_file = "$BP_TMP/patscan.seq";
3682     $pat_file = "$BP_TMP/patscan.pat";
3683     $out_file = "$BP_TMP/patscan.out";
3684
3685     $fh_out = Maasha::Common::write_open( $seq_file );
3686
3687     $i = 0;
3688
3689     while ( $record = get_record( $in ) ) 
3690     {
3691         if ( $record->{ "SEQ" } and $record->{ "SEQ_NAME" } )
3692         {
3693             $type = Maasha::Seq::seq_guess_type( $record->{ "SEQ" } ) if not $type;
3694
3695             Maasha::Fasta::put_entry( [ $i, $record->{ "SEQ" } ], $fh_out );
3696
3697             $head_hash{ $i } = $record->{ "SEQ_NAME" };
3698
3699             $i++;
3700         }
3701     }
3702
3703     close $fh_out;
3704
3705     $arg  = join " ", @args;
3706     $arg .= " -p" if $type eq "protein";
3707
3708     foreach $pattern ( @{ $patterns } )
3709     {
3710         $fh_out = Maasha::Common::write_open( $pat_file );
3711
3712         print $fh_out "$pattern\n";
3713
3714         close $fh_out;
3715
3716         if ( $options->{ 'genome' } ) {
3717             `scan_for_matches $arg $pat_file < $genome_file > $out_file`;
3718             # Maasha::Common::run( "scan_for_matches", "$arg $pat_file < $genome_file > $out_file" );
3719         } else {
3720             `scan_for_matches $arg $pat_file < $seq_file > $out_file`;
3721             # Maasha::Common::run( "scan_for_matches", "$arg $pat_file < $seq_file > $out_file" );
3722         }
3723
3724         $fh_in = Maasha::Common::read_open( $out_file );
3725
3726         while ( $entry = Maasha::Fasta::get_entry( $fh_in ) )
3727         {
3728             $result = Maasha::Patscan::parse_scan_result( $entry, $pattern );
3729
3730             if ( $options->{ 'genome' } )
3731             {
3732                 $result->{ "CHR" }     = $result->{ "S_ID" };
3733                 $result->{ "CHR_BEG" } = $result->{ "S_BEG" }; 
3734                 $result->{ "CHR_END" } = $result->{ "S_END" }; 
3735
3736                 delete $result->{ "S_ID" };
3737                 delete $result->{ "S_BEG" };
3738                 delete $result->{ "S_END" };
3739             }
3740             else
3741             {
3742                 $result->{ "S_ID" } = $head_hash{ $result->{ "S_ID" } };
3743             }
3744
3745             put_record( $result, $out );
3746         }
3747
3748         close $fh_in;
3749     }
3750
3751     unlink $pat_file;
3752     unlink $seq_file;
3753     unlink $out_file;
3754 }
3755
3756
3757 sub script_create_blast_db
3758 {
3759     # Martin A. Hansen, September 2007.
3760
3761     # Creates a NCBI BLAST database with formatdb
3762
3763     my ( $in,        # handle to in stream
3764          $out,       # handle to out stream
3765          $options,   # options hash
3766        ) = @_;
3767
3768     # Returns nothing.
3769
3770     my ( $fh, $seq_type, $path, $record, $entry );
3771
3772     $path = $options->{ "database" };
3773
3774     $fh = Maasha::Common::write_open( $path );
3775
3776     while ( $record = get_record( $in ) ) 
3777     {
3778         put_record( $record, $out ) if not $options->{ "no_stream" };
3779
3780         if ( $entry = record2fasta( $record ) )
3781         {
3782             $seq_type = Maasha::Seq::seq_guess_type( $entry->[ SEQ ] ) if not $seq_type;
3783
3784             Maasha::Fasta::put_entry( $entry, $fh );
3785         }
3786     }
3787
3788     close $fh;
3789
3790     if ( $seq_type eq "protein" ) {
3791         Maasha::Common::run( "formatdb", "-p T -i $path -t $options->{ 'database' }" );
3792     } else {
3793         Maasha::Common::run( "formatdb", "-p F -i $path -t $options->{ 'database' }" );
3794     }
3795
3796     unlink $path;
3797 }
3798
3799
3800 sub script_blast_seq
3801 {
3802     # Martin A. Hansen, September 2007.
3803
3804     # BLASTs sequences in stream against a given database.
3805
3806     my ( $in,        # handle to in stream
3807          $out,       # handle to out stream
3808          $options,   # options hash
3809        ) = @_;
3810
3811     # Returns nothing.
3812
3813     my ( $genome, $q_type, $s_type, $tmp_in, $tmp_out, $fh_in, $fh_out, $record, $line, @fields, $entry );
3814
3815     $options->{ "e_val" }  = 10 if not defined $options->{ "e_val" };
3816     $options->{ "filter" } = "F";
3817     $options->{ "filter" } = "T" if $options->{ "filter" };
3818     $options->{ "cpus" } ||= 1;
3819
3820     $options->{ "database" } = "$ENV{ 'BP_DATA' }/genomes/$options->{ 'genome' }/blast/$options->{ 'genome' }.fna" if $options->{ 'genome' };
3821
3822     $tmp_in  = "$BP_TMP/blast_query.seq";
3823     $tmp_out = "$BP_TMP/blast.result";
3824
3825     $fh_out = Maasha::Common::write_open( $tmp_in );
3826
3827     while ( $record = get_record( $in ) ) 
3828     {
3829         if ( $entry = record2fasta( $record ) )
3830         {
3831             $q_type = Maasha::Seq::seq_guess_type( $entry->[ SEQ ] ) if not $q_type;
3832
3833             Maasha::Fasta::put_entry( $entry, $fh_out );
3834         }
3835
3836         put_record( $record, $out );
3837     }
3838
3839     close $fh_out;
3840
3841     if ( -f $options->{ 'database' } . ".phr" ) {
3842         $s_type = "protein";
3843     } else {
3844         $s_type = "nucleotide";
3845     }
3846
3847     if ( not $options->{ 'program' } )
3848     {
3849         if ( $q_type ne "protein" and $s_type ne "protein" ) {
3850             $options->{ 'program' } = "blastn";
3851         } elsif ( $q_type eq "protein" and $s_type eq "protein" ) {
3852             $options->{ 'program' } = "blastp";
3853         } elsif ( $q_type ne "protein" and $s_type eq "protein" ) {
3854             $options->{ 'program' } = "blastx";
3855         } elsif ( $q_type eq "protein" and $s_type ne "protein" ) {
3856             $options->{ 'program' } = "tblastn";
3857         }
3858     }
3859
3860     if ( $options->{ 'verbose' } )
3861     {
3862         Maasha::Common::run(
3863             "blastall",
3864             join( " ",
3865                 "-p $options->{ 'program' }",
3866                 "-e $options->{ 'e_val' }",
3867                 "-a $options->{ 'cpus' }",
3868                 "-m 8",
3869                 "-i $tmp_in",
3870                 "-d $options->{ 'database' }",
3871                 "-F $options->{ 'filter' }",
3872                 "-o $tmp_out",
3873             ),
3874             1
3875         );
3876     }
3877     else
3878     {
3879         Maasha::Common::run(
3880             "blastall",
3881             join( " ",
3882                 "-p $options->{ 'program' }",
3883                 "-e $options->{ 'e_val' }",
3884                 "-a $options->{ 'cpus' }",
3885                 "-m 8",
3886                 "-i $tmp_in",
3887                 "-d $options->{ 'database' }",
3888                 "-F $options->{ 'filter' }",
3889                 "-o $tmp_out",
3890                 "> /dev/null 2>&1"
3891             ),
3892             1
3893         );
3894     }
3895
3896     unlink $tmp_in;
3897
3898     $fh_out = Maasha::Common::read_open( $tmp_out );
3899
3900     undef $record;
3901
3902     while ( $line = <$fh_out> )
3903     {
3904         chomp $line;
3905
3906         next if $line =~ /^#/;
3907
3908         @fields = split /\s+/, $line;
3909
3910         $record->{ "REC_TYPE" }   = "BLAST";
3911         $record->{ "Q_ID" }       = $fields[ 0 ];
3912         $record->{ "S_ID" }       = $fields[ 1 ];
3913         $record->{ "IDENT" }      = $fields[ 2 ];
3914         $record->{ "ALIGN_LEN" }  = $fields[ 3 ];
3915         $record->{ "MISMATCHES" } = $fields[ 4 ];
3916         $record->{ "GAPS" }       = $fields[ 5 ];
3917         $record->{ "Q_BEG" }      = $fields[ 6 ] - 1; # BLAST is 1-based
3918         $record->{ "Q_END" }      = $fields[ 7 ] - 1; # BLAST is 1-based
3919         $record->{ "S_BEG" }      = $fields[ 8 ] - 1; # BLAST is 1-based
3920         $record->{ "S_END" }      = $fields[ 9 ] - 1; # BLAST is 1-based
3921         $record->{ "E_VAL" }      = $fields[ 10 ];
3922         $record->{ "BIT_SCORE" }  = $fields[ 11 ];
3923
3924         if ( $record->{ "S_BEG" } > $record->{ "S_END" } )
3925         {
3926             $record->{ "STRAND" } = '-';
3927
3928             ( $record->{ "S_BEG" }, $record->{ "S_END" } ) = ( $record->{ "S_END" }, $record->{ "S_BEG" } );
3929         }
3930         else
3931         {
3932             $record->{ "STRAND" } = '+';
3933         }
3934
3935         put_record( $record, $out );
3936     }
3937
3938     close $fh_out;
3939
3940     unlink $tmp_out;
3941 }
3942
3943
3944 sub script_blat_seq
3945 {
3946     # Martin A. Hansen, August 2007.
3947
3948     # BLATs sequences in stream against a given genome.
3949
3950     my ( $in,        # handle to in stream
3951          $out,       # handle to out stream
3952          $options,   # options hash
3953        ) = @_;
3954
3955     # Returns nothing.
3956
3957     my ( $blat_args, $genome_file, $query_file, $fh_in, $fh_out, $type, $record, $result_file, $entries, $entry );
3958
3959     $genome_file = "$ENV{ 'BP_DATA' }/genomes/$options->{ 'genome' }/fasta/$options->{ 'genome' }.fna";
3960
3961     $options->{ 'tile_size' }    ||= 11;
3962     $options->{ 'one_off' }      ||= 0;
3963     $options->{ 'min_identity' } ||= 90;
3964     $options->{ 'min_score' }    ||= 0;
3965     $options->{ 'step_size' }    ||= $options->{ 'tile_size' };
3966
3967     $blat_args .= " -tileSize=$options->{ 'tile_size' }";
3968     $blat_args .= " -oneOff=$options->{ 'one_off' }";
3969     $blat_args .= " -minIdentity=$options->{ 'min_identity' }";
3970     $blat_args .= " -minScore=$options->{ 'min_score' }";
3971     $blat_args .= " -stepSize=$options->{ 'step_size' }";
3972 #    $blat_args .= " -ooc=" . Maasha::Config::genome_blat_ooc( $options->{ "genome" }, 11 ) if $options->{ 'ooc' };
3973
3974     $query_file = "$BP_TMP/blat.seq";
3975
3976     $fh_out = Maasha::Common::write_open( $query_file );
3977
3978     while ( $record = get_record( $in ) ) 
3979     {
3980         if ( $entry = record2fasta( $record ) )
3981         {
3982             $type = Maasha::Seq::seq_guess_type( $entry->[ SEQ ] ) if not $type;
3983             Maasha::Fasta::put_entry( $entry, $fh_out, 80 );
3984         }
3985
3986         put_record( $record, $out );
3987     }
3988
3989     close $fh_out;
3990
3991     $blat_args .= " -t=dnax" if $type eq "protein";
3992     $blat_args .= " -q=$type";
3993
3994     $result_file = "$BP_TMP/blat.psl";
3995
3996     Maasha::Common::run( "blat", "$genome_file $query_file $blat_args $result_file > /dev/null 2>&1" );
3997
3998     unlink $query_file;
3999
4000     $entries = Maasha::UCSC::psl_get_entries( $result_file );
4001
4002     map { put_record( $_, $out ) } @{ $entries };
4003
4004     unlink $result_file;
4005 }
4006
4007
4008 sub script_soap_seq
4009 {
4010     # Martin A. Hansen, July 2008.
4011
4012     # soap sequences in stream against a given file or genome.
4013
4014     my ( $in,        # handle to in stream
4015          $out,       # handle to out stream
4016          $options,   # options hash
4017        ) = @_;
4018
4019     # Returns nothing.
4020
4021     my ( $genome, $tmp_in, $tmp_out, $fh_in, $fh_out, $record, $line, @fields, $entry, $count, $args );
4022
4023     $options->{ "seed_size" }  ||= 10;
4024     $options->{ "mismatches" } ||= 2;
4025     $options->{ "gap_size" }   ||= 0;
4026     $options->{ "cpus" }       ||= 1;
4027
4028     if ( $options->{ "genome" } ) {
4029         $options->{ "in_file" } = "$ENV{ 'BP_DATA' }/genomes/$options->{ 'genome' }/fasta/$options->{ 'genome' }.fna";
4030     }
4031
4032     $tmp_in  = "$BP_TMP/soap_query.seq";
4033     $tmp_out = "$BP_TMP/soap.result";
4034
4035     $fh_out = Maasha::Common::write_open( $tmp_in );
4036  
4037     $count = 0;
4038
4039     while ( $record = get_record( $in ) ) 
4040     {
4041         if ( $entry = record2fasta( $record ) )
4042         {
4043             Maasha::Fasta::put_entry( $entry, $fh_out );
4044
4045             $count++;
4046         }
4047
4048         put_record( $record, $out );
4049     }
4050
4051     close $fh_out;
4052
4053     if ( $count > 0 )
4054     {
4055         $args = join( " ",
4056             "-s $options->{ 'seed_size' }",
4057             "-r 2",
4058             "-a $tmp_in",
4059             "-v $options->{ 'mismatches' }",
4060             "-g $options->{ 'gap_size' }",
4061             "-p $options->{ 'cpus' }",
4062             "-d $options->{ 'in_file' }",
4063             "-o $tmp_out",
4064         );
4065
4066         $args .= " > /dev/null 2>&1" if not $options->{ 'verbose' };
4067
4068         Maasha::Common::run( "soap", $args, 1 );
4069
4070         unlink $tmp_in;
4071
4072         $fh_out = Maasha::Common::read_open( $tmp_out );
4073
4074         undef $record;
4075
4076         while ( $line = <$fh_out> )
4077         {
4078             chomp $line;
4079
4080             @fields = split /\t/, $line;
4081
4082             $record->{ "REC_TYPE" }   = "SOAP";
4083             $record->{ "Q_ID" }       = $fields[ 0 ];
4084             $record->{ "SCORE" }      = $fields[ 3 ];
4085             $record->{ "STRAND" }     = $fields[ 6 ];
4086             $record->{ "S_ID" }       = $fields[ 7 ];
4087             $record->{ "S_BEG" }      = $fields[ 8 ] - 1; # soap is 1-based
4088             $record->{ "S_END" }      = $fields[ 8 ] + $fields[ 5 ] - 2;
4089
4090             put_record( $record, $out );
4091         }
4092
4093         close $fh_out;
4094     }
4095
4096     unlink $tmp_out;
4097 }
4098
4099
4100 sub script_match_seq
4101 {
4102     # Martin A. Hansen, August 2007.
4103
4104     # BLATs sequences in stream against a given genome.
4105
4106     my ( $in,        # handle to in stream
4107          $out,       # handle to out stream
4108          $options,   # options hash
4109        ) = @_;
4110
4111     # Returns nothing.
4112
4113     my ( $record, @entries, $results );
4114
4115     $options->{ "word_size" } ||= 20;
4116     $options->{ "direction" } ||= "both";
4117
4118     while ( $record = get_record( $in ) ) 
4119     {
4120         if ( $record->{ "SEQ_NAME" } and $record->{ "SEQ" } ) {
4121             push @entries, [ $record->{ "SEQ_NAME" }, $record->{ "SEQ" } ];
4122         }
4123
4124         put_record( $record, $out );
4125     }
4126
4127     if ( @entries == 1 )
4128     {
4129         $results = Maasha::Match::match_mummer( [ $entries[ 0 ] ], [ $entries[ 0 ] ], $options, $BP_TMP );
4130
4131         map { put_record( $_, $out ) } @{ $results };
4132     }
4133     elsif ( @entries == 2 )
4134     {
4135         $results = Maasha::Match::match_mummer( [ $entries[ 0 ] ], [ $entries[ 1 ] ], $options, $BP_TMP );
4136
4137         map { put_record( $_, $out ) } @{ $results };
4138     }
4139 }
4140
4141
4142 sub script_create_vmatch_index
4143 {
4144     # Martin A. Hansen, January 2008.
4145
4146     # Create a vmatch index from sequences in the stream.
4147
4148     my ( $in,        # handle to in stream
4149          $out,       # handle to out stream
4150          $options,   # options hash
4151        ) = @_;
4152
4153     # Returns nothing.
4154
4155     my ( $record, $file_tmp, $fh_tmp, $type, $entry );
4156
4157     if ( $options->{ "index_name" } )
4158     {
4159         $file_tmp = $options->{ 'index_name' };
4160         $fh_tmp   = Maasha::Common::write_open( $file_tmp );
4161     }
4162
4163     while ( $record = get_record( $in ) ) 
4164     {
4165         if ( $options->{ "index_name" } and $entry = record2fasta( $record ) )
4166         {
4167             Maasha::Fasta::put_entry( $entry, $fh_tmp );
4168
4169             $type = Maasha::Seq::seq_guess_type( $entry->[ SEQ ] ) if not defined $type;
4170         }
4171
4172         put_record( $record, $out ) if not $options->{ "no_stream" };
4173     }
4174
4175     if ( $options->{ "index_name" } )
4176     {
4177         close $fh_tmp;
4178     
4179         if ( $type eq "protein" ) {
4180             Maasha::Common::run( "mkvtree", "-db $file_tmp -protein -pl $options->{ 'prefix_length' } -allout -indexname $file_tmp > /dev/null 2>&1" );
4181         } else {
4182             Maasha::Common::run( "mkvtree", "-db $file_tmp -dna -pl $options->{ 'prefix_length' } -allout -indexname $file_tmp > /dev/null 2>&1" );
4183         }
4184
4185         unlink $file_tmp;
4186     }
4187 }
4188
4189
4190 sub script_vmatch_seq
4191 {
4192     # Martin A. Hansen, August 2007.
4193
4194     # Vmatches sequences in stream against a given genome.
4195
4196     my ( $in,        # handle to in stream
4197          $out,       # handle to out stream
4198          $options,   # options hash
4199        ) = @_;
4200
4201     # Returns nothing.
4202
4203     my ( @index_files, @records, $result_file, $fh_in, $record, %hash );
4204
4205     $options->{ 'count' } = 1 if $options->{ 'max_hits' };
4206
4207     if ( $options->{ "index_name" } )
4208     {
4209         @index_files = $options->{ "index_name" };
4210     }
4211     else
4212     {
4213         @index_files = Maasha::Common::ls_files( "$ENV{ 'BP_DATA' }/genomes/$options->{ 'genome' }/vmatch" );
4214
4215         map { $_ =~ /^(.+)\.[a-z1]{3,4}$/; $hash{ $1 } = 1 } @index_files;
4216
4217         @index_files = sort keys %hash;
4218     }
4219
4220     while ( $record = get_record( $in ) ) 
4221     {
4222         push @records, $record;
4223
4224         put_record( $record, $out );
4225     }
4226
4227     $result_file = Maasha::Match::match_vmatch( $BP_TMP, \@records, \@index_files, $options );
4228
4229     undef @records;
4230
4231     $fh_in = Maasha::Common::read_open( $result_file );
4232
4233     while ( $record = Maasha::Match::vmatch_get_entry( $fh_in ) ) {
4234         put_record( $record, $out );
4235     }
4236
4237     close $fh_in;
4238
4239     unlink $result_file;
4240 }
4241
4242
4243 sub script_write_fasta
4244 {
4245     # Martin A. Hansen, August 2007.
4246
4247     # Write FASTA entries from sequences in stream.
4248
4249     my ( $in,        # handle to in stream
4250          $out,       # handle to out stream
4251          $options,   # options hash
4252        ) = @_;
4253
4254     # Returns nothing.
4255
4256     my ( $record, $fh, $entry );
4257
4258     $fh = write_stream( $options->{ "data_out" }, $options->{ "compress" } );
4259
4260     while ( $record = get_record( $in ) ) 
4261     {
4262         if ( $entry = record2fasta( $record ) ) {
4263             Maasha::Fasta::put_entry( $entry, $fh, $options->{ "wrap" } );
4264         }
4265
4266         put_record( $record, $out ) if not $options->{ "no_stream" };
4267     }
4268
4269     close $fh;
4270 }
4271
4272
4273 sub script_write_align
4274 {
4275     # Martin A. Hansen, August 2007.
4276
4277     # Write pretty alignments aligned sequences in stream.
4278
4279     my ( $in,        # handle to in stream
4280          $out,       # handle to out stream
4281          $options,   # options hash
4282        ) = @_;
4283
4284     # Returns nothing.
4285
4286     my ( $fh, $record, @entries );
4287
4288     $fh = write_stream( $options->{ "data_out" } ) ;
4289
4290     while ( $record = get_record( $in ) ) 
4291     {
4292         if ( $record->{ "SEQ_NAME" } and $record->{ "SEQ" } ) {
4293             push @entries, [ $record->{ "SEQ_NAME" }, $record->{ "SEQ" } ];
4294         }
4295
4296         put_record( $record, $out ) if not $options->{ "no_stream" };
4297     }
4298
4299     if ( scalar( @entries ) == 2 ) {
4300         Maasha::Align::align_print_pairwise( $entries[ 0 ], $entries[ 1 ], $fh, $options->{ "wrap" } );
4301     } elsif ( scalar ( @entries ) > 2 ) {
4302         Maasha::Align::align_print_multi( \@entries, $fh, $options->{ "wrap" }, $options->{ "no_ruler" }, $options->{ "no_consensus" } );
4303     }
4304
4305     close $fh if $fh;
4306 }
4307
4308
4309 sub script_write_blast
4310 {
4311     # Martin A. Hansen, November 2007.
4312
4313     # Write data in blast table format (-m8 and 9).
4314
4315     my ( $in,        # handle to in stream
4316          $out,       # handle to out stream
4317          $options,   # options hash
4318        ) = @_;
4319
4320     # Returns nothing.
4321
4322     my ( $fh, $record, $first );
4323
4324     $fh = write_stream( $options->{ "data_out" }, $options->{ "compress" } ) ;
4325
4326     $first = 1;
4327
4328     while ( $record = get_record( $in ) ) 
4329     {
4330         if ( $record->{ "REC_TYPE" } eq "BLAST" )
4331         {
4332             if ( $options->{ "comment" } and $first )
4333             {
4334                 print "# Fields: Query id, Subject id, % identity, alignment length, mismatches, gap openings, q. start, q. end, s. start, s. end, e-value, bit score\n";
4335
4336                 $first = 0;
4337             }
4338
4339             if ( $record->{ "STRAND" } eq "-" ) {
4340                 ( $record->{ "S_BEG" }, $record->{ "S_END" } ) = ( $record->{ "S_END" }, $record->{ "S_BEG" } );
4341             }
4342
4343             print $fh join( "\t",
4344                 $record->{ "Q_ID" },
4345                 $record->{ "S_ID" },
4346                 $record->{ "IDENT" },
4347                 $record->{ "ALIGN_LEN" },
4348                 $record->{ "MISMATCHES" },
4349                 $record->{ "GAPS" },
4350                 $record->{ "Q_BEG" } + 1,
4351                 $record->{ "Q_END" } + 1,
4352                 $record->{ "S_BEG" } + 1,
4353                 $record->{ "S_END" } + 1,
4354                 $record->{ "E_VAL" },
4355                 $record->{ "BIT_SCORE" }
4356             ), "\n";
4357         }
4358
4359         put_record( $record, $out ) if not $options->{ "no_stream" };
4360     }
4361
4362     close $fh;
4363 }
4364
4365
4366 sub script_write_tab
4367 {
4368     # Martin A. Hansen, August 2007.
4369
4370     # Write data as table.
4371
4372     my ( $in,        # handle to in stream
4373          $out,       # handle to out stream
4374          $options,   # options hash
4375        ) = @_;
4376
4377     # Returns nothing.
4378
4379     my ( $fh, $record, $key, @keys, @vals, $ok, %no_keys, $A, $B );
4380
4381     $options->{ "delimit" } ||= "\t";
4382
4383     map { $no_keys{ $_ } = 1 } @{ $options->{ "no_keys" } };
4384
4385     $fh = write_stream( $options->{ "data_out" }, $options->{ "compress" } );
4386
4387     while ( $record = get_record( $in ) ) 
4388     {
4389         undef @vals;
4390         $ok = 1;
4391         
4392         if ( $options->{ "keys" } )
4393         {
4394             map { $ok = 0 if not exists $record->{ $_ } } @{ $options->{ "keys" } };
4395
4396             if ( $ok )
4397             {
4398                 foreach $key ( @{ $options->{ "keys" }  } )
4399                 {
4400                     if ( exists $record->{ $key } )
4401                     {
4402                         push @keys, $key if $options->{ "comment" };
4403                         push @vals, $record->{ $key };
4404                     }
4405                 }
4406              }
4407         }
4408         else
4409         {
4410             foreach $key ( sort { $A = $a; $B = $b; $A =~ s/^V(\d+)$/$1/; $B =~ s/^V(\d+)$/$1/; $A <=> $B } keys %{ $record } )
4411             {
4412                 next if exists $no_keys{ $key };
4413
4414                 push @keys, $key if $options->{ "comment" };
4415                 push @vals, $record->{ $key };
4416             }
4417         }
4418
4419         if ( @keys and $options->{ "comment" } )
4420         {
4421             print $fh "#", join( $options->{ "delimit" }, @keys ), "\n";
4422
4423             delete $options->{ "comment" };
4424         }
4425
4426         print $fh join( $options->{ "delimit" }, @vals ), "\n" if @vals;
4427
4428         put_record( $record, $out ) if not $options->{ "no_stream" };
4429     }
4430
4431     close $fh;
4432 }
4433
4434
4435 sub script_write_bed
4436 {
4437     # Martin A. Hansen, August 2007.
4438
4439     # Write BED format for the UCSC genome browser using records in stream.
4440
4441     my ( $in,        # handle to in stream
4442          $out,       # handle to out stream
4443          $options,   # options hash
4444        ) = @_;
4445
4446     # Returns nothing.
4447
4448     my ( $fh, $record, $new_record );
4449
4450     $fh = write_stream( $options->{ "data_out" }, $options->{ "compress" } );
4451
4452     while ( $record = get_record( $in ) ) 
4453     {
4454         if ( $record->{ "REC_TYPE" } eq "BED" )                                             # ---- Hits from BED ----
4455         {
4456             Maasha::UCSC::bed_put_entry( $record, $fh, $record->{ "BED_COLS" } );
4457         }
4458         elsif ( $record->{ "REC_TYPE" } eq "PSL" and $record->{ "S_ID" } =~ /^chr/i )       # ---- Hits from BLAT (PSL) ----
4459         {
4460             $new_record->{ "CHR" }     = $record->{ "S_ID" };
4461             $new_record->{ "CHR_BEG" } = $record->{ "S_BEG" };
4462             $new_record->{ "CHR_END" } = $record->{ "S_END" };
4463             $new_record->{ "Q_ID" }    = $record->{ "Q_ID" };
4464             $new_record->{ "SCORE" }   = $record->{ "SCORE" } || 999;
4465             $new_record->{ "STRAND" }  = $record->{ "STRAND" };
4466
4467             Maasha::UCSC::bed_put_entry( $new_record, $fh, 6 );
4468         }
4469         elsif ( $record->{ "REC_TYPE" } eq "PATSCAN" and $record->{ "CHR" } )               # ---- Hits from patscan_seq ----
4470         {
4471             Maasha::UCSC::bed_put_entry( $record, $fh, 6 );
4472         }
4473         elsif ( $record->{ "REC_TYPE" } eq "BLAST" and $record->{ "S_ID" } =~ /^chr/i )     # ---- Hits from BLAST ----
4474         {
4475             $new_record->{ "CHR" }     = $record->{ "S_ID" };
4476             $new_record->{ "CHR_BEG" } = $record->{ "S_BEG" };
4477             $new_record->{ "CHR_END" } = $record->{ "S_END" };
4478             $new_record->{ "Q_ID" }    = $record->{ "Q_ID" };
4479             $new_record->{ "SCORE" }   = $record->{ "SCORE" } || 999; # or use E_VAL somehow
4480             $new_record->{ "STRAND" }  = $record->{ "STRAND" };
4481
4482             Maasha::UCSC::bed_put_entry( $new_record, $fh, 6 );
4483         }
4484         elsif ( $record->{ "REC_TYPE" } eq "VMATCH" and $record->{ "S_ID" } =~ /^chr/i )    # ---- Hits from Vmatch ----
4485         {
4486             $new_record->{ "CHR" }     = $record->{ "S_ID" };
4487             $new_record->{ "CHR_BEG" } = $record->{ "S_BEG" };
4488             $new_record->{ "CHR_END" } = $record->{ "S_END" };
4489             $new_record->{ "Q_ID" }    = $record->{ "Q_ID" };
4490             $new_record->{ "SCORE" }   = $record->{ "SCORE" } || 999; # or use E_VAL somehow
4491             $new_record->{ "STRAND" }  = $record->{ "STRAND" };
4492
4493             Maasha::UCSC::bed_put_entry( $new_record, $fh, 6 );
4494         }
4495         elsif ( $record->{ "REC_TYPE" } eq "SOAP" and $record->{ "S_ID" } =~ /^chr/i )    # ---- Hits from Vmatch ----
4496         {
4497             $new_record->{ "CHR" }     = $record->{ "S_ID" };
4498             $new_record->{ "CHR_BEG" } = $record->{ "S_BEG" };
4499             $new_record->{ "CHR_END" } = $record->{ "S_END" };
4500             $new_record->{ "Q_ID" }    = $record->{ "Q_ID" };
4501             $new_record->{ "SCORE" }   = $record->{ "SCORE" } || 999;
4502             $new_record->{ "STRAND" }  = $record->{ "STRAND" };
4503
4504             Maasha::UCSC::bed_put_entry( $new_record, $fh, 6 );
4505         }
4506         elsif ( $record->{ "CHR" } and defined $record->{ "CHR_BEG" } and $record->{ "CHR_END" } )  # ---- Generic data from tables ----
4507         {
4508             Maasha::UCSC::bed_put_entry( $record, $fh );
4509         }
4510
4511         put_record( $record, $out ) if not $options->{ "no_stream" };
4512     }
4513
4514     close $fh;
4515 }
4516
4517
4518 sub script_write_psl
4519 {
4520     # Martin A. Hansen, August 2007.
4521
4522     # Write PSL output from stream.
4523
4524     my ( $in,        # handle to in stream
4525          $out,       # handle to out stream
4526          $options,   # options hash
4527        ) = @_;
4528
4529     # Returns nothing.
4530
4531     my ( $fh, $record, @output, $first );
4532
4533     $first = 1;
4534
4535     $fh = write_stream( $options->{ "data_out" }, $options->{ "compress" } );
4536
4537     while ( $record = get_record( $in ) ) 
4538     {
4539         put_record( $record, $out ) if not $options->{ "no_stream" };
4540
4541         if ( $record->{ "REC_TYPE" } and $record->{ "REC_TYPE" } eq "PSL" )
4542         {
4543             Maasha::UCSC::psl_put_header( $fh ) if $first;
4544             Maasha::UCSC::psl_put_entry( $record, $fh );
4545             $first = 0;
4546         }
4547     }
4548
4549     close $fh;
4550 }
4551
4552
4553 sub script_write_fixedstep
4554 {
4555     # Martin A. Hansen, Juli 2008.
4556
4557     # Write fixedStep entries from recrods in the stream.
4558
4559     my ( $in,        # handle to in stream
4560          $out,       # handle to out stream
4561          $options,   # options hash
4562        ) = @_;
4563
4564     # Returns nothing.
4565
4566     my ( $fh, $record, $vals );
4567
4568     $fh = write_stream( $options->{ "data_out" }, $options->{ "compress" } );
4569
4570     while ( $record = get_record( $in ) ) 
4571     {
4572         if ( $record->{ "CHR" } and $record->{ "CHR_BEG" } and $record->{ "STEP" } and $record->{ "VALS" } )
4573         {
4574             print $fh "fixedStep chrom=$record->{ 'CHR' } start=$record->{ 'CHR_BEG' } step=$record->{ 'STEP' }\n";
4575
4576             $vals = $record->{ 'VALS' };
4577
4578             $vals =~ tr/;/\n/;
4579
4580             print $fh "$vals\n";
4581         }
4582
4583         put_record( $record, $out ) if not $options->{ "no_stream" };
4584     }
4585
4586     close $fh;
4587 }
4588
4589
4590 sub script_write_2bit
4591 {
4592     # Martin A. Hansen, March 2008.
4593
4594     # Write sequence entries from stream in 2bit format.
4595
4596     my ( $in,        # handle to in stream
4597          $out,       # handle to out stream
4598          $options,   # options hash
4599        ) = @_;
4600
4601     # Returns nothing.
4602
4603     my ( $record, $mask, $tmp_file, $fh_tmp, $fh_in, $fh_out, $entry );
4604
4605     $mask = 1 if not $options->{ "no_mask" };
4606
4607     $tmp_file = "$BP_TMP/write_2bit.fna";
4608     $fh_tmp   = Maasha::Common::write_open( $tmp_file );
4609
4610     $fh_out = write_stream( $options->{ "data_out" } );
4611
4612     while ( $record = get_record( $in ) ) 
4613     {
4614         if ( $entry = record2fasta( $record ) ) {
4615             Maasha::Fasta::put_entry( $entry, $fh_tmp );
4616         }
4617
4618         put_record( $record, $out ) if not $options->{ "no_stream" };
4619     }
4620
4621     close $fh_tmp;
4622
4623     $fh_in = Maasha::Common::read_open( $tmp_file );
4624
4625     Maasha::TwoBit::fasta2twobit( $fh_in, $fh_out, $mask );
4626
4627     close $fh_in;
4628     close $fh_out;
4629
4630     unlink $tmp_file;
4631 }
4632
4633
4634 sub script_write_solid
4635 {
4636     # Martin A. Hansen, April 2008.
4637
4638     # Write di-base encoded Solid sequence from entries in stream.
4639
4640     my ( $in,        # handle to in stream
4641          $out,       # handle to out stream
4642          $options,   # options hash
4643        ) = @_;
4644
4645     # Returns nothing.
4646
4647     my ( $record, $fh, $entry );
4648
4649     $fh = write_stream( $options->{ "data_out" }, $options->{ "compress" } );
4650
4651     while ( $record = get_record( $in ) ) 
4652     {
4653         if ( $entry = record2fasta( $record ) )
4654         {
4655             $entry->[ SEQ ] = Maasha::Solid::seq2color_space( uc $entry->[ SEQ ] );
4656
4657             Maasha::Fasta::put_entry( $entry, $fh, $options->{ "wrap" } );
4658         }
4659
4660         put_record( $record, $out ) if not $options->{ "no_stream" };
4661     }
4662
4663     close $fh;
4664 }
4665
4666
4667 sub script_write_ucsc_config
4668 {
4669     # Martin A. Hansen, November 2008.
4670
4671     # Write UCSC Genome Broser configuration (.ra file type) from
4672     # records in the stream.
4673
4674     my ( $in,        # handle to in stream
4675          $out,       # handle to out stream
4676          $options,   # options hash
4677        ) = @_;
4678
4679     # Returns nothing.
4680
4681     my ( $record, $fh );
4682
4683     $fh = write_stream( $options->{ "data_out" } );
4684
4685     while ( $record = get_record( $in ) ) 
4686     {
4687         Maasha::UCSC::ucsc_config_put_entry( $record, $fh ) if $record->{ "REC_TYPE" } eq "UCSC Config";
4688
4689         put_record( $record, $out ) if not $options->{ "no_stream" };
4690     }
4691
4692     close $fh;
4693 }
4694
4695
4696 sub script_plot_seqlogo
4697 {
4698     # Martin A. Hansen, August 2007.
4699
4700     # Calculates and writes a sequence logo for alignments.
4701
4702     my ( $in,        # handle to in stream
4703          $out,       # handle to out stream
4704          $options,   # options hash
4705        ) = @_;
4706
4707     # Returns nothing.
4708
4709     my ( $record, @entries, $logo, $fh );
4710
4711     while ( $record = get_record( $in ) ) 
4712     {
4713         if ( $record->{ "SEQ_NAME" } and $record->{ "SEQ" } ) {
4714             push @entries, [ $record->{ "SEQ_NAME" }, $record->{ "SEQ" } ];
4715         }
4716
4717         put_record( $record, $out ) if not $options->{ "no_stream" };
4718     }
4719
4720     $logo = Maasha::Plot::seq_logo( \@entries );
4721
4722     $fh = write_stream( $options->{ "data_out" } );
4723
4724     print $fh $logo;
4725
4726     close $fh;
4727 }
4728
4729
4730 sub script_plot_phastcons_profiles
4731 {
4732     # Martin A. Hansen, January 2008.
4733
4734     # Plots PhastCons profiles.
4735
4736     my ( $in,        # handle to in stream
4737          $out,       # handle to out stream
4738          $options,   # options hash
4739        ) = @_;
4740
4741     # Returns nothing.
4742
4743     my ( $phastcons_file, $phastcons_index, $index, $fh_phastcons, $record, $scores, $AoA, $plot, $fh );
4744
4745     $options->{ "title" } ||= "PhastCons Profiles";
4746
4747     $phastcons_file  = Maasha::Config::genome_phastcons( $options->{ "genome" } );
4748     $phastcons_index = Maasha::Config::genome_phastcons_index( $options->{ "genome" } );
4749
4750     $index           = Maasha::UCSC::fixedstep_index_retrieve( $phastcons_index );
4751     $fh_phastcons    = Maasha::Common::read_open( $phastcons_file );
4752
4753     while ( $record = get_record( $in ) ) 
4754     {
4755         if ( $record->{ "CHR" } and $record->{ "CHR_BEG" } and $record->{ "CHR_END" } )
4756         {
4757             $scores = Maasha::UCSC::fixedstep_index_lookup( $index, $fh_phastcons, $record->{ "CHR" },
4758                                                                                    $record->{ "CHR_BEG" },
4759                                                                                    $record->{ "CHR_END" },
4760                                                                                    $options->{ "flank" } );
4761
4762             push @{ $AoA }, [ @{ $scores } ];
4763         }
4764
4765         put_record( $record, $out ) if not $options->{ "no_stream" };
4766     }
4767
4768     Maasha::UCSC::phastcons_normalize( $AoA );
4769
4770     $AoA = [ [ Maasha::UCSC::phastcons_mean( $AoA ) ] ] if $options->{ "mean" };
4771     $AoA = [ [ Maasha::UCSC::phastcons_median( $AoA ) ] ] if $options->{ "median" };
4772
4773     $AoA = Maasha::Matrix::matrix_flip( $AoA );
4774
4775     $plot = Maasha::Plot::lineplot_simple( $AoA, $options, $BP_TMP );
4776
4777     $fh = write_stream( $options->{ "data_out" } );
4778
4779     print $fh "$_\n" foreach @{ $plot };
4780
4781     close $fh;
4782 }
4783
4784
4785 sub script_analyze_bed
4786 {
4787     # Martin A. Hansen, March 2008.
4788
4789     # Analyze BED entries in stream.
4790
4791     my ( $in,        # handle to in stream
4792          $out,       # handle to out stream
4793          $options,   # options hash
4794        ) = @_;
4795
4796     # Returns nothing.
4797
4798     my ( $record );
4799
4800     while ( $record = get_record( $in ) ) 
4801     {
4802         $record = Maasha::UCSC::bed_analyze( $record ) if $record->{ "REC_TYPE" } eq "BED";
4803
4804         put_record( $record, $out );
4805     }
4806 }
4807
4808
4809 sub script_analyze_vals
4810 {
4811     # Martin A. Hansen, August 2007.
4812
4813     # Analyze values for given keys in stream.
4814
4815     my ( $in,        # handle to in stream
4816          $out,       # handle to out stream
4817          $options,   # options hash
4818        ) = @_;
4819
4820     # Returns nothing.
4821
4822     my ( $record, $key, @keys, %key_hash, $analysis, $len );
4823
4824     map { $key_hash{ $_ } = 1 } @{ $options->{ "keys" } };
4825
4826     while ( $record = get_record( $in ) ) 
4827     {
4828         foreach $key ( keys %{ $record } )
4829         {
4830             next if $options->{ "keys" } and not exists $key_hash{ $key };
4831
4832             $analysis->{ $key }->{ "COUNT" }++;
4833
4834             if ( Maasha::Calc::is_a_number( $record->{ $key } ) )
4835             {
4836                 $analysis->{ $key }->{ "TYPE" } = "num";
4837                 $analysis->{ $key }->{ "SUM" } += $record->{ $key };
4838                 $analysis->{ $key }->{ "MAX" } = $record->{ $key } if $record->{ $key } > $analysis->{ $key }->{ "MAX" } or not $analysis->{ $key }->{ "MAX" };
4839                 $analysis->{ $key }->{ "MIN" } = $record->{ $key } if $record->{ $key } < $analysis->{ $key }->{ "MIN" } or not $analysis->{ $key }->{ "MIN" };
4840             }
4841             else
4842             {
4843                 $len = length $record->{ $key };
4844
4845                 $analysis->{ $key }->{ "TYPE" } = "alph";
4846                 $analysis->{ $key }->{ "SUM" } += $len;
4847                 $analysis->{ $key }->{ "MAX" } = $len if $len > $analysis->{ $key }->{ "MAX" } or not $analysis->{ $key }->{ "MAX" };
4848                 $analysis->{ $key }->{ "MIN" } = $len if $len < $analysis->{ $key }->{ "MIM" } or not $analysis->{ $key }->{ "MIN" };
4849             }
4850         }
4851
4852         put_record( $record, $out ) if not $options->{ "no_stream" };
4853     }
4854
4855     foreach $key ( keys %{ $analysis } )
4856     {
4857         $analysis->{ $key }->{ "MEAN" } = sprintf "%.2f", $analysis->{ $key }->{ "SUM" } / $analysis->{ $key }->{ "COUNT" };
4858         $analysis->{ $key }->{ "SUM" }  = sprintf "%.2f", $analysis->{ $key }->{ "SUM" };
4859     }
4860
4861     my ( $keys, $types, $counts, $mins, $maxs, $sums, $means );
4862
4863     $keys   = "KEY  ";
4864     $types  = "TYPE ";
4865     $counts = "COUNT";
4866     $mins   = "MIN  ";
4867     $maxs   = "MAX  ";
4868     $sums   = "SUM  ";
4869     $means  = "MEAN ";
4870
4871     if ( $options->{ "keys" } ) {
4872         @keys = @{ $options->{ "keys" } };
4873     } else {
4874         @keys = keys %{ $analysis };
4875     }
4876
4877     foreach $key ( @keys )
4878     {
4879         $keys   .= sprintf "% 15s", $key;
4880         $types  .= sprintf "% 15s", $analysis->{ $key }->{ "TYPE" };
4881         $counts .= sprintf "% 15s", $analysis->{ $key }->{ "COUNT" };
4882         $mins   .= sprintf "% 15s", $analysis->{ $key }->{ "MIN" };
4883         $maxs   .= sprintf "% 15s", $analysis->{ $key }->{ "MAX" };
4884         $sums   .= sprintf "% 15s", $analysis->{ $key }->{ "SUM" };
4885         $means  .= sprintf "% 15s", $analysis->{ $key }->{ "MEAN" };
4886     }
4887
4888     print $out "$keys\n";
4889     print $out "$types\n";
4890     print $out "$counts\n";
4891     print $out "$mins\n";
4892     print $out "$maxs\n";
4893     print $out "$sums\n";
4894     print $out "$means\n";
4895 }
4896
4897
4898 sub script_head_records
4899 {
4900     # Martin A. Hansen, August 2007.
4901
4902     # Display the first sequences in stream.
4903
4904     my ( $in,        # handle to in stream
4905          $out,       # handle to out stream
4906          $options,   # options hash
4907        ) = @_;
4908
4909     # Returns nothing.
4910
4911     my ( $record, $count );
4912
4913     $options->{ "num" } ||= 10;
4914
4915     $count = 0;
4916
4917     while ( $record = get_record( $in ) ) 
4918     {
4919         $count++;
4920
4921         put_record( $record, $out );
4922
4923         last if $count == $options->{ "num" };
4924     }
4925 }
4926
4927
4928 sub script_remove_keys
4929 {
4930     # Martin A. Hansen, August 2007.
4931
4932     # Remove keys from stream.
4933
4934     my ( $in,        # handle to in stream
4935          $out,       # handle to out stream
4936          $options,   # options hash
4937        ) = @_;
4938
4939     # Returns nothing.
4940
4941     my ( $record, $new_record );
4942
4943     while ( $record = get_record( $in ) ) 
4944     {
4945         if ( $options->{ "keys" } )
4946         {
4947             map { delete $record->{ $_ } } @{ $options->{ "keys" } };
4948         }
4949         elsif ( $options->{ "save_keys" } )
4950         {
4951             map { $new_record->{ $_ } = $record->{ $_ } if exists $record->{ $_ } } @{ $options->{ "save_keys" } };
4952
4953             $record = $new_record;
4954         }
4955
4956         put_record( $record, $out ) if keys %{ $record };
4957     }
4958 }
4959
4960
4961 sub script_remove_adaptor
4962 {
4963     # Martin A. Hansen, August 2008.
4964
4965     # Find and remove adaptor from sequences in the stream.
4966
4967     my ( $in,        # handle to in stream
4968          $out,       # handle to out stream
4969          $options,   # options hash
4970        ) = @_;
4971
4972     # Returns nothing.
4973
4974     my ( $record, $adaptor, $seq, $adaptor_len, $seq_len, $offset, $max_match, $max_mismatch, $pos );
4975
4976     $options->{ "remove" } ||= "after";
4977
4978     $max_mismatch = $options->{ "mismatches" } || 0;
4979     $offset       = $options->{ "offset" };
4980
4981     if ( not defined $offset ) {
4982         $offset = 0;
4983     } else {
4984         $offset--;
4985     }
4986
4987     $adaptor      = uc $options->{ "adaptor" };
4988     $adaptor_len  = length $adaptor;
4989
4990     while ( $record = get_record( $in ) ) 
4991     {
4992         if ( $record->{ "SEQ" } )
4993         {
4994             $seq     = uc $record->{ "SEQ" };
4995             $seq_len = length $seq;
4996
4997             $pos = Maasha::Common::index_m( $seq, $adaptor, $seq_len, $adaptor_len, $offset, $max_mismatch );
4998
4999             $record->{ "ADAPTOR_POS" } = $pos;
5000
5001             if ( $pos >= 0 and $options->{ "remove" } ne "skip" )
5002             {
5003                 if ( $options->{ "remove" } eq "after" )
5004                 {
5005                     $record->{ "SEQ" }     = substr $record->{ "SEQ" }, 0, $pos;
5006                     $record->{ "SEQ_LEN" } = $pos;
5007                 }
5008                 else
5009                 {
5010                     $record->{ "SEQ" }     = substr $record->{ "SEQ" }, $pos + $adaptor_len;
5011                     $record->{ "SEQ_LEN" } = length $record->{ "SEQ" };
5012                 }
5013             }
5014
5015             put_record( $record, $out );
5016         }
5017         else
5018         {
5019             put_record( $record, $out );
5020         }
5021     }
5022 }
5023
5024
5025 sub script_remove_mysql_tables
5026 {
5027     # Martin A. Hansen, November 2008.
5028
5029     # Remove MySQL tables from values in stream.
5030
5031     my ( $in,        # handle to in stream
5032          $out,       # handle to out stream
5033          $options,   # options hash
5034        ) = @_;
5035
5036     # Returns nothing.
5037
5038     my ( $record, %table_hash, $dbh, $table );
5039
5040     $options->{ "user" }     ||= Maasha::UCSC::ucsc_get_user();
5041     $options->{ "password" } ||= Maasha::UCSC::ucsc_get_password();
5042
5043     map { $table_hash{ $_ } = 1 } @{ $options->{ 'tables' } };
5044
5045     while ( $record = get_record( $in ) )
5046     {
5047         map { $table_hash{ $record->{ $_ } } = 1 } @{ $options->{ 'keys' } };
5048
5049         put_record( $record, $out ) if not $options->{ 'no_stream' };
5050     }
5051
5052     $dbh = Maasha::SQL::connect( $options->{ "database" }, $options->{ "user" }, $options->{ "password" } );
5053
5054     foreach $table ( sort keys %table_hash )
5055     {
5056         if ( Maasha::SQL::table_exists( $dbh, $table ) )
5057         {
5058             print STDERR qq(Removing table "$table" from database "$options->{ 'database' }" ... ) if $options->{ 'verbose' };
5059             Maasha::SQL::delete_table( $dbh, $table );
5060             print STDERR "done.\n" if $options->{ 'verbose' };
5061         }
5062         else
5063         {
5064             print STDERR qq(WARNING: table "$table" not found in database "$options->{ 'database' }\n");
5065         }
5066     }
5067
5068     Maasha::SQL::disconnect( $dbh );
5069 }
5070
5071
5072 sub script_remove_ucsc_tracks
5073 {
5074     # Martin A. Hansen, November 2008.
5075
5076     # Remove track from MySQL tables and config file.
5077
5078     my ( $in,        # handle to in stream
5079          $out,       # handle to out stream
5080          $options,   # options hash
5081        ) = @_;
5082
5083     # Returns nothing.
5084
5085     my ( $record, %track_hash, $fh_in, $fh_out, $track, @tracks, @new_tracks, $dbh );
5086
5087     $options->{ 'user' }        ||= Maasha::UCSC::ucsc_get_user();
5088     $options->{ 'password' }    ||= Maasha::UCSC::ucsc_get_password();
5089     $options->{ 'config_file' } ||= "$ENV{ 'HOME' }/ucsc/my_tracks.ra";
5090
5091     map { $track_hash{ $_ } = 1 } @{ $options->{ 'tracks' } };
5092
5093     while ( $record = get_record( $in ) )
5094     {
5095         map { $track_hash{ $record->{ $_ } } = 1 } @{ $options->{ 'keys' } };
5096
5097         put_record( $record, $out ) if not $options->{ 'no_stream' };
5098     }
5099
5100     # ---- locate track in config file ----
5101
5102     $fh_in = Maasha::Common::read_open( $options->{ 'config_file' } );
5103     
5104     while ( $track = Maasha::UCSC::ucsc_config_get_entry( $fh_in ) ) {
5105         push @tracks, $track;
5106     }
5107
5108     close $fh_in;
5109
5110     map { push @new_tracks, $_ if not exists $track_hash{ $_->{ 'track' } } } @tracks;
5111
5112     print STDERR qq(WARNING: track not found in config file: "$options->{ 'config_file' }"\n) if scalar @tracks == scalar @new_tracks;
5113
5114     rename "$options->{ 'config_file' }", "$options->{ 'config_file' }~";
5115
5116     $fh_out = Maasha::Common::write_open( $options->{ 'config_file' } );
5117
5118     map { Maasha::UCSC::ucsc_config_put_entry( $_, $fh_out ) } @new_tracks;
5119
5120     close $fh_out;
5121
5122     # ---- locate track in database ----
5123
5124     $dbh = Maasha::SQL::connect( $options->{ "database" }, $options->{ "user" }, $options->{ "password" } );
5125
5126     foreach $track ( sort keys %track_hash )
5127     {
5128         if ( Maasha::SQL::table_exists( $dbh, $track ) )
5129         {
5130             print STDERR qq(Removing table "$track" from database "$options->{ 'database' }" ... ) if $options->{ 'verbose' };
5131             Maasha::SQL::delete_table( $dbh, $track );
5132             print STDERR "done.\n" if $options->{ 'verbose' };
5133         }
5134         else
5135         {
5136             print STDERR qq(WARNING: table "$track" not found in database "$options->{ 'database' }\n");
5137         }
5138     }
5139
5140     Maasha::SQL::disconnect( $dbh );
5141
5142     Maasha::Common::run( "ucscMakeTracks.pl", "-b > /dev/null 2>&1" );
5143 }
5144
5145
5146 sub script_rename_keys
5147 {
5148     # Martin A. Hansen, August 2007.
5149
5150     # Rename keys in stream.
5151
5152     my ( $in,        # handle to in stream
5153          $out,       # handle to out stream
5154          $options,   # options hash
5155        ) = @_;
5156
5157     # Returns nothing.
5158
5159     my ( $record );
5160
5161     while ( $record = get_record( $in ) ) 
5162     {
5163         if ( exists $record->{ $options->{ "keys" }->[ 0 ] } )
5164         {
5165             $record->{ $options->{ "keys" }->[ 1 ] } = $record->{ $options->{ "keys" }->[ 0 ] };
5166
5167             delete $record->{ $options->{ "keys" }->[ 0 ] };
5168         }
5169
5170         put_record( $record, $out );
5171     }
5172 }
5173
5174
5175 sub script_uniq_vals
5176 {
5177     # Martin A. Hansen, August 2007.
5178
5179     # Find unique values in stream.
5180
5181     my ( $in,        # handle to in stream
5182          $out,       # handle to out stream
5183          $options,   # options hash
5184        ) = @_;
5185
5186     # Returns nothing.
5187
5188     my ( %hash, $record );
5189
5190     while ( $record = get_record( $in ) ) 
5191     {
5192         if ( $record->{ $options->{ "key" } } )
5193         {
5194             if ( not $hash{ $record->{ $options->{ "key" } } } and not $options->{ "invert" } )
5195             {
5196                 put_record( $record, $out );
5197
5198                 $hash{ $record->{ $options->{ "key" } } } = 1;
5199             }
5200             elsif ( $hash{ $record->{ $options->{ "key" } } } and $options->{ "invert" } )
5201             {
5202                 put_record( $record, $out );
5203             }
5204             else
5205             {
5206                 $hash{ $record->{ $options->{ "key" } } } = 1;
5207             }
5208         }
5209         else
5210         {
5211             put_record( $record, $out );
5212         }
5213     }
5214 }
5215
5216
5217 sub script_merge_vals
5218 {
5219     # Martin A. Hansen, August 2007.
5220
5221     # Rename keys in stream.
5222
5223     my ( $in,        # handle to in stream
5224          $out,       # handle to out stream
5225          $options,   # options hash
5226        ) = @_;
5227
5228     # Returns nothing.
5229
5230     my ( $record, @join, $i );
5231
5232     $options->{ "delimit" } ||= '_';
5233
5234     while ( $record = get_record( $in ) ) 
5235     {
5236         if ( exists $record->{ $options->{ "keys" }->[ 0 ] } )
5237         {
5238             @join = $record->{ $options->{ "keys" }->[ 0 ] };
5239             
5240             for ( $i = 1; $i < @{ $options->{ "keys" } }; $i++ ) {
5241                 push @join, $record->{ $options->{ "keys" }->[ $i ] } if exists $record->{ $options->{ "keys" }->[ $i ] };
5242             }
5243
5244             $record->{ $options->{ "keys" }->[ 0 ] } = join $options->{ "delimit" }, @join;
5245         }
5246
5247         put_record( $record, $out );
5248     }
5249 }
5250
5251
5252 sub script_merge_records
5253 {
5254     # Martin A. Hansen, July 2008.
5255
5256     # Merges records in the stream based on identical values of two given keys.
5257
5258     my ( $in,        # handle to in stream
5259          $out,       # handle to out stream
5260          $options,   # options hash
5261        ) = @_;
5262
5263     # Returns nothing.
5264
5265     my ( $merge, $record, $file1, $file2, $fh1, $fh2, $key1, $key2, @keys1, @keys2, @vals1, @vals2,
5266          $num1, $num2, $num, $cmp, $i );
5267
5268     $merge = $options->{ "merge" } || "AandB";
5269
5270     $file1 = "$BP_TMP/merge_records1.tmp";
5271     $file2 = "$BP_TMP/merge_records2.tmp";
5272
5273     $fh1   = Maasha::Common::write_open( $file1 );
5274     $fh2   = Maasha::Common::write_open( $file2 );
5275
5276     $key1  = $options->{ "keys" }->[ 0 ];
5277     $key2  = $options->{ "keys" }->[ 1 ];
5278
5279     $num   = $key2 =~ s/n$//;
5280     $num1  = 0;
5281     $num2  = 0;
5282
5283     while ( $record = get_record( $in ) ) 
5284     {
5285         if ( exists $record->{ $key1 } )
5286         {
5287             @keys1 = $key1;
5288             @vals1 = $record->{ $key1 };
5289
5290             delete $record->{ $key1 };
5291
5292             map { push @keys1, $_; push @vals1, $record->{ $_ } } keys %{ $record };
5293
5294             print $fh1 join( "\t", @vals1 ), "\n";
5295
5296             $num1++;
5297         }
5298         elsif ( exists $record->{ $key2 } )
5299         {
5300             @keys2 = $key2;
5301             @vals2 = $record->{ $key2 };
5302
5303             delete $record->{ $key2 };
5304
5305             map { push @keys2, $_; push @vals2, $record->{ $_ } } keys %{ $record };
5306
5307             print $fh2 join( "\t", @vals2 ), "\n";
5308
5309             $num2++;
5310         }
5311     }
5312
5313     close $fh1;
5314     close $fh2;
5315
5316     if ( $num )
5317     {
5318         Maasha::Common::run( "sort", "-k 1,1n $file1 > $file1.sort" ) and rename "$file1.sort", $file1;
5319         Maasha::Common::run( "sort", "-k 1,1n $file2 > $file2.sort" ) and rename "$file2.sort", $file2;
5320     }
5321     else
5322     {
5323         Maasha::Common::run( "sort", "-k 1,1 $file1 > $file1.sort" ) and rename "$file1.sort", $file1;
5324         Maasha::Common::run( "sort", "-k 1,1 $file2 > $file2.sort" ) and rename "$file2.sort", $file2;
5325     }
5326
5327     $fh1 = Maasha::Common::read_open( $file1 );
5328     $fh2 = Maasha::Common::read_open( $file2 );
5329
5330     @vals1 = Maasha::Common::get_fields( $fh1 );
5331     @vals2 = Maasha::Common::get_fields( $fh2 );
5332
5333     while ( $num1 > 0 and $num2 > 0 )
5334     {
5335         undef $record;
5336
5337         if ( $num ) {
5338             $cmp = $vals1[ 0 ] <=> $vals2[ 0 ];
5339         } else {
5340             $cmp = $vals1[ 0 ] cmp $vals2[ 0 ];
5341         }
5342
5343         if ( $cmp < 0 )
5344         {
5345             if ( $merge =~ /^(AorB|AnotB)$/ )
5346             {
5347                 for ( $i = 0; $i < @keys1; $i++ ) {
5348                     $record->{ $keys1[ $i ] } = $vals1[ $i ];
5349                 }
5350
5351                 put_record( $record, $out );
5352             }
5353
5354             @vals1 = Maasha::Common::get_fields( $fh1 );
5355             $num1--;
5356         }
5357         elsif ( $cmp > 0 )
5358         {
5359             if ( $merge =~ /^(BorA|BnotA)$/ )
5360             {
5361                 for ( $i = 0; $i < @keys2; $i++ ) {
5362                     $record->{ $keys2[ $i ] } = $vals2[ $i ];
5363                 }
5364
5365                 put_record( $record, $out );
5366             }
5367
5368             @vals2 = Maasha::Common::get_fields( $fh2 );
5369             $num2--;
5370         }
5371         else
5372         {
5373             if ( $merge =~ /^(AandB|AorB|BorA)$/ )
5374             {
5375                 for ( $i = 0; $i < @keys1; $i++ ) {
5376                     $record->{ $keys1[ $i ] } = $vals1[ $i ];
5377                 }
5378
5379                 for ( $i = 1; $i < @keys2; $i++ ) {
5380                     $record->{ $keys2[ $i ] } = $vals2[ $i ];
5381                 }
5382             
5383                 put_record( $record, $out );
5384             }
5385
5386             @vals1 = Maasha::Common::get_fields( $fh1 );
5387             @vals2 = Maasha::Common::get_fields( $fh2 );
5388             $num1--;
5389             $num2--;
5390         }
5391     }
5392
5393     close $fh1;
5394     close $fh2;
5395
5396     unlink $file1;
5397     unlink $file2;
5398
5399     if ( $num1 > 0 and $merge =~ /^(AorB|AnotB)$/ )
5400     {
5401         undef $record;
5402
5403         for ( $i = 0; $i < @keys1; $i++ ) {
5404             $record->{ $keys1[ $i ] } = $vals1[ $i ];
5405         }
5406
5407         put_record( $record, $out );
5408     }
5409
5410     if ( $num2 > 0 and $merge =~ /^(BorA|BnotA)$/ )
5411     {
5412         undef $record;
5413
5414         for ( $i = 0; $i < @keys2; $i++ ) {
5415             $record->{ $keys2[ $i ] } = $vals2[ $i ];
5416         }
5417
5418         put_record( $record, $out );
5419     }
5420 }
5421
5422
5423 sub script_grab
5424 {
5425     # Martin A. Hansen, August 2007.
5426
5427     # Grab for records in stream.
5428
5429     my ( $in,        # handle to in stream
5430          $out,       # handle to out stream
5431          $options,   # options hash
5432        ) = @_;
5433
5434     # Returns nothing.
5435
5436     my ( $keys, $vals_only, $keys_only, $invert, $patterns, $pattern, $regex, $record, $key, $op, $val, %lookup_hash, $found );
5437
5438     $keys      = $options->{ 'keys' };
5439     $vals_only = $options->{ 'vals_only' };
5440     $keys_only = $options->{ 'keys_only' };
5441     $invert    = $options->{ 'invert' };
5442
5443     if ( $options->{ 'patterns' } )
5444     {
5445         $patterns = [ split ",", $options->{ 'patterns' } ];
5446     }
5447     elsif ( -f $options->{ 'patterns_in' } )
5448     {
5449         $patterns = Maasha::Patscan::read_patterns( $options->{ 'patterns_in' } );
5450     }
5451     elsif ( $options->{ 'regex' } )
5452     {
5453         if ( $options->{ 'case_insensitive' } ) {
5454             $regex = qr/$options->{ 'regex' }/i;
5455         } else {
5456             $regex = qr/$options->{ 'regex' }/;
5457         }
5458     }
5459     elsif ( -f $options->{ 'exact_in' } )
5460     {
5461         $patterns = Maasha::Patscan::read_patterns( $options->{ 'exact_in' } );
5462
5463         map { $lookup_hash{ $_ } = 1 } @{ $patterns };
5464
5465         undef $patterns;
5466     }
5467     elsif ( $options->{ 'eval' } )
5468     {
5469         if ( $options->{ 'eval' } =~ /^([^><=! ]+)\s*(>=|<=|>|<|=|!=|eq|ne)\s*(.+)$/ )
5470         {
5471             $key = $1;
5472             $op  = $2;
5473             $val = $3;
5474         }
5475     } 
5476
5477     while ( $record = get_record( $in ) ) 
5478     {
5479         $found = 0;
5480
5481         if ( %lookup_hash ) {
5482             $found = grab_lookup( \%lookup_hash, $record, $keys, $vals_only, $keys_only );
5483         } elsif ( $patterns ) {
5484             $found = grab_patterns( $patterns, $record, $keys, $vals_only, $keys_only );
5485         } elsif ( $regex ) {
5486             $found = grab_regex( $regex, $record, $keys, $vals_only, $keys_only );
5487         } elsif ( $op ) {
5488             $found = grab_eval( $key, $op, $val, $record );
5489         }
5490
5491         if ( $found and not $invert ) {
5492             put_record( $record, $out );
5493         } elsif ( not $found and $invert ) {
5494             put_record( $record, $out );
5495         }
5496     }
5497 }
5498
5499
5500 sub script_compute
5501 {
5502     # Martin A. Hansen, August 2007.
5503
5504     # Evaluate extression for records in stream.
5505
5506     my ( $in,        # handle to in stream
5507          $out,       # handle to out stream
5508          $options,   # options hash
5509        ) = @_;
5510
5511     # Returns nothing.
5512
5513     my ( $record, $eval_key, @keys, $eval_val );
5514
5515     while ( $record = get_record( $in ) ) 
5516     {
5517         if ( $options->{ "eval" } )
5518         {
5519             if ( $options->{ "eval" } =~ /^(.+)\s*=\s*(.+)$/ )
5520             {
5521                 $eval_key = $1;
5522                 $eval_val = $2;
5523
5524                 if ( not @keys )
5525                 {
5526                     @keys = split /\s+|\+|-|\*|\/|\*\*/, $eval_val;
5527
5528                     @keys = grep { exists $record->{ $_ } } @keys;
5529                 }
5530
5531                 map { $eval_val =~ s/\Q$_\E/$record->{ $_ }/g } @keys;
5532
5533                 $record->{ $eval_key } = eval "$eval_val" or Maasha::Common::error( "eval failed -> $@" );
5534             }
5535             else
5536             {
5537                 warn qq(WARNING: Bad compute expression: "$options->{ 'eval' }"\n);
5538             }
5539         } 
5540
5541         put_record( $record, $out );
5542     }
5543 }
5544
5545
5546 sub script_flip_tab
5547 {
5548     # Martin A. Hansen, June 2008.
5549
5550     # Flip a table.
5551
5552     my ( $in,        # handle to in stream
5553          $out,       # handle to out stream
5554          $options,   # options hash
5555        ) = @_;
5556
5557     # Returns nothing.
5558
5559     my ( $record, $key, $A, $B, @rows, @matrix, $row, $i );
5560
5561     while ( $record = get_record( $in ) ) 
5562     {
5563         undef @rows;
5564
5565         foreach $key ( sort { $A = $a; $B = $b; $A =~ s/^V(\d+)$/$1/; $B =~ s/^V(\d+)$/$1/; $A <=> $B } keys %{ $record } )
5566         {
5567             push @rows, $record->{ $key };
5568
5569         }
5570
5571         push @matrix, [ @rows ];
5572     }
5573
5574     undef $record;
5575
5576     @matrix = Maasha::Matrix::matrix_flip( \@matrix );
5577
5578     foreach $row ( @matrix )
5579     {
5580         for ( $i = 0; $i < @{ $row }; $i++ ) {
5581             $record->{ "V$i" } = $row->[ $i ];
5582         }
5583
5584         put_record( $record, $out );
5585     }
5586 }
5587
5588
5589 sub script_add_ident
5590 {
5591     # Martin A. Hansen, May 2008.
5592
5593     # Add a unique identifier to each record in stream.
5594
5595     my ( $in,        # handle to in stream
5596          $out,       # handle to out stream
5597          $options,   # options hash
5598        ) = @_;
5599
5600     # Returns nothing.
5601
5602     my ( $record, $key, $prefix, $i );
5603
5604     $key    = $options->{ "key" }    || "ID";
5605     $prefix = $options->{ "prefix" } || "ID";
5606
5607     $i = 0;
5608
5609     while ( $record = get_record( $in ) ) 
5610     {
5611         $record->{ $key } = sprintf( "$prefix%08d", $i );
5612
5613         put_record( $record, $out );
5614
5615         $i++;
5616     }
5617 }
5618
5619
5620 sub script_count_records
5621 {
5622     # Martin A. Hansen, August 2007.
5623
5624     # Count records in stream.
5625
5626     my ( $in,        # handle to in stream
5627          $out,       # handle to out stream
5628          $options,   # options hash
5629        ) = @_;
5630
5631     # Returns nothing.
5632
5633     my ( $record, $count, $result, $fh, $line );
5634
5635     $count = 0;
5636
5637     if ( $options->{ "no_stream" } )
5638     {
5639         while ( $line = <$in> )
5640         {
5641             chomp $line;
5642
5643             $count++ if $line eq "---";
5644         }
5645     }
5646     else
5647     {
5648         while ( $record = get_record( $in ) ) 
5649         {
5650             put_record( $record, $out );
5651
5652             $count++;
5653         }
5654     }
5655
5656     $result = { "RECORDS_COUNT" => $count };
5657
5658     $fh = write_stream( $options->{ "data_out" } );
5659
5660     put_record( $result, $fh );
5661
5662     close $fh;
5663 }
5664
5665
5666 sub script_random_records
5667 {
5668     # Martin A. Hansen, August 2007.
5669
5670     # Pick a number or random records from stream.
5671
5672     my ( $in,        # handle to in stream
5673          $out,       # handle to out stream
5674          $options,   # options hash
5675        ) = @_;
5676
5677     # Returns nothing.
5678
5679     my ( $record, $tmp_file, $fh_out, $fh_in, $count, $i, %rand_hash, $rand, $max );
5680
5681     $options->{ "num" } ||= 10;
5682
5683     $tmp_file = "$BP_TMP/random_records.tmp";
5684
5685     $fh_out = Maasha::Common::write_open( $tmp_file );
5686
5687     $count = 0;
5688
5689     while ( $record = get_record( $in ) ) 
5690     {
5691         put_record( $record, $fh_out );
5692
5693         $count++;
5694     }
5695
5696     close $fh_out;
5697
5698     $max = 0;
5699     $i   = 0;
5700
5701     Maasha::Common::error( qq(Requested random records > records in stream) ) if $options->{ "num" } > $count;
5702
5703     while ( $i < $options->{ "num" } )
5704     {
5705         $rand = int( rand( $count ) );
5706     
5707         if ( not exists $rand_hash{ $rand } )
5708         {
5709             $rand_hash{ $rand } = 1;
5710
5711             $max = $rand if $rand > $max;
5712
5713             $i++;
5714         }
5715     }
5716
5717     $fh_in = Maasha::Common::read_open( $tmp_file );
5718
5719     $count = 0;
5720
5721     while ( $record = get_record( $fh_in ) ) 
5722     {
5723         put_record( $record, $out ) if exists $rand_hash{ $count };
5724
5725         last if $count == $max;
5726
5727         $count++;
5728     }
5729
5730     close $fh_in;
5731
5732     unlink $tmp_file;
5733 }
5734
5735
5736 sub script_sort_records
5737 {
5738     # Martin A. Hansen, August 2007.
5739
5740     # Sort to sort records according to keys.
5741
5742     my ( $in,        # handle to in stream
5743          $out,       # handle to out stream
5744          $options,   # options hash
5745        ) = @_;
5746
5747     # Returns nothing.
5748
5749     my ( @keys, $key, @sort_cmd, $sort_str, $sort_sub, @records, $record, $i );
5750
5751     foreach $key ( @{ $options->{ "keys" } } )
5752     {
5753         if ( $key =~ s/n$// ) {
5754             push @sort_cmd, qq(\$a->{ "$key" } <=> \$b->{ "$key" });
5755         } else {
5756             push @sort_cmd, qq(\$a->{ "$key" } cmp \$b->{ "$key" });
5757         }
5758     }
5759
5760     $sort_str = join " or ", @sort_cmd;
5761     $sort_sub = eval "sub { $sort_str }";   # NB security issue!
5762
5763     while ( $record = get_record( $in ) ) {
5764         push @records, $record;
5765     }
5766
5767     @records = sort $sort_sub @records;
5768
5769     if ( $options->{ "reverse" } )
5770     {
5771         for ( $i = scalar @records - 1; $i >= 0; $i-- ) {
5772             put_record( $records[ $i ], $out );
5773         }
5774     }
5775     else
5776     {
5777         for ( $i = 0; $i < scalar @records; $i++ ) {
5778             put_record( $records[ $i ], $out );
5779         }
5780     }
5781 }
5782
5783
5784 sub script_count_vals
5785 {
5786     # Martin A. Hansen, August 2007.
5787
5788     # Count records in stream.
5789
5790     my ( $in,        # handle to in stream
5791          $out,       # handle to out stream
5792          $options,   # options hash
5793        ) = @_;
5794
5795     # Returns nothing.
5796
5797     my ( $num, $record, %count_hash, @records, $tmp_file, $fh_out, $fh_in, $cache );
5798
5799     $tmp_file = "$BP_TMP/count_cache.tmp";
5800
5801     $fh_out   = Maasha::Common::write_open( $tmp_file );
5802
5803     $cache    = 0;
5804     $num      = 0;
5805
5806     while ( $record = get_record( $in ) ) 
5807     {
5808         map { $count_hash{ $_ }{ $record->{ $_ } }++ if exists $record->{ $_ } } @{ $options->{ "keys" } };
5809
5810         push @records, $record;
5811
5812         if ( scalar @records > 5_000_000 )   # too many records to hold in memory - use disk cache
5813         {
5814             map { put_record( $_, $fh_out ) } @records;
5815
5816             undef @records;
5817
5818             $cache = 1;
5819         }
5820
5821         print STDERR "verbose: records read $num\n" if ( $options->{ 'verbose' } and ( $num % 1_000_000 ) == 0 );
5822
5823         $num++;
5824     }
5825
5826     close $fh_out;
5827
5828     if ( $cache )
5829     {
5830         $num   = 0;
5831
5832         $fh_in = Maasha::Common::read_open( $tmp_file );
5833
5834         while ( $record = get_record( $fh_in ) )
5835         {
5836             map { $record->{ $_ . "_COUNT" } = $count_hash{ $_ }{ $record->{ $_ } } if exists $record->{ $_ } } @{ $options->{ "keys" } };
5837
5838             put_record( $record, $out );
5839
5840             print STDERR "verbose: cache read $num\n" if ( $options->{ 'verbose' } and ( $num % 1_000_000 ) == 0 );
5841
5842             $num++;
5843         }
5844     
5845         close $fh_in;
5846     }
5847
5848     foreach $record ( @records )
5849     {
5850         map { $record->{ $_ . "_COUNT" } = $count_hash{ $_ }{ $record->{ $_ } } if exists $record->{ $_ } } @{ $options->{ "keys" } };
5851
5852         put_record( $record, $out );
5853     }
5854
5855     unlink $tmp_file;
5856 }
5857
5858
5859 sub script_plot_histogram
5860 {
5861     # Martin A. Hansen, September 2007.
5862
5863     # Plot a simple histogram for a given key using GNU plot.
5864
5865     my ( $in,        # handle to in stream
5866          $out,       # handle to out stream
5867          $options,   # options hash
5868        ) = @_;
5869
5870     # Returns nothing.
5871
5872     my ( $record, %data_hash, $max, @data_list, $i, $result, $fh );
5873
5874     $options->{ "title" } ||= "Histogram";
5875     $options->{ "sort" }  ||= "num";
5876
5877     while ( $record = get_record( $in ) ) 
5878     {
5879         $data_hash{ $record->{ $options->{ "key" } } }++ if defined $record->{ $options->{ "key" } };
5880
5881         put_record( $record, $out ) if not $options->{ "no_stream" };
5882     }
5883
5884     if ( $options->{ "sort" } eq "num" ) {
5885         map { push @data_list, [ $_, $data_hash{ $_ } ] } sort { $a <=> $b } keys %data_hash;
5886     } else {
5887         map { push @data_list, [ $_, $data_hash{ $_ } ] } sort keys %data_hash;
5888     }
5889
5890     $result = Maasha::Plot::histogram_simple( \@data_list, $options );
5891
5892     $fh = write_stream( $options->{ "data_out" } );
5893
5894     print $fh "$_\n" foreach @{ $result };
5895
5896     close $fh;
5897 }
5898
5899
5900 sub script_plot_lendist
5901 {
5902     # Martin A. Hansen, August 2007.
5903
5904     # Plot length distribution using GNU plot.
5905
5906     my ( $in,        # handle to in stream
5907          $out,       # handle to out stream
5908          $options,   # options hash
5909        ) = @_;
5910
5911     # Returns nothing.
5912
5913     my ( $record, %data_hash, $max, @data_list, $i, $result, $fh );
5914
5915     $options->{ "title" } ||= "Length Distribution";
5916
5917     while ( $record = get_record( $in ) ) 
5918     {
5919         $data_hash{ $record->{ $options->{ "key" } } }++ if defined $record->{ $options->{ "key" } };
5920
5921         put_record( $record, $out ) if not $options->{ "no_stream" };
5922     }
5923
5924     $max = Maasha::Calc::list_max( [ keys %data_hash ] );
5925
5926     for ( $i = 0; $i < $max; $i++ ) {
5927         push @data_list, [ $i, $data_hash{ $i } || 0 ];
5928     }
5929
5930     $result = Maasha::Plot::histogram_lendist( \@data_list, $options );
5931
5932     $fh = write_stream( $options->{ "data_out" } );
5933
5934     print $fh "$_\n" foreach @{ $result };
5935
5936     close $fh;
5937 }
5938
5939
5940 sub script_plot_chrdist
5941 {
5942     # Martin A. Hansen, August 2007.
5943
5944     # Plot chromosome distribution using GNU plot.
5945
5946     my ( $in,        # handle to in stream
5947          $out,       # handle to out stream
5948          $options,   # options hash
5949        ) = @_;
5950
5951     # Returns nothing.
5952
5953     my ( $record, %data_hash, @data_list, $elem, $sort_key, $count, $result, $fh );
5954
5955     $options->{ "title" } ||= "Chromosome Distribution";
5956
5957     while ( $record = get_record( $in ) ) 
5958     {
5959         if ( $record->{ "CHR" } ) {                                                             # generic
5960             $data_hash{ $record->{ "CHR" } }++;
5961         } elsif ( $record->{ "REC_TYPE" } eq "PATSCAN" and $record->{ "S_ID" } =~ /^chr/i ) {   # patscan
5962             $data_hash{ $record->{ "S_ID" } }++;
5963         } elsif ( $record->{ "REC_TYPE" } eq "PSL" and $record->{ "S_ID" } =~ /^chr/i ) {       # BLAT / PSL
5964             $data_hash{ $record->{ "S_ID" } }++;
5965         } elsif ( $record->{ "REC_TYPE" } eq "BLAST" and $record->{ "S_ID" } =~ /^chr/i ) {     # BLAST
5966             $data_hash{ $record->{ "S_ID" } }++;
5967         }
5968
5969         put_record( $record, $out ) if not $options->{ "no_stream" };
5970     }
5971
5972     foreach $elem ( keys %data_hash )
5973     {
5974         $sort_key = $elem;
5975
5976         $sort_key =~ s/chr//i;
5977     
5978         $sort_key =~ s/^X(.*)/99$1/;
5979         $sort_key =~ s/^Y(.*)/99$1/;
5980         $sort_key =~ s/^Z(.*)/999$1/;
5981         $sort_key =~ s/^M(.*)/9999$1/;
5982         $sort_key =~ s/^U(.*)/99999$1/;
5983
5984         $count = $sort_key =~ tr/_//;
5985
5986         $sort_key =~ s/_.*/"999999" x $count/ex;
5987
5988         push @data_list, [ $elem, $data_hash{ $elem }, $sort_key ];
5989     }
5990
5991     @data_list = sort { $a->[ 2 ] <=> $b->[ 2 ] } @data_list;
5992
5993     $result = Maasha::Plot::histogram_chrdist( \@data_list, $options );
5994
5995     $fh = write_stream( $options->{ "data_out" } );
5996
5997     print $fh "$_\n" foreach @{ $result };
5998
5999     close $fh;
6000 }
6001
6002
6003 sub script_plot_karyogram
6004 {
6005     # Martin A. Hansen, August 2007.
6006
6007     # Plot hits on karyogram.
6008
6009     my ( $in,        # handle to in stream
6010          $out,       # handle to out stream
6011          $options,   # options hash
6012        ) = @_;
6013
6014     # Returns nothing.
6015
6016     my ( %options, $record, @data, $fh, $result, %data_hash );
6017
6018     $options->{ "genome" }     ||= "human";
6019     $options->{ "feat_color" } ||= "black";
6020
6021     while ( $record = get_record( $in ) ) 
6022     {
6023         if ( $record->{ "CHR" } and $record->{ "CHR_BEG" } and $record->{ "CHR_END" } )
6024         {
6025             push @{ $data_hash{ $record->{ "CHR" } } }, [ $record->{ "CHR_BEG" }, $record->{ "CHR_END" }, $options->{ "feat_color" } ];
6026         }
6027
6028         put_record( $record, $out ) if not $options->{ "no_stream" };
6029     }
6030
6031     $result = Maasha::Plot::karyogram( \%data_hash, \%options );
6032
6033     $fh = write_stream( $options->{ "data_out" } );
6034
6035     print $fh $result;
6036
6037     close $fh;
6038 }
6039
6040
6041 sub script_plot_matches
6042 {
6043     # Martin A. Hansen, August 2007.
6044
6045     # Plot matches in 2D generating a dotplot.
6046
6047     my ( $in,        # handle to in stream
6048          $out,       # handle to out stream
6049          $options,   # options hash
6050        ) = @_;
6051
6052     # Returns nothing.
6053
6054     my ( $record, @data, $fh, $result, %data_hash );
6055
6056     $options->{ "direction" } ||= "both";
6057
6058     while ( $record = get_record( $in ) ) 
6059     {
6060         if ( defined $record->{ "Q_BEG" } and defined $record->{ "S_BEG" } and $record->{ "Q_END" } and $record->{ "S_END" } ) {
6061             push @data, $record;
6062         }
6063
6064         put_record( $record, $out ) if not $options->{ "no_stream" };
6065     }
6066
6067     $options->{ "title" }  ||= "plot_matches";
6068     $options->{ "xlabel" } ||= $data[ 0 ]->{ "Q_ID" };
6069     $options->{ "ylabel" } ||= $data[ 0 ]->{ "S_ID" };
6070
6071     $result = Maasha::Plot::dotplot_matches( \@data, $options, $BP_TMP );
6072
6073     $fh = write_stream( $options->{ "data_out" } );
6074
6075     print $fh "$_\n" foreach @{ $result };
6076
6077     close $fh;
6078 }
6079
6080
6081 sub script_length_vals
6082 {
6083     # Martin A. Hansen, August 2007.
6084
6085     # Determine the length of the value for given keys.
6086
6087     my ( $in,        # handle to in stream
6088          $out,       # handle to out stream
6089          $options,   # options hash
6090        ) = @_;
6091
6092     # Returns nothing.
6093
6094     my ( $record, $key );
6095
6096     while ( $record = get_record( $in ) ) 
6097     {
6098         foreach $key ( @{ $options->{ "keys" } } )
6099         {
6100             if ( $record->{ $key } ) {
6101                 $record->{ $key . "_LEN" } = length $record->{ $key };
6102             }
6103         }
6104
6105         put_record( $record, $out );
6106     }
6107 }
6108
6109
6110 sub script_sum_vals
6111 {
6112     # Martin A. Hansen, August 2007.
6113
6114     # Calculates the sums for values of given keys.
6115
6116     my ( $in,        # handle to in stream
6117          $out,       # handle to out stream
6118          $options,   # options hash
6119        ) = @_;
6120
6121     # Returns nothing.
6122
6123     my ( $record, $key, %sum_hash, $fh );
6124
6125     while ( $record = get_record( $in ) ) 
6126     {
6127         foreach $key ( @{ $options->{ "keys" } } )
6128         {
6129             if ( $record->{ $key } ) {
6130                 $sum_hash{ $key } += $record->{ $key };
6131             }
6132         }
6133
6134         put_record( $record, $out ) if not $options->{ "no_stream" };
6135     }
6136
6137     $fh = write_stream( $options->{ "data_out" } );
6138
6139     foreach $key ( @{ $options->{ "keys" } } ) {
6140         put_record( { $key . "_SUM" => $sum_hash{ $key } || 0 } , $fh );
6141     }
6142
6143     close $fh;
6144 }
6145
6146
6147 sub script_mean_vals
6148 {
6149     # Martin A. Hansen, August 2007.
6150
6151     # Calculate the mean of values of given keys.
6152
6153     my ( $in,        # handle to in stream
6154          $out,       # handle to out stream
6155          $options,   # options hash
6156        ) = @_;
6157
6158     # Returns nothing.
6159
6160     my ( $record, $key, %sum_hash, %count_hash, $mean, $fh );
6161
6162     while ( $record = get_record( $in ) ) 
6163     {
6164         foreach $key ( @{ $options->{ "keys" } } )
6165         {
6166             if ( $record->{ $key } )
6167             {
6168                 $sum_hash{ $key } += $record->{ $key };
6169                 $count_hash{ $key }++;
6170             }
6171         }
6172
6173         put_record( $record, $out ) if not $options->{ "no_stream" };
6174     }
6175
6176     $fh = write_stream( $options->{ "data_out" } );
6177
6178     foreach $key ( @{ $options->{ "keys" } } )
6179     {
6180         if ( $count_hash{ $key } ) {
6181             $mean = sprintf( "%.2f", ( $sum_hash{ $key } / $count_hash{ $key } ) );
6182         } else {
6183             $mean = "N/A";
6184         }
6185
6186         put_record( { $key . "_MEAN" => $mean } , $fh );
6187     }
6188
6189     close $fh;
6190 }
6191
6192
6193 sub script_median_vals
6194 {
6195     # Martin A. Hansen, March 2008.
6196
6197     # Calculate the median values of given keys.
6198
6199     my ( $in,        # handle to in stream
6200          $out,       # handle to out stream
6201          $options,   # options hash
6202        ) = @_;
6203
6204     # Returns nothing.
6205
6206     my ( $record, $key, %median_hash, $median, $fh );
6207
6208     while ( $record = get_record( $in ) ) 
6209     {
6210         foreach $key ( @{ $options->{ "keys" } } ) {
6211             push @{ $median_hash{ $key } }, $record->{ $key } if defined $record->{ $key };
6212         }
6213
6214         put_record( $record, $out ) if not $options->{ "no_stream" };
6215     }
6216
6217     $fh = write_stream( $options->{ "data_out" } );
6218
6219     foreach $key ( @{ $options->{ "keys" } } )
6220     {
6221         if ( $median_hash{ $key } ) {
6222             $median = Maasha::Calc::median( $median_hash{ $key } );
6223         } else {
6224             $median = "N/A";
6225         }
6226
6227         put_record( { $key . "_MEDIAN" => $median } , $fh );
6228     }
6229
6230     close $fh;
6231 }
6232
6233
6234 sub script_max_vals
6235 {
6236     # Martin A. Hansen, February 2008.
6237
6238     # Determine the maximum values of given keys.
6239
6240     my ( $in,        # handle to in stream
6241          $out,       # handle to out stream
6242          $options,   # options hash
6243        ) = @_;
6244
6245     # Returns nothing.
6246
6247     my ( $record, $key, $fh, %max_hash, $max_record );
6248
6249     while ( $record = get_record( $in ) ) 
6250     {
6251         foreach $key ( @{ $options->{ "keys" } } )
6252         {
6253             if ( $record->{ $key } )
6254             {
6255                 $max_hash{ $key } = $record->{ $key } if $record->{ $key } > $max_hash{ $key };
6256             }
6257         }
6258
6259         put_record( $record, $out ) if not $options->{ "no_stream" };
6260     }
6261
6262     $fh = write_stream( $options->{ "data_out" } );
6263
6264     foreach $key ( @{ $options->{ "keys" } } )
6265     {
6266         $max_record->{ $key . "_MAX" } = $max_hash{ $key };
6267     }
6268
6269     put_record( $max_record, $fh );
6270
6271     close $fh;
6272 }
6273
6274
6275 sub script_min_vals
6276 {
6277     # Martin A. Hansen, February 2008.
6278
6279     # Determine the minimum values of given keys.
6280
6281     my ( $in,        # handle to in stream
6282          $out,       # handle to out stream
6283          $options,   # options hash
6284        ) = @_;
6285
6286     # Returns nothing.
6287
6288     my ( $record, $key, $fh, %min_hash, $min_record );
6289
6290     while ( $record = get_record( $in ) ) 
6291     {
6292         foreach $key ( @{ $options->{ "keys" } } )
6293         {
6294             if ( defined $record->{ $key } )
6295             {
6296                 if ( exists $min_hash{ $key } ) {
6297                     $min_hash{ $key } = $record->{ $key } if $record->{ $key } < $min_hash{ $key };
6298                 } else {
6299                     $min_hash{ $key } = $record->{ $key }; 
6300                 }
6301             }
6302         }
6303
6304         put_record( $record, $out ) if not $options->{ "no_stream" };
6305     }
6306
6307     $fh = write_stream( $options->{ "data_out" } );
6308
6309     foreach $key ( @{ $options->{ "keys" } } )
6310     {
6311         $min_record->{ $key . "_MIN" } = $min_hash{ $key };
6312     }
6313
6314     put_record( $min_record, $fh );
6315
6316     close $fh;
6317 }
6318
6319
6320 sub script_upload_to_ucsc
6321 {
6322     # Martin A. Hansen, August 2007.
6323
6324     # Calculate the mean of values of given keys.
6325
6326     # This routine has developed into the most ugly hack. Do something!
6327
6328     my ( $in,        # handle to in stream
6329          $out,       # handle to out stream
6330          $options,   # options hash
6331        ) = @_;
6332
6333     # Returns nothing.
6334
6335     my ( $record, $file, $wib_file, $wig_file, $wib_dir, $fh_out, $i, $first, $format, $type, $columns, $append, $vals );
6336
6337     $options->{ "short_label" } ||= $options->{ 'table' };
6338     $options->{ "long_label" }  ||= $options->{ 'table' };
6339     $options->{ "group" }       ||= $ENV{ "LOGNAME" };
6340     $options->{ "priority" }    ||= 1;
6341     $options->{ "visibility" }  ||= "pack";
6342     $options->{ "color" }       ||= join( ",", int( rand( 255 ) ), int( rand( 255 ) ), int( rand( 255 ) ) );
6343     $options->{ "chunk_size" }  ||= 10_000_000_000;    # Due to 32-bit UCSC compilation really large tables cannot be loaded in one go.
6344
6345     $file = "$BP_TMP/ucsc_upload.tmp";
6346
6347     $append = 0;
6348
6349     $first = 1;
6350
6351     $i = 0;
6352
6353     $fh_out = Maasha::Common::write_open( $file );
6354
6355     while ( $record = get_record( $in ) ) 
6356     {
6357         put_record( $record, $out ) if not $options->{ "no_stream" };
6358
6359         if ( $record->{ "REC_TYPE" } eq "fixed_step" )
6360         {
6361             $vals = $record->{ "VALS" };
6362             $vals =~ tr/;/\n/;
6363
6364             print $fh_out "fixedStep chrom=$record->{ 'CHR' } start=$record->{ 'CHR_BEG' } step=$record->{ 'STEP' }\n";
6365             print $fh_out "$vals\n";
6366
6367             $format = "WIGGLE" if not $format;
6368         }
6369         elsif ( $record->{ "REC_TYPE" } eq "PSL" )
6370         {
6371             Maasha::UCSC::psl_put_header( $fh_out ) if $first;
6372             Maasha::UCSC::psl_put_entry( $record, $fh_out );
6373             
6374             $first = 0;
6375
6376             $format = "PSL" if not $format;
6377         }
6378         elsif ( $record->{ "REC_TYPE" } eq "BED" and $record->{ "SEC_STRUCT" } )
6379         {
6380             # chrom chromStart  chromEnd    name    score   strand  size    secStr  conf 
6381
6382             print $fh_out join ( "\t",
6383                 $record->{ "CHR" },
6384                 $record->{ "CHR_BEG" },
6385                 $record->{ "CHR_END" } + 1,
6386                 $record->{ "Q_ID" },
6387                 $record->{ "SCORE" },
6388                 $record->{ "STRAND" },
6389                 $record->{ "SIZE" },
6390                 $record->{ "SEC_STRUCT" },
6391                 $record->{ "CONF" },
6392             ), "\n";
6393
6394             $format  = "BED_SS" if not $format;
6395         }
6396         elsif ( $record->{ "REC_TYPE" } eq "BED" )
6397         {
6398             Maasha::UCSC::bed_put_entry( $record, $fh_out, $record->{ "BED_COLS" } );
6399
6400             $format  = "BED"                   if not $format;
6401             $columns = $record->{ "BED_COLS" } if not $columns;
6402         }
6403         elsif ( $record->{ "REC_TYPE" } eq "PATSCAN" and $record->{ "CHR" } )
6404         {
6405             Maasha::UCSC::bed_put_entry( $record, $fh_out, 6 );
6406
6407             $format  = "BED" if not $format;
6408             $columns = 6     if not $columns;
6409         }
6410         elsif ( $record->{ "REC_TYPE" } eq "BLAST" and $record->{ "S_ID" } =~ /^chr/ )
6411         {
6412             $record->{ "CHR" }     = $record->{ "S_ID" };
6413             $record->{ "CHR_BEG" } = $record->{ "S_BEG" };
6414             $record->{ "CHR_END" } = $record->{ "S_END" };
6415             $record->{ "SCORE" }   = $record->{ "BIT_SCORE" } * 1000;
6416
6417             $format  = "BED" if not $format;
6418             $columns = 6     if not $columns;
6419
6420             Maasha::UCSC::bed_put_entry( $record, $fh_out );
6421         }
6422         elsif ( $record->{ "REC_TYPE" } eq "VMATCH" and $record->{ "S_ID" } =~ /^chr/i )
6423         {
6424             $record->{ "CHR" }     = $record->{ "S_ID" };
6425             $record->{ "CHR_BEG" } = $record->{ "S_BEG" };
6426             $record->{ "CHR_END" } = $record->{ "S_END" };
6427             $record->{ "SCORE" }   = $record->{ "SCORE" } || 999;
6428             $record->{ "SCORE" }   = int( $record->{ "SCORE" } );
6429
6430             $format  = "BED" if not $format;
6431             $columns = 6     if not $columns;
6432
6433             Maasha::UCSC::bed_put_entry( $record, $fh_out, 6 );
6434         }
6435
6436         if ( $i == $options->{ "chunk_size" } )
6437         {
6438             close $fh_out;
6439
6440             if ( $format eq "BED" ) {
6441                 Maasha::UCSC::bed_upload_to_ucsc( $BP_TMP, $file, $options, $append );
6442             } elsif ( $format eq "PSL" ) {
6443                 Maasha::UCSC::psl_upload_to_ucsc( $file, $options, $append ); 
6444             }
6445
6446             unlink $file;
6447
6448             $first = 1;
6449
6450             $append = 1;
6451
6452             $fh_out = Maasha::Common::write_open( $file );
6453         }
6454
6455         $i++;
6456     }
6457
6458     close $fh_out;
6459
6460     if ( exists $options->{ "database" } and $options->{ "table" } )
6461     {
6462         if ( $format eq "BED" )
6463         {
6464             $type = "bed $columns";
6465
6466             Maasha::UCSC::bed_upload_to_ucsc( $BP_TMP, $file, $options, $append );
6467         }
6468         elsif ( $format eq "BED_SS" )
6469         {
6470             $options->{ "sec_struct" } = 1; 
6471
6472             $type = "sec_struct";
6473         
6474             Maasha::UCSC::bed_upload_to_ucsc( $BP_TMP, $file, $options, $append );
6475         }
6476         elsif ( $format eq "PSL" )
6477         {
6478             $type = "psl";
6479
6480             Maasha::UCSC::psl_upload_to_ucsc( $file, $options, $append ); 
6481         }
6482         elsif ( $format eq "WIGGLE" )
6483         {
6484             $options->{ "visibility" } = "full";
6485
6486             $wig_file = "$options->{ 'table' }.wig";
6487             $wib_file = "$options->{ 'table' }.wib";
6488
6489             $wib_dir  = "$ENV{ 'HOME' }/ucsc/wib";
6490
6491             Maasha::Common::dir_create_if_not_exists( $wib_dir );
6492
6493             if ( $options->{ 'verbose' } ) {
6494                 `cd $BP_TMP && wigEncode $file $wig_file $wib_file`;
6495             } else {
6496                 `cd $BP_TMP && wigEncode $file $wig_file $wib_file > /dev/null 2>&1`;
6497             }
6498
6499             Maasha::Common::run( "mv", "$BP_TMP/$wib_file $wib_dir" );
6500
6501             unlink $file;
6502
6503             $file = $wig_file;
6504
6505             $type = "wig 0";
6506
6507             Maasha::UCSC::wiggle_upload_to_ucsc( $BP_TMP, $wib_dir, $file, $options );
6508         }
6509
6510         unlink $file;
6511
6512         Maasha::UCSC::update_my_tracks( $options, $type );
6513     }
6514 }
6515
6516
6517 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
6518
6519
6520 sub grab_lookup
6521 {
6522     # Martin A. Hansen, November 2009.
6523
6524     # Uses keys from a lookup hash to search records. Optionally, a list of
6525     # keys can be given so the lookup is limited to these, also, flags
6526     # can be given to limit lookup to keys or vals only. Returns 1 if lookup
6527     # succeeded, else 0.
6528
6529     my ( $lookup_hash,   # hashref with patterns
6530          $record,        # hashref
6531          $keys,          # list of keys   - OPTIONAL
6532          $vals_only,     # only vals flag - OPTIONAL
6533          $keys_only,     # only keys flag - OPTIONAL
6534        ) = @_;
6535
6536     # Returns boolean.
6537
6538     if ( $keys )
6539     {
6540         map { return 1 if exists $lookup_hash->{ $record->{ $_ } } } @{ $keys };
6541     }
6542     else
6543     {
6544         if ( not $vals_only ) {
6545             map { return 1 if exists $lookup_hash->{ $_ } } keys %{ $record };
6546         }
6547
6548         if ( not $keys_only ) {
6549             map { return 1 if exists $lookup_hash->{ $record->{ $_ } } } keys %{ $record };
6550         }
6551     }
6552
6553     return 0;
6554 }
6555
6556
6557 sub grab_patterns
6558 {
6559     # Martin A. Hansen, November 2009.
6560
6561     # Uses patterns to match records containing the pattern as a substring.
6562     # Returns 1 if the record is matched, else 0.
6563
6564     my ( $patterns,   # list of patterns
6565          $record,     # hashref
6566          $keys,       # list of keys   - OPTIONAL
6567          $vals_only,  # only vals flag - OPTIONAL
6568          $keys_only,  # only keys flag - OPTIONAL
6569        ) = @_;
6570
6571     # Returns boolean.
6572
6573     my ( $pattern );
6574
6575     foreach $pattern ( @{ $patterns } )
6576     {
6577         if ( $keys )
6578         {
6579             map { return 1 if index( $record->{ $_ }, $pattern ) >= 0 } @{ $keys };
6580         }
6581         else
6582         {
6583             if ( not $vals_only ) {
6584                 map { return 1 if index( $_, $pattern ) >= 0 } keys %{ $record };
6585             }
6586
6587             if ( not $keys_only ) {
6588                 map { return 1 if index( $record->{ $_ }, $pattern ) >= 0 } keys %{ $record };
6589             }
6590         }
6591     }
6592
6593     return 0;
6594 }
6595
6596
6597 sub grab_regex
6598 {
6599     # Martin A. Hansen, November 2009.
6600
6601     # Uses regex to match records.
6602     # Returns 1 if the record is matched, else 0.
6603
6604     my ( $regex,      # regex to match
6605          $record,     # hashref
6606          $keys,       # list of keys   - OPTIONAL
6607          $vals_only,  # only vals flag - OPTIONAL
6608          $keys_only,  # only keys flag - OPTIONAL
6609        ) = @_;
6610
6611     # Returns boolean.
6612
6613     if ( $keys )
6614     {
6615         map { return 1 if $record->{ $_ } =~ /$regex/ } @{ $keys };
6616     }
6617     else
6618     {
6619         if ( not $vals_only ) {
6620             map { return 1 if $_ =~ /$regex/ } keys %{ $record };
6621         }
6622
6623         if ( not $keys_only ) {
6624             map { return 1 if $record->{ $_ } =~ /$regex/ } keys %{ $record };
6625         }
6626     }
6627
6628     return 0;
6629 }
6630
6631
6632 sub grab_eval
6633 {
6634     # Martin A. Hansen, November 2009.
6635
6636     # Test if the value of a given record key evaluates according
6637     # to a given operator. Returns 1 if eval is OK, else 0.
6638
6639     my ( $key,     # record key
6640          $op,      # operator
6641          $val,     # value
6642          $record,  # hashref
6643        ) = @_;
6644     
6645     # Returns boolean.
6646
6647     if ( defined $record->{ $key } ) 
6648     {
6649         return 1 if ( $op eq "<" and $record->{ $key } < $val );
6650         return 1 if ( $op eq ">" and $record->{ $key } > $val );
6651         return 1 if ( $op eq ">=" and $record->{ $key } >= $val );
6652         return 1 if ( $op eq "<=" and $record->{ $key } <= $val );
6653         return 1 if ( $op eq "=" and $record->{ $key } == $val );
6654         return 1 if ( $op eq "!=" and $record->{ $key } != $val );
6655         return 1 if ( $op eq "eq" and $record->{ $key } eq $val );
6656         return 1 if ( $op eq "ne" and $record->{ $key } ne $val );
6657     }
6658
6659     return 0;
6660 }
6661
6662
6663 sub record2fasta
6664 {
6665     # Martin A. Hansen, July 2008.
6666
6667     # Given a biopiece record converts it to a FASTA record.
6668     # If no generic SEQ or SEQ_NAME is found, the Q_* and S_* are
6669     # tried in that order.
6670
6671     my ( $record,    # record
6672        ) = @_;
6673
6674     # Returns a tuple.
6675
6676     my ( $seq_name, $seq );
6677
6678     $seq_name = $record->{ "SEQ_NAME" } || $record->{ "Q_ID" }  || $record->{ "S_ID" };
6679     $seq      = $record->{ "SEQ" }      || $record->{ "Q_SEQ" } || $record->{ "S_SEQ" };
6680
6681     if ( defined $seq_name and defined $seq ) {
6682         return wantarray ? ( $seq_name, $seq ) : [ $seq_name, $seq ];
6683     } else {
6684         return;
6685     }
6686 }
6687
6688
6689 sub read_stream
6690 {
6691     # Martin A. Hansen, July 2007.
6692
6693     # Opens a stream to STDIN or a file,
6694
6695     my ( $path,   # path - OPTIONAL
6696        ) = @_;
6697
6698     # Returns filehandle.
6699
6700     my ( $fh );
6701
6702     if ( not -t STDIN ) {
6703         $fh = Maasha::Common::read_stdin();
6704     } elsif ( not $path ) {
6705 #        Maasha::Common::error( qq(no data stream) );
6706     } else {
6707         $fh = Maasha::Common::read_open( $path );
6708     }
6709     
6710 #    $fh->autoflush(1) if $fh;  # Disable file buffer for debugging.
6711
6712     return $fh;
6713 }
6714
6715
6716 sub write_stream
6717 {
6718     # Martin A. Hansen, August 2007.
6719
6720     # Opens a stream to STDOUT or a file.
6721
6722     my ( $path,   # path          - OPTIONAL
6723          $gzip,   # compress data - OPTIONAL
6724        ) = @_;
6725
6726     # Returns filehandle.
6727
6728     my ( $fh );
6729
6730     if ( $path ) {
6731         $fh = Maasha::Common::write_open( $path, $gzip );
6732     } else {
6733         $fh = Maasha::Common::write_stdout();
6734     }
6735
6736     return $fh;
6737 }
6738
6739
6740 sub get_record
6741 {
6742     # Martin A. Hansen, July 2007.
6743
6744     # Reads one record at a time and converts that record
6745     # to a Perl data structure (a hash) which is returned.
6746
6747     my ( $fh,   # handle to stream
6748        ) = @_;
6749
6750     # Returns a hash. 
6751
6752     my ( $block, @lines, $line, $key, $value, %record );
6753
6754     local $/ = "\n---\n";
6755
6756     $block = <$fh>;
6757
6758     chomp $block;
6759
6760     return if not defined $block;
6761
6762     @lines = split "\n", $block;
6763
6764     foreach $line ( @lines )
6765     {
6766         ( $key, $value ) = split ": ", $line, 2;
6767
6768         $record{ $key } = $value;
6769     }
6770
6771     return wantarray ? %record : \%record;
6772 }
6773
6774
6775 sub put_record
6776 {
6777     # Martin A. Hansen, July 2007.
6778
6779     # Given a Perl datastructure (a hash ref) emits this to STDOUT or a filehandle.
6780
6781     my ( $data,   # data structure
6782          $fh,     # file handle - OPTIONAL
6783        ) = @_;
6784
6785     # Returns nothing.
6786
6787     if ( scalar keys %{ $data } )
6788     {
6789         if ( $fh )
6790         {
6791             map { print $fh "$_: $data->{ $_ }\n" } keys %{ $data };
6792             print $fh "---\n";
6793         }
6794         else
6795         {
6796             map { print "$_: $data->{ $_ }\n" } keys %{ $data };
6797             print "---\n";
6798         }
6799     }
6800
6801     undef $data;
6802 }
6803
6804
6805 sub getopt_files
6806 {
6807     # Martin A. Hansen, November 2007.
6808
6809     # Extracts files from an explicit GetOpt::Long argument
6810     # allowing for the use of glob. E.g.
6811     # --data_in=test.fna
6812     # --data_in=test.fna,test2.fna
6813     # --data_in=*.fna
6814     # --data_in=test.fna,/dir/*.fna
6815
6816     my ( $option,   # option from GetOpt::Long
6817        ) = @_;
6818
6819     # Returns a list.
6820
6821     my ( $elem, @files );
6822
6823     foreach $elem ( split ",", $option )
6824     {
6825         if ( -f $elem ) {
6826             push @files, $elem;
6827         } elsif ( $elem =~ /\*/ ) {
6828             push @files, glob( $elem );
6829         }
6830     }
6831
6832     return wantarray ? @files : \@files;
6833 }
6834
6835
6836 sub sig_handler
6837 {
6838     # Martin A. Hansen, April 2008.
6839
6840     # Removes temporary directory and exits gracefully.
6841     # This subroutine is meant to be run always as the last
6842     # thing even if a script is dies or is interrupted
6843     # or killed. 
6844
6845     my ( $sig,   # signal from the %SIG
6846        ) = @_;
6847
6848     # print STDERR "signal->$sig<-\n";
6849
6850     chomp $sig;
6851
6852     sleep 1;
6853
6854     if ( -d $BP_TMP )
6855     {
6856         if ( $sig =~ /MAASHA_ERROR/ ) {
6857             print STDERR "\nProgram '$script' had an error"                     . "  -  Please wait for temporary data to be removed\n";
6858         } elsif ( $sig eq "INT" ) {
6859             print STDERR "\nProgram '$script' interrupted (ctrl-c was pressed)" . "  -  Please wait for temporary data to be removed\n";
6860         } elsif ( $sig eq "TERM" ) {
6861             print STDERR "\nProgram '$script' terminated (someone used kill?)"  . "  -  Please wait for temporary data to be removed\n";
6862         } else {
6863             print STDERR "\nProgram '$script' died->$sig"                       . "  -  Please wait for temporary data to be removed\n";
6864         }
6865
6866         clean_tmp();
6867     }
6868
6869     exit( 0 );
6870 }
6871
6872
6873 sub clean_tmp
6874 {
6875     # Martin A. Hansen, July 2008.
6876
6877     # Cleans out any unused temporary files and directories in BP_TMP.
6878
6879     # Returns nothing.
6880
6881     my ( $tmpdir, @dirs, $curr_pid, $dir, $user, $sid, $pid );
6882
6883     $tmpdir = $ENV{ 'BP_TMP' } || Maasha::Common::error( 'No BP_TMP variable in environment.' );
6884
6885     $curr_pid = Maasha::Common::get_processid();
6886
6887     @dirs = Maasha::Common::ls_dirs( $tmpdir );
6888
6889     foreach $dir ( @dirs )
6890     {
6891         if ( $dir =~ /^$tmpdir\/(.+)_(\d+)_(\d+)_bp_tmp$/ )
6892         {
6893             $user = $1;
6894             $sid  = $2;
6895             $pid  = $3;
6896
6897             if ( $user eq Maasha::Common::get_user() )
6898             {
6899                 if ( not Maasha::Common::process_running( $pid ) )
6900                 {
6901                     # print STDERR "Removing stale dir: $dir\n";
6902                     Maasha::Common::dir_remove( $dir );
6903                 }
6904                 elsif ( $pid == $curr_pid )
6905                 {
6906                     # print STDERR "Removing current dir: $dir\n";
6907                     # Maasha::Common::dir_remove( $dir );
6908                 }
6909             }
6910         }
6911     }
6912 }
6913
6914
6915 END
6916 {
6917     clean_tmp();
6918 }
6919
6920
6921 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
6922
6923 1;
6924
6925 __END__