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