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