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