]> git.donarmstrong.com Git - biopieces.git/blob - code_perl/Maasha/Biopieces.pm
cbd0e1f16b531913d385b88fa1282a8ee7ec646c
[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, 1 ) )
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, $tag_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 6 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, 1 );
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 = $file_hash->{ $chr };
2204         $tag_file = "$bed_file.tc";
2205
2206         Maasha::Common::run( "bed2tag_contigs", "< $bed_file > $tag_file" );
2207
2208         $fh_in = Maasha::Filesys::file_read_open( $tag_file );
2209
2210         while ( $bed_entry = Maasha::UCSC::BED::bed_entry_get( $fh_in, $cols ) )
2211         {
2212             if ( $record = Maasha::UCSC::BED::bed2biopiece( $bed_entry ) ) {
2213                 put_record( $record, $out );
2214             }
2215         }
2216
2217         close $fh_in;
2218
2219         unlink $bed_file;
2220         unlink $tag_file;
2221     }
2222 }
2223
2224
2225 sub script_format_genome
2226 {
2227     # Martin A. Hansen, Juli 2008.
2228
2229     # Format a genome to speficed formats.
2230
2231     my ( $in,        # handle to in stream
2232          $out,       # handle to out stream
2233          $options,   # options hash
2234        ) = @_;
2235
2236     # Returns nothing.
2237
2238     my ( $dir, $genome, $fasta_dir, $phastcons_dir, $vals, $fh_out, $record, $format, $index, $entry );
2239
2240     $dir    = $options->{ 'dir' } || $ENV{ 'BP_DATA' };
2241     $genome = $options->{ 'genome' };
2242
2243     Maasha::Common::error( "Directory: $dir does not exist" ) if not -d $dir;
2244     Maasha::Common::dir_create_if_not_exists( "$dir/genomes" );
2245     Maasha::Common::dir_create_if_not_exists( "$dir/genomes/$genome" );
2246
2247     if ( grep { $_ =~ /fasta|blast|vmatch/i } @{ $options->{ "formats" } } )
2248     {
2249         if ( -f "$dir/genomes/$genome/fasta/$genome.fna" )
2250         {
2251             $fasta_dir = "$dir/genomes/$genome/fasta";
2252         }
2253         else
2254         {
2255             Maasha::Common::dir_create_if_not_exists( "$dir/genomes/$genome/fasta" );
2256
2257             $fasta_dir = "$dir/genomes/$genome/fasta";
2258
2259             $fh_out = Maasha::Common::write_open( "$fasta_dir/$genome.fna" );
2260         }
2261     }
2262     elsif ( grep { $_ =~ /phastcons/i } @{ $options->{ "formats" } } )
2263     {
2264         Maasha::Common::dir_create_if_not_exists( "$dir/genomes/$genome/phastcons" );
2265     
2266         $phastcons_dir = "$dir/genomes/$genome/phastcons";
2267
2268         $fh_out = Maasha::Common::write_open( "$phastcons_dir/$genome.pp" );
2269     }
2270
2271     while ( $record = get_record( $in ) ) 
2272     {
2273         if ( $fh_out and $entry = Maasha::Fasta::biopiece2fasta( $record ) )
2274         {
2275             Maasha::Fasta::put_entry( $entry, $fh_out, $options->{ "wrap" } );
2276         }
2277         elsif ( $fh_out and $record->{ "CHR" } and $record->{ "CHR_BEG" } and $record->{ "STEP" } and $record->{ "VALS" } )
2278         {
2279             print $fh_out "fixedStep chrom=$record->{ 'CHR' } start=$record->{ 'CHR_BEG' } step=$record->{ 'STEP' }\n";
2280
2281             $vals = $record->{ 'VALS' };
2282
2283             $vals =~ tr/,/\n/;
2284
2285             print $fh_out "$vals\n";
2286         }
2287
2288         put_record( $record, $out ) if not $options->{ "no_stream" };
2289     }
2290
2291     foreach $format ( @{ $options->{ 'formats' } } )
2292     {
2293         if    ( $format =~ /^fasta$/i )     { Maasha::Fasta::fasta_index( "$fasta_dir/$genome.fna", "$dir/genomes/$genome/fasta/$genome.index" ) }
2294         elsif ( $format =~ /^blast$/i )     { Maasha::NCBI::blast_index( "$genome.fna", $fasta_dir, "$dir/genomes/$genome/blast", "dna", $genome ) }
2295         elsif ( $format =~ /^blat$/i )      { print STDERR "BLAT FORMAT NOT IMPLEMENTED" }
2296         elsif ( $format =~ /^vmatch$/i )    { Maasha::Match::vmatch_index( "$genome.fna", $fasta_dir, "$dir/genomes/$genome/vmatch", $BP_TMP ) }
2297         elsif ( $format =~ /^phastcons$/i ) { Maasha::UCSC::phastcons_index( "$genome.pp", $phastcons_dir ) }
2298     }
2299
2300     close $fh_out if $fh_out;
2301 }
2302
2303
2304 sub script_length_seq
2305 {
2306     # Martin A. Hansen, August 2007.
2307
2308     # Determine the length of sequences in stream.
2309
2310     my ( $in,        # handle to in stream
2311          $out,       # handle to out stream
2312          $options,   # options hash
2313        ) = @_;
2314
2315     # Returns nothing.
2316
2317     my ( $record, $total );
2318
2319     while ( $record = get_record( $in ) ) 
2320     {
2321         if ( $record->{ "SEQ" } )
2322         {
2323             $record->{ "SEQ_LEN" } = length $record->{ "SEQ" };
2324             $total += $record->{ "SEQ_LEN" };
2325         }
2326
2327         put_record( $record, $out ) if not $options->{ "no_stream" };
2328     }
2329
2330     put_record( { TOTAL_SEQ_LEN => $total }, $out );
2331 }
2332
2333
2334 sub script_uppercase_seq
2335 {
2336     # Martin A. Hansen, August 2007.
2337
2338     # Uppercases sequences in stream.
2339
2340     my ( $in,    # handle to in stream
2341          $out,   # handle to out stream
2342        ) = @_;
2343
2344     # Returns nothing.
2345
2346     my ( $record );
2347
2348     while ( $record = get_record( $in ) ) 
2349     {
2350         $record->{ "SEQ" } = uc $record->{ "SEQ" } if $record->{ "SEQ" };
2351
2352         put_record( $record, $out );
2353     }
2354 }
2355
2356
2357 sub script_shuffle_seq
2358 {
2359     # Martin A. Hansen, December 2007.
2360
2361     # Shuffle sequences in stream.
2362
2363     my ( $in,    # handle to in stream
2364          $out,   # handle to out stream
2365        ) = @_;
2366
2367     # Returns nothing.
2368
2369     my ( $record );
2370
2371     while ( $record = get_record( $in ) ) 
2372     {
2373         $record->{ "SEQ" } = Maasha::Seq::seq_shuffle( $record->{ "SEQ" } ) if $record->{ "SEQ" };
2374
2375         put_record( $record, $out );
2376     }
2377 }
2378
2379
2380 sub script_analyze_seq
2381 {
2382     # Martin A. Hansen, August 2007.
2383
2384     # Analyze sequence composition of sequences in stream.
2385
2386     my ( $in,     # handle to in stream
2387          $out,    # handle to out stream
2388        ) = @_;
2389
2390     # Returns nothing.
2391
2392     my ( $record, $analysis );
2393
2394     while ( $record = get_record( $in ) ) 
2395     {
2396         if ( $record->{ "SEQ" } )
2397         {
2398             $analysis = Maasha::Seq::seq_analyze( $record->{ "SEQ" } );
2399
2400             map { $record->{ $_ } = $analysis->{ $_ } } keys %{ $analysis };
2401         }
2402
2403         put_record( $record, $out );
2404     }
2405 }
2406
2407
2408 sub script_analyze_tags
2409 {
2410     # Martin A. Hansen, August 2008.
2411
2412     # Analyze sequence tags in stream.
2413
2414     my ( $in,     # handle to in stream
2415          $out,    # handle to out stream
2416        ) = @_;
2417
2418     # Returns nothing.
2419
2420     my ( $record, $analysis, %len_hash, %clone_hash, $clones, $key, $tag_record );
2421
2422     while ( $record = get_record( $in ) ) 
2423     {
2424         if ( $record->{ "SEQ_NAME" } and $record->{ "SEQ" } )
2425         {
2426             if ( $record->{ "SEQ_NAME" } =~ /_(\d+)$/ )
2427             {
2428                 $clones = $1;
2429
2430                 $len_hash{ length( $record->{ "SEQ" } ) }++;
2431                 $clone_hash{ length( $record->{ "SEQ" } ) } += $clones;
2432             }
2433         }
2434         elsif ( $record->{ "Q_ID" } and $record->{ "BED_LEN" } )
2435         {
2436             if ( $record->{ "Q_ID" } =~ /_(\d+)$/ )
2437             {
2438                 $clones = $1;
2439
2440                 $len_hash{ $record->{ "BED_LEN" } }++;
2441                 $clone_hash{ $record->{ "BED_LEN" } } += $clones;
2442             }
2443         }
2444     }
2445
2446     foreach $key ( sort { $a <=> $b } keys %len_hash )
2447     {
2448         $tag_record->{ "TAG_LEN" }    = $key;
2449         $tag_record->{ "TAG_COUNT" }  = $len_hash{ $key };
2450         $tag_record->{ "TAG_CLONES" } = $clone_hash{ $key };
2451  
2452         put_record( $tag_record, $out );
2453     }
2454 }
2455
2456
2457 sub script_complexity_seq
2458 {
2459     # Martin A. Hansen, May 2008.
2460
2461     # Generates an index calculated as the most common di-residue over
2462     # the sequence length for all sequences in stream.
2463
2464     my ( $in,     # handle to in stream
2465          $out,    # handle to out stream
2466        ) = @_;
2467
2468     # Returns nothing.
2469
2470     my ( $record, $index );
2471
2472     while ( $record = get_record( $in ) ) 
2473     {
2474         $record->{ "SEQ_COMPLEXITY" } = sprintf( "%.2f", Maasha::Seq::seq_complexity( $record->{ "SEQ" } ) ) if $record->{ "SEQ" };
2475
2476         put_record( $record, $out );
2477     }
2478 }
2479
2480
2481 sub script_oligo_freq
2482 {
2483     # Martin A. Hansen, August 2007.
2484
2485     # Determine the length of sequences in stream.
2486
2487     my ( $in,        # handle to in stream
2488          $out,       # handle to out stream
2489          $options,   # options hash
2490        ) = @_;
2491
2492     # Returns nothing.
2493
2494     my ( $record, %oligos, @freq_table );
2495
2496     $options->{ "word_size" } ||= 7;
2497
2498     while ( $record = get_record( $in ) ) 
2499     {
2500         if ( $record->{ "SEQ" } )
2501         {
2502             map { $oligos{ $_ }++ } Maasha::Seq::seq2oligos( \$record->{ "SEQ" }, $options->{ "word_size" } );
2503
2504             if ( not $options->{ "all" } )
2505             {
2506                 @freq_table = Maasha::Seq::oligo_freq( \%oligos );
2507
2508                 map { put_record( $_, $out ) } @freq_table;
2509             
2510                 undef %oligos;
2511             }
2512         }
2513
2514         put_record( $record, $out );
2515     }
2516
2517     if ( $options->{ "all" } )
2518     {
2519         @freq_table = Maasha::Seq::oligo_freq( \%oligos );
2520
2521         map { put_record( $_, $out ) } @freq_table;
2522     }
2523 }
2524
2525
2526 sub script_create_weight_matrix
2527 {
2528     # Martin A. Hansen, August 2007.
2529
2530     # Creates a weight matrix from an alignmnet.
2531
2532     my ( $in,        # handle to in stream
2533          $out,       # handle to out stream
2534          $options,   # options hash
2535        ) = @_;
2536
2537     # Returns nothing.
2538
2539     my ( $record, $count, $i, $res, %freq_hash, %res_hash, $freq );
2540
2541     $count = 0;
2542     
2543     while ( $record = get_record( $in ) ) 
2544     {
2545         if ( $record->{ "SEQ" } )
2546         {
2547             for ( $i = 0; $i < length $record->{ "SEQ" }; $i++ )
2548             {
2549                 $res = substr $record->{ "SEQ" }, $i, 1;
2550
2551                 $freq_hash{ $i }{ $res }++;
2552                 $res_hash{ $res } = 1;
2553             }
2554
2555             $count++;
2556         }
2557         else
2558         {
2559             put_record( $record, $out );
2560         }
2561     }
2562
2563     foreach $res ( sort keys %res_hash )
2564     {
2565         undef $record;
2566
2567         $record->{ "V0" } = $res;
2568
2569         for ( $i = 0; $i < keys %freq_hash; $i++ )
2570         {
2571             $freq = $freq_hash{ $i }{ $res } || 0;
2572
2573             if ( $options->{ "percent" } ) {
2574                 $freq = sprintf( "%.0f", 100 * $freq / $count ) if $freq > 0;
2575             }
2576
2577             $record->{ "V" . ( $i + 1 ) } = $freq;
2578         }
2579
2580         put_record( $record, $out );
2581     }
2582 }
2583
2584
2585 sub script_calc_bit_scores
2586 {
2587     # Martin A. Hansen, March 2007.
2588
2589     # Calculates the bit scores for each position from an alignmnet in the stream.
2590
2591     my ( $in,        # handle to in stream
2592          $out,       # handle to out stream
2593        ) = @_;
2594
2595     # Returns nothing.
2596
2597     my ( $record, $type, $count, $i, $res, %freq_hash, $bit_max, $bit_height, $bit_diff );
2598
2599     $count = 0;
2600
2601     while ( $record = get_record( $in ) ) 
2602     {
2603         if ( $record->{ "SEQ" } )
2604         {
2605             $type = Maasha::Seq::seq_guess_type( $record->{ "SEQ" } ) if not $type;
2606
2607             for ( $i = 0; $i < length $record->{ "SEQ" }; $i++ )
2608             {
2609                 $res = substr $record->{ "SEQ" }, $i, 1;
2610
2611                 next if $res =~ /-|_|~|\./;
2612
2613                 $freq_hash{ $i }{ $res }++;
2614             }
2615
2616             $count++;
2617         }
2618         else
2619         {
2620             put_record( $record, $out );
2621         }
2622     }
2623
2624     undef $record;
2625
2626     if ( $type eq "protein" ) {
2627         $bit_max = 4;
2628     } else {
2629         $bit_max = 2;
2630     }
2631
2632     for ( $i = 0; $i < keys %freq_hash; $i++ )
2633     {
2634         $bit_height = Maasha::Seq::seqlogo_calc_bit_height( $freq_hash{ $i }, $count );
2635
2636         $bit_diff = $bit_max - $bit_height;
2637
2638         $record->{ "V" . ( $i ) } = sprintf( "%.2f", $bit_diff );
2639     }
2640
2641     put_record( $record, $out );
2642 }
2643
2644
2645 sub script_calc_fixedstep
2646 {
2647     # Martin A. Hansen, September 2008.
2648
2649     # Calculates fixedstep entries from data in the stream.
2650
2651     my ( $in,        # handle to in stream
2652          $out,       # handle to out stream
2653          $options,   # options hash
2654        ) = @_;
2655
2656     # Returns nothing.
2657
2658     my ( $bed_file, $fh_in, $fh_out, $cols, $record, $file_hash, $chr, $bed_entry, $fixedstep_file, $fixedstep_entry );
2659
2660     $bed_file = "$BP_TMP/calc_fixedstep.bed";
2661     $fh_out   = Maasha::Filesys::file_write_open( $bed_file );
2662     $cols     = 5; # we only need the first 5 BED columns
2663
2664     while ( $record = get_record( $in ) ) 
2665     {
2666         if ( $bed_entry = Maasha::UCSC::BED::biopiece2bed( $record, $cols ) ) {
2667             Maasha::UCSC::BED::bed_entry_put( $bed_entry, $fh_out, $cols, 1 );
2668         }
2669     }
2670
2671     close $fh_out;
2672
2673     $file_hash = Maasha::UCSC::BED::bed_file_split_on_chr( $bed_file, $BP_TMP, $cols );
2674
2675     unlink $bed_file;
2676
2677     foreach $chr ( sort keys %{ $file_hash } )
2678     {
2679         $bed_file       = $file_hash->{ $chr };
2680         $fixedstep_file = "$bed_file.fixedstep";
2681         
2682         Maasha::Common::run( "bed2fixedstep", "< $bed_file > $fixedstep_file" );
2683
2684         $fh_in = Maasha::Filesys::file_read_open( $fixedstep_file );
2685
2686         while ( $fixedstep_entry = Maasha::UCSC::Wiggle::fixedstep_entry_get( $fh_in ) )
2687         {
2688             if ( $record = Maasha::UCSC::Wiggle::fixedstep2biopiece( $fixedstep_entry ) ) {
2689                 put_record( $record, $out );
2690             }
2691         }
2692
2693         close $fh_in;
2694
2695         unlink $bed_file;
2696         unlink $fixedstep_file;
2697     }
2698 }
2699
2700
2701 sub script_reverse_seq
2702 {
2703     # Martin A. Hansen, August 2007.
2704
2705     # Reverse sequence in record.
2706
2707     my ( $in,    # handle to in stream
2708          $out,   # handle to out stream
2709        ) = @_;
2710
2711     # Returns nothing.
2712
2713     my ( $record );
2714
2715     while ( $record = get_record( $in ) ) 
2716     {
2717         if ( $record->{ "SEQ" } ) {
2718             $record->{ "SEQ" } = reverse $record->{ "SEQ" };
2719         }
2720
2721         put_record( $record, $out );
2722     }
2723 }
2724
2725
2726 sub script_complement_seq
2727 {
2728     # Martin A. Hansen, August 2007.
2729
2730     # Complement sequence in record.
2731
2732     my ( $in,     # handle to in stream
2733          $out,    # handle to out stream
2734        ) = @_;
2735
2736     # Returns nothing.
2737
2738     my ( $record, $type );
2739
2740     while ( $record = get_record( $in ) ) 
2741     {
2742         if ( $record->{ "SEQ" } )
2743         {
2744             if ( not $type ) {
2745                 $type = Maasha::Seq::seq_guess_type( $record->{ "SEQ" } );
2746             }
2747             
2748             if ( $type eq "rna" ) {
2749                 Maasha::Seq::rna_comp( \$record->{ "SEQ" } );
2750             } elsif ( $type eq "dna" ) {
2751                 Maasha::Seq::dna_comp( \$record->{ "SEQ" } );
2752             }
2753         }
2754
2755         put_record( $record, $out );
2756     }
2757 }
2758
2759
2760 sub script_remove_indels
2761 {
2762     # Martin A. Hansen, August 2007.
2763
2764     # Remove indels from sequences in stream.
2765
2766     my ( $in,     # handle to in stream
2767          $out,    # handle to out stream
2768        ) = @_;
2769
2770     # Returns nothing.
2771
2772     my ( $record );
2773
2774     while ( $record = get_record( $in ) ) 
2775     {
2776         $record->{ 'SEQ' } =~ tr/-~.//d if $record->{ "SEQ" };
2777
2778         put_record( $record, $out );
2779     }
2780 }
2781
2782
2783 sub script_transliterate_seq
2784 {
2785     # Martin A. Hansen, August 2007.
2786
2787     # Transliterate chars from sequence in record.
2788
2789     my ( $in,        # handle to in stream
2790          $out,       # handle to out stream
2791          $options,   # options hash
2792        ) = @_;
2793
2794     # Returns nothing.
2795
2796     my ( $record, $search, $replace, $delete );
2797
2798     $search  = $options->{ "search" }  || "";
2799     $replace = $options->{ "replace" } || "";
2800     $delete  = $options->{ "delete" }  || "";
2801
2802     while ( $record = get_record( $in ) ) 
2803     {
2804         if ( $record->{ "SEQ" } )
2805         {
2806             if ( $search and $replace ) {
2807                 eval "\$record->{ 'SEQ' } =~ tr/$search/$replace/";
2808             } elsif ( $delete ) {
2809                 eval "\$record->{ 'SEQ' } =~ tr/$delete//d";
2810             }
2811         }
2812
2813         put_record( $record, $out );
2814     }
2815 }
2816
2817
2818 sub script_transliterate_vals
2819 {
2820     # Martin A. Hansen, April 2008.
2821
2822     # Transliterate chars from values in record.
2823
2824     my ( $in,        # handle to in stream
2825          $out,       # handle to out stream
2826          $options,   # options hash
2827        ) = @_;
2828
2829     # Returns nothing.
2830
2831     my ( $record, $search, $replace, $delete, $key );
2832
2833     $search  = $options->{ "search" }  || "";
2834     $replace = $options->{ "replace" } || "";
2835     $delete  = $options->{ "delete" }  || "";
2836
2837     while ( $record = get_record( $in ) ) 
2838     {
2839         foreach $key ( @{ $options->{ "keys" } } )
2840         {
2841             if ( exists $record->{ $key } )
2842             {
2843                 if ( $search and $replace ) {
2844                     eval "\$record->{ $key } =~ tr/$search/$replace/";
2845                 } elsif ( $delete ) {
2846                     eval "\$record->{ $key } =~ tr/$delete//d";
2847                 }
2848             }
2849         }
2850
2851         put_record( $record, $out );
2852     }
2853 }
2854
2855
2856 sub script_translate_seq
2857 {
2858     # Martin A. Hansen, February 2008.
2859
2860     # Translate DNA sequence into protein sequence.
2861
2862     my ( $in,        # handle to in stream
2863          $out,       # handle to out stream
2864          $options,   # options hash
2865        ) = @_;
2866
2867     # Returns nothing.
2868
2869     my ( $record, $frame, %new_record );
2870
2871     $options->{ "frames" } ||= [ 1, 2, 3, -1, -2, -3 ];
2872
2873     while ( $record = get_record( $in ) ) 
2874     {
2875         if ( $record->{ "SEQ" } )
2876         {
2877             if ( Maasha::Seq::seq_guess_type( $record->{ "SEQ" } ) eq "dna" )
2878             {
2879                 foreach $frame ( @{ $options->{ "frames" } } )
2880                 {
2881                     %new_record = %{ $record };
2882
2883                     $new_record{ "SEQ" }     = Maasha::Seq::translate( $record->{ "SEQ" }, $frame );
2884                     $new_record{ "SEQ_LEN" } = length $new_record{ "SEQ" };
2885                     $new_record{ "FRAME" }   = $frame;
2886
2887                     put_record( \%new_record, $out );
2888                 }
2889             }
2890         }
2891         else
2892         {
2893             put_record( $record, $out );
2894         }
2895     }
2896 }
2897
2898
2899 sub script_extract_seq
2900 {
2901     # Martin A. Hansen, August 2007.
2902
2903     # Extract subsequences from sequences in record.
2904
2905     my ( $in,        # handle to in stream
2906          $out,       # handle to out stream
2907          $options,   # options hash
2908        ) = @_;
2909
2910     # Returns nothing.
2911
2912     my ( $beg, $end, $len, $record );
2913
2914     if ( not defined $options->{ "beg" } or $options->{ "beg" } < 0 ) {
2915         $beg = 0;
2916     } else {
2917         $beg = $options->{ "beg" } - 1;   # correcting for start offset
2918     }
2919
2920     if ( defined $options->{ "end" } and $options->{ "end" } - 1 < $beg ) {
2921         $end = $beg - 1;
2922     } elsif ( defined $options->{ "end" } ) {
2923         $end = $options->{ "end" } - 1;   # correcting for start offset
2924     }
2925
2926     $len = $options->{ "len" };
2927
2928 #    print "beg->$beg,  end->$end,  len->$len\n";
2929
2930     while ( $record = get_record( $in ) ) 
2931     {
2932         if ( $record->{ "SEQ" } )
2933         {
2934             if ( defined $beg and defined $end )
2935             {
2936                 if ( $end - $beg + 1 > length $record->{ "SEQ" } ) {
2937                     $record->{ "SEQ" } = substr $record->{ "SEQ" }, $beg;
2938                 } else {
2939                     $record->{ "SEQ" } = substr $record->{ "SEQ" }, $beg, $end - $beg + 1;
2940                 }
2941             }
2942             elsif ( defined $beg and defined $len )
2943             {
2944                 if ( $len > length $record->{ "SEQ" } ) {
2945                     $record->{ "SEQ" } = substr $record->{ "SEQ" }, $beg;
2946                 } else {
2947                     $record->{ "SEQ" } = substr $record->{ "SEQ" }, $beg, $len;
2948                 }
2949             }
2950             elsif ( defined $beg )
2951             {
2952                 $record->{ "SEQ" } = substr $record->{ "SEQ" }, $beg;
2953             }
2954         }
2955
2956         $record->{ "SEQ_LEN" } = length $record->{ "SEQ" };
2957
2958         put_record( $record, $out );
2959     }
2960 }
2961
2962
2963 sub script_get_genome_seq
2964 {
2965     # Martin A. Hansen, December 2007.
2966
2967     # Gets a subsequence from a genome.
2968
2969     my ( $in,        # handle to in stream
2970          $out,       # handle to out stream
2971          $options,   # options hash
2972        ) = @_;
2973
2974     # Returns nothing.
2975
2976     my ( $record, $genome, $genome_file, $index_file, $index, $fh, $index_head, $index_beg, $index_len, $beg, $len, %lookup_hash, @begs, @lens, $i );
2977
2978     $options->{ "flank" } ||= 0;
2979
2980     if ( $options->{ "genome" } ) 
2981     {
2982         $genome      = $options->{ "genome" };
2983
2984         $genome_file = "$ENV{ 'BP_DATA' }/genomes/$genome/fasta/$genome.fna";
2985         $index_file  = "$ENV{ 'BP_DATA' }/genomes/$genome/fasta/$genome.index";
2986
2987         $fh          = Maasha::Common::read_open( $genome_file );
2988         $index       = Maasha::Fasta::index_retrieve( $index_file );
2989
2990         shift @{ $index }; # Get rid of the file size info
2991
2992         map { $lookup_hash{ $_->[ 0 ] } = [ $_->[ 1 ], $_->[ 2 ] ] } @{ $index };
2993
2994         if ( exists $lookup_hash{ $options->{ "chr" } } and defined $options->{ "beg" } and ( defined $options->{ "end" } or defined $options->{ "len" } ) )
2995         {
2996             ( $index_beg, $index_len ) = @{ $lookup_hash{ $options->{ "chr" } } };
2997
2998             $beg = $index_beg + $options->{ "beg" } - 1;
2999
3000             if ( $options->{ "len" } ) {
3001                 $len = $options->{ "len" };
3002             } elsif ( $options->{ "end" } ) {
3003                 $len = ( $options->{ "end" } - $options->{ "beg" } + 1 );
3004             }   
3005             
3006             $beg -= $options->{ "flank" };
3007             $len += 2 * $options->{ "flank" };
3008
3009             if ( $beg <= $index_beg )
3010             {
3011                 $len -= $index_beg - $beg;
3012                 $beg = $index_beg;
3013             }
3014
3015             $len = $index_beg + $index_len - $beg if $beg + $len > $index_beg + $index_len;
3016
3017             next if $beg > $index_beg + $index_len;
3018
3019             $record->{ "CHR" }     = $options->{ "chr" };
3020             $record->{ "CHR_BEG" } = $beg - $index_beg;
3021             $record->{ "CHR_END" } = $record->{ "CHR_BEG" } + $len - 1;
3022             
3023             $record->{ "SEQ" }     = Maasha::Common::file_read( $fh, $beg, $len );
3024             $record->{ "SEQ_LEN" } = $len;
3025
3026             put_record( $record, $out );
3027         }   
3028     }
3029
3030     while ( $record = get_record( $in ) ) 
3031     {
3032         if ( $options->{ "genome" } and not $record->{ "SEQ" } )
3033         {
3034             if ( $record->{ "REC_TYPE" } eq "BED" and exists $lookup_hash{ $record->{ "CHR" } } )
3035             {
3036                 ( $index_beg, $index_len ) = @{ $lookup_hash{ $record->{ "CHR" } } };
3037             
3038                 $beg = $record->{ "CHR_BEG" } + $index_beg;
3039                 $len = $record->{ "CHR_END" } - $record->{ "CHR_BEG" } + 1;
3040             }
3041             elsif ( $record->{ "REC_TYPE" } eq "PSL" and exists $lookup_hash{ $record->{ "S_ID" } } )
3042             {
3043                 ( $index_beg, $index_len ) = @{ $lookup_hash{ $record->{ "S_ID" } } };
3044             
3045                 $beg = $record->{ "S_BEG" } + $index_beg;
3046                 $len = $record->{ "S_END" } - $record->{ "S_BEG" } + 1;
3047             }
3048             elsif ( $record->{ "REC_TYPE" } eq "BLAST" and exists $lookup_hash{ $record->{ "S_ID" } } )
3049             {
3050                 ( $index_beg, $index_len ) = @{ $lookup_hash{ $record->{ "S_ID" } } };
3051             
3052                 $beg = $record->{ "S_BEG" } + $index_beg;
3053                 $len = $record->{ "S_END" } - $record->{ "S_BEG" } + 1;
3054             }
3055
3056             $beg -= $options->{ "flank" };
3057             $len += 2 * $options->{ "flank" };
3058
3059             if ( $beg <= $index_beg )
3060             {
3061                 $len -= $index_beg - $beg;
3062                 $beg = $index_beg;
3063             }
3064
3065             $len = $index_beg + $index_len - $beg if $beg + $len > $index_beg + $index_len;
3066
3067             next if $beg > $index_beg + $index_len;
3068
3069             $record->{ "CHR_BEG" } = $beg - $index_beg;
3070             $record->{ "CHR_END" } = $record->{ "CHR_BEG" } + $len - 1;
3071
3072             $record->{ "SEQ" } = Maasha::Common::file_read( $fh, $beg, $len );
3073
3074             if ( $record->{ "STRAND" } and $record->{ "STRAND" } eq "-" )
3075             {
3076                 Maasha::Seq::dna_comp( \$record->{ "SEQ" } );
3077                 $record->{ "SEQ" } = reverse $record->{ "SEQ" };
3078             }
3079
3080             if ( $options->{ "mask" } )
3081             {
3082                 if ( $record->{ "BLOCKCOUNT" } > 1 ) # uppercase hit block segments and lowercase the rest.
3083                 {
3084                     $record->{ "SEQ" } = lc $record->{ "SEQ" };
3085                 
3086                     @begs = split ",", $record->{ "Q_BEGS" };
3087                     @lens = split ",", $record->{ "BLOCKSIZES" };
3088
3089                     for ( $i = 0; $i < @begs; $i++ ) {
3090                         substr $record->{ "SEQ" }, $begs[ $i ], $lens[ $i ], uc substr $record->{ "SEQ" }, $begs[ $i ], $lens[ $i ];
3091                     }
3092                 }
3093             }
3094         }
3095
3096         put_record( $record, $out );
3097     }
3098
3099     close $fh if $fh;                                                                                                                                          
3100 }
3101
3102
3103 sub script_get_genome_align
3104 {
3105     # Martin A. Hansen, April 2008.
3106
3107     # Gets a subalignment from a multiple genome alignment.
3108
3109     my ( $in,        # handle to in stream
3110          $out,       # handle to out stream
3111          $options,   # options hash
3112        ) = @_;
3113
3114     # Returns nothing.
3115
3116     my ( $record, $maf_track, $align, $align_num, $beg, $end, $len, $entry );
3117
3118     $options->{ "strand" } ||= "+";
3119
3120     $align_num = 1;
3121
3122     $maf_track = Maasha::Config::maf_track( $options->{ "genome" } );
3123
3124     if ( $options->{ "chr" } and $options->{ "beg" } and ( $options->{ "end" } or $options->{ "len" } ) )
3125     {
3126         $beg = $options->{ "beg" } - 1;
3127         
3128         if ( $options->{ "end" } ) {
3129             $end = $options->{ "end" };
3130         } elsif ( $options->{ "len" } ) {
3131             $end = $beg + $options->{ "len" };
3132         }
3133
3134         $align = Maasha::UCSC::maf_extract( $BP_TMP, $options->{ "genome" }, $maf_track, $options->{ "chr" }, $beg, $end, $options->{ "strand" } );
3135
3136         foreach $entry ( @{ $align } )
3137         {
3138             $entry->{ "CHR" }     = $record->{ "CHR" };
3139             $entry->{ "CHR_BEG" } = $record->{ "CHR_BEG" };
3140             $entry->{ "CHR_END" } = $record->{ "CHR_END" };
3141             $entry->{ "STRAND" }  = $record->{ "STRAND" } || '+';
3142             $entry->{ "Q_ID" }    = $record->{ "Q_ID" };
3143             $entry->{ "SCORE" }   = $record->{ "SCORE" };
3144
3145             put_record( $entry, $out );
3146         }
3147     }
3148
3149     while ( $record = get_record( $in ) ) 
3150     {
3151         if ( $record->{ "REC_TYPE" } eq "BED" )
3152         {
3153             $align = Maasha::UCSC::maf_extract( $BP_TMP, $options->{ "genome" }, $maf_track, $record->{ "CHR" }, $record->{ "CHR_BEG" }, $record->{ "CHR_END" }, $record->{ "STRAND" } );
3154         }
3155         elsif ( $record->{ "REC_TYPE" } eq "VMATCH" )
3156         {
3157             $align = Maasha::UCSC::maf_extract( $BP_TMP, $options->{ "genome" }, $maf_track, $record->{ "S_ID" }, $record->{ "S_BEG" }, $record->{ "S_END" } + 1, $record->{ "STRAND" } );
3158         }
3159         elsif ( $record->{ "REC_TYPE" } eq "PSL" )
3160         {
3161             $align = Maasha::UCSC::maf_extract( $BP_TMP, $options->{ "genome" }, $maf_track, $record->{ "S_ID" }, $record->{ "S_BEG" }, $record->{ "S_END" }, $record->{ "STRAND" } );
3162         }
3163         elsif ( $record->{ "REC_TYPE" } eq "BLAST" )
3164         {
3165             $align = Maasha::UCSC::maf_extract( $BP_TMP, $options->{ "genome" }, $maf_track, $record->{ "S_ID" }, $record->{ "S_BEG" }, $record->{ "S_END" }, $record->{ "STRAND" } );
3166         }
3167
3168         foreach $entry ( @{ $align } )
3169         {
3170             $entry->{ "CHR" }     = $record->{ "CHR" };
3171             $entry->{ "CHR_BEG" } = $record->{ "CHR_BEG" };
3172             $entry->{ "CHR_END" } = $record->{ "CHR_END" };
3173             $entry->{ "STRAND" }  = $record->{ "STRAND" };
3174             $entry->{ "Q_ID" }    = $record->{ "Q_ID" };
3175             $entry->{ "SCORE" }   = $record->{ "SCORE" };
3176
3177             put_record( $entry, $out );
3178         }
3179
3180         $align_num++;
3181     }
3182 }
3183
3184
3185 sub script_get_genome_phastcons
3186 {
3187     # Martin A. Hansen, February 2008.
3188
3189     # Get phastcons scores from genome intervals.
3190
3191     my ( $in,        # handle to in stream
3192          $out,       # handle to out stream
3193          $options,   # options hash
3194        ) = @_;
3195
3196     # Returns nothing.
3197
3198     my ( $phastcons_file, $phastcons_index, $index, $fh_phastcons, $scores, $record );
3199
3200     $options->{ "flank" } ||= 0;
3201
3202     $phastcons_file  = Maasha::Config::genome_phastcons( $options->{ "genome" } );
3203     $phastcons_index = Maasha::Config::genome_phastcons_index( $options->{ "genome" } );
3204
3205     $index           = Maasha::UCSC::fixedstep_index_retrieve( $phastcons_index );
3206     $fh_phastcons    = Maasha::Common::read_open( $phastcons_file );
3207
3208     if ( defined $options->{ "chr" } and defined $options->{ "beg" } and ( defined $options->{ "end" } or defined $options->{ "len" } ) )
3209     {
3210         $options->{ "beg" } -= 1;   # request is 1-based
3211         $options->{ "end" } -= 1;   # request is 1-based
3212
3213         if ( $options->{ "len" } ) {
3214             $options->{ "end" } = $options->{ "beg" } + $options->{ "len" } - 1;
3215         }
3216
3217         $scores = Maasha::UCSC::fixedstep_index_lookup( $index, $fh_phastcons, $options->{ "chr" }, $options->{ "beg" }, $options->{ "end" }, $options->{ "flank" } );
3218
3219         $record->{ "CHR" }       = $options->{ "chr" };
3220         $record->{ "CHR_BEG" }   = $options->{ "beg" } - $options->{ "flank" };
3221         $record->{ "CHR_END" }   = $options->{ "end" } + $options->{ "flank" };
3222         
3223         $record->{ "PHASTCONS" }   = join ",", @{ $scores };
3224         $record->{ "PHAST_COUNT" } = scalar @{ $scores };  # DEBUG
3225
3226         put_record( $record, $out );
3227     }   
3228
3229     while ( $record = get_record( $in ) ) 
3230     {
3231         if ( $record->{ "REC_TYPE" } eq "BED" )
3232         {
3233             $scores = Maasha::UCSC::fixedstep_index_lookup( $index, $fh_phastcons, $record->{ "CHR" }, $record->{ "CHR_BEG" }, $record->{ "CHR_END" }, $options->{ "flank" } );
3234         }
3235         elsif ( $record->{ "REC_TYPE" } eq "PSL" )
3236         {
3237             $scores = Maasha::UCSC::fixedstep_index_lookup( $index, $fh_phastcons, $record->{ "S_ID" }, $record->{ "S_BEG" }, $record->{ "S_END" }, $options->{ "flank" } );
3238         }
3239         elsif ( $record->{ "REC_TYPE" } eq "BLAST" )
3240         {
3241             $scores = Maasha::UCSC::fixedstep_index_lookup( $index, $fh_phastcons, $record->{ "S_ID" }, $record->{ "S_BEG" }, $record->{ "S_END" }, $options->{ "flank" } );
3242         }
3243
3244         $record->{ "PHASTCONS" } = join ",", @{ $scores } if @{ $scores };
3245 #        $record->{ "PHAST_COUNT" } = @{ $scores } if @{ $scores };  # DEBUG
3246
3247         put_record( $record, $out );
3248     }
3249
3250     close $fh_phastcons if $fh_phastcons;                                                                                                                                          
3251 }
3252
3253
3254 sub script_fold_seq
3255 {
3256     # Martin A. Hansen, December 2007.
3257
3258     # Folds sequences in stream into secondary structures.
3259
3260     my ( $in,     # handle to in stream
3261          $out,    # handle to out stream
3262        ) = @_;
3263
3264     # Returns nothing.
3265
3266     my ( $record, $type, $struct, $index );
3267
3268     while ( $record = get_record( $in ) ) 
3269     {
3270         if ( $record->{ "SEQ" } )
3271         {
3272             if ( not $type ) {
3273                 $type = Maasha::Seq::seq_guess_type( $record->{ "SEQ" } );
3274             }
3275             
3276             if ( $type ne "protein" )
3277             {
3278                 ( $struct, $index ) = Maasha::Seq::fold_struct_rnafold( $record->{ "SEQ" } );
3279                 $record->{ "SEC_STRUCT" }  = $struct;
3280                 $record->{ "FREE_ENERGY" } = $index;
3281                 $record->{ "SCORE" }       = abs int $index;
3282                 $record->{ "SIZE" }        = length $struct;
3283                 $record->{ "CONF" }        = "1," x $record->{ "SIZE" };
3284             }
3285         }
3286
3287         put_record( $record, $out );
3288     }
3289 }
3290
3291
3292 sub script_split_seq
3293 {
3294     # Martin A. Hansen, August 2007.
3295
3296     # Split a sequence in stream into words.
3297
3298     my ( $in,        # handle to in stream
3299          $out,       # handle to out stream
3300          $options,   # options hash
3301        ) = @_;
3302
3303     # Returns nothing.
3304
3305     my ( $record, $new_record, $i, $subseq, %lookup );
3306
3307     $options->{ "word_size" } ||= 7;
3308
3309     while ( $record = get_record( $in ) ) 
3310     {
3311         if ( $record->{ "SEQ_NAME" } and $record->{ "SEQ" } )
3312         {
3313             for ( $i = 0; $i < length( $record->{ "SEQ" } ) - $options->{ "word_size" } + 1; $i++ )
3314             {
3315                 $subseq = substr $record->{ "SEQ" }, $i, $options->{ "word_size" };
3316
3317                 if ( $options->{ "uniq" } and not $lookup{ $subseq } )
3318                 {
3319                     $new_record->{ "SEQ_NAME" } = $record->{ "SEQ_NAME" } . "[" . ( $i + 1 ) . "-" . ( $i + $options->{ "word_size" } ) . "]";
3320                     $new_record->{ "SEQ" }      = $subseq;
3321
3322                     put_record( $new_record, $out );
3323
3324                     $lookup{ $subseq } = 1;
3325                 }
3326                 else
3327                 {
3328                     $new_record->{ "SEQ_NAME" } = $record->{ "SEQ_NAME" } . "[" . ( $i + 1 ) . "-" . ( $i + $options->{ "word_size" } ) . "]";
3329                     $new_record->{ "SEQ" }      = $subseq;
3330
3331                     put_record( $new_record, $out );
3332                 }
3333             }
3334         }
3335         else
3336         {
3337             put_record( $record, $out );
3338         }
3339     }
3340 }
3341
3342
3343 sub script_split_bed
3344 {
3345     # Martin A. Hansen, June 2008.
3346
3347     # Split a BED record into overlapping windows.
3348
3349     my ( $in,        # handle to in stream
3350          $out,       # handle to out stream
3351          $options,   # options hash
3352        ) = @_;
3353
3354     # Returns nothing.
3355
3356     my ( $record, $new_record, $i );
3357
3358     $options->{ "window_size" } ||= 20;
3359     $options->{ "step_size" }   ||= 1;
3360
3361     while ( $record = get_record( $in ) ) 
3362     {
3363         if ( $record->{ "CHR" } and $record->{ "CHR_BEG" } and $record->{ "CHR_END" } )
3364         {
3365             $record->{ "BED_LEN" } = $record->{ "CHR_END" } - $record->{ "CHR_BEG" } + 1;
3366
3367             for ( $i = 0; $i < $record->{ "BED_LEN" } - $options->{ "window_size" }; $i += $options->{ "step_size" } )
3368             {
3369                 $new_record->{ "REC_TYPE" } = "BED";
3370                 $new_record->{ "CHR" }      = $record->{ "CHR" };
3371                 $new_record->{ "CHR_BEG" }  = $record->{ "CHR_BEG" } + $i;
3372                 $new_record->{ "CHR_END" }  = $record->{ "CHR_BEG" } + $i + $options->{ "window_size" };
3373                 $new_record->{ "BED_LEN" }  = $options->{ "window_size" };
3374                 $new_record->{ "Q_ID" }     = $record->{ "Q_ID" } . "_$i";
3375                 $new_record->{ "SCORE" }    = $record->{ "SCORE" };
3376                 $new_record->{ "STRAND" }   = $record->{ "STRAND" };
3377
3378                 put_record( $new_record, $out );
3379             }
3380         }
3381         else
3382         {
3383             put_record( $record, $out );
3384         }
3385     }
3386 }
3387
3388
3389 sub script_align_seq
3390 {
3391     # Martin A. Hansen, August 2007.
3392
3393     # Align sequences in stream.
3394
3395     my ( $in,    # handle to in stream
3396          $out,   # handle to out stream
3397        ) = @_;
3398
3399     # Returns nothing.
3400
3401     my ( $record, @entries, $entry );
3402
3403     while ( $record = get_record( $in ) ) 
3404     {
3405         if ( $record->{ "SEQ_NAME" } and $record->{ "SEQ" } ) {
3406             push @entries, [ $record->{ "SEQ_NAME" }, $record->{ "SEQ" } ];
3407         } elsif ( $record->{ "Q_ID" } and $record->{ "SEQ" } ) {
3408             push @entries, [ $record->{ "Q_ID" }, $record->{ "SEQ" } ];
3409         } else {
3410             put_record( $record, $out );
3411         }
3412     }
3413
3414     @entries = Maasha::Align::align( \@entries );
3415
3416     foreach $entry ( @entries )
3417     {
3418         if ( $entry->[ SEQ_NAME ] and $entry->[ SEQ ] )
3419         {
3420             $record = {
3421                 SEQ_NAME => $entry->[ SEQ_NAME ],
3422                 SEQ      => $entry->[ SEQ ],
3423             };
3424
3425             put_record( $record, $out );
3426         }
3427     }
3428 }
3429
3430
3431 sub script_tile_seq
3432 {
3433     # Martin A. Hansen, February 2008.
3434
3435     # Using the first sequence in stream as reference, tile
3436     # all subsequent sequences based on pairwise alignments.
3437
3438     my ( $in,        # handle to in stream
3439          $out,       # handle to out stream
3440          $options,   # options hash
3441        ) = @_;
3442
3443     # Returns nothing.
3444
3445     my ( $record, $first, $ref_entry, @entries );
3446
3447     $first = 1;
3448
3449     while ( $record = get_record( $in ) ) 
3450     {
3451         if ( $record->{ "SEQ_NAME" } and $record->{ "SEQ" } )
3452         {
3453             if ( $first )
3454             {
3455                 $ref_entry = [ $record->{ "SEQ_NAME" }, $record->{ "SEQ" } ];
3456
3457                 $first = 0;
3458             }
3459             else
3460             {
3461                 push @entries, [ $record->{ "SEQ_NAME" }, $record->{ "SEQ" } ];
3462             }
3463         }
3464         else
3465         {
3466             put_record( $record, $out );
3467         }
3468     }
3469
3470     @entries = Maasha::Align::align_tile( $ref_entry, \@entries, $options );
3471
3472     map { put_record( { SEQ_NAME => $_->[ SEQ_NAME ], SEQ => $_->[ SEQ ] }, $out ) } @entries;
3473 }
3474
3475
3476 sub script_invert_align
3477 {
3478     # Martin A. Hansen, February 2008.
3479
3480     # Inverts an alignment showing only non-mathing residues
3481     # using the first sequence as reference.
3482
3483     my ( $in,        # handle to in stream
3484          $out,       # handle to out stream
3485          $options,   # options hash
3486        ) = @_;
3487
3488     # Returns nothing.
3489
3490     my ( $record, @entries );
3491
3492     while ( $record = get_record( $in ) ) 
3493     {
3494         if ( $record->{ "SEQ_NAME" } and $record->{ "SEQ" } )
3495         {
3496             push @entries, [ $record->{ "SEQ_NAME" }, $record->{ "SEQ" } ];
3497         }
3498         else
3499         {
3500             put_record( $record, $out );
3501         }
3502     }
3503
3504     Maasha::Align::align_invert( \@entries, $options->{ "soft" } );
3505
3506     map { put_record( { SEQ_NAME => $_->[ SEQ_NAME ], SEQ => $_->[ SEQ ] }, $out ) } @entries;
3507 }
3508
3509
3510 sub script_patscan_seq
3511 {
3512     # Martin A. Hansen, August 2007.
3513
3514     # Locates patterns in sequences using scan_for_matches.
3515
3516     my ( $in,        # handle to in stream
3517          $out,       # handle to out stream
3518          $options,   # options hash
3519        ) = @_;
3520
3521     # Returns nothing.
3522
3523     my ( $genome_file, @args, $arg, $type, $seq_file, $pat_file, $out_file, $fh_in, $fh_out, $record, $patterns, $pattern, $entry, $result, %head_hash, $i );
3524
3525     if ( $options->{ "patterns" } ) {
3526         $patterns = Maasha::Patscan::parse_patterns( $options->{ "patterns" } );
3527     } elsif ( -f $options->{ "patterns_in" } ) {
3528         $patterns = Maasha::Patscan::read_patterns( $options->{ "patterns_in" } );
3529     }
3530
3531     $genome_file = "$ENV{ 'BP_DATA' }/genomes/$options->{ 'genome' }/fasta/$options->{ 'genome' }.fna" if $options->{ 'genome' };
3532
3533     push @args, "-c"                            if $options->{ "comp" };
3534     push @args, "-m $options->{ 'max_hits' }"   if $options->{ 'max_hits' };
3535     push @args, "-n $options->{ 'max_misses' }" if $options->{ 'max_hits' };
3536
3537     $seq_file = "$BP_TMP/patscan.seq";
3538     $pat_file = "$BP_TMP/patscan.pat";
3539     $out_file = "$BP_TMP/patscan.out";
3540
3541     $fh_out = Maasha::Common::write_open( $seq_file );
3542
3543     $i = 0;
3544
3545     while ( $record = get_record( $in ) ) 
3546     {
3547         if ( $record->{ "SEQ" } and $record->{ "SEQ_NAME" } )
3548         {
3549             $type = Maasha::Seq::seq_guess_type( $record->{ "SEQ" } ) if not $type;
3550
3551             Maasha::Fasta::put_entry( [ $i, $record->{ "SEQ" } ], $fh_out );
3552
3553             $head_hash{ $i } = $record->{ "SEQ_NAME" };
3554
3555             $i++;
3556         }
3557     }
3558
3559     close $fh_out;
3560
3561     $arg  = join " ", @args;
3562     $arg .= " -p" if $type eq "protein";
3563
3564     foreach $pattern ( @{ $patterns } )
3565     {
3566         $fh_out = Maasha::Common::write_open( $pat_file );
3567
3568         print $fh_out "$pattern\n";
3569
3570         close $fh_out;
3571
3572         if ( $options->{ 'genome' } ) {
3573             `scan_for_matches $arg $pat_file < $genome_file > $out_file`;
3574             # Maasha::Common::run( "scan_for_matches", "$arg $pat_file < $genome_file > $out_file" );
3575         } else {
3576             `scan_for_matches $arg $pat_file < $seq_file > $out_file`;
3577             # Maasha::Common::run( "scan_for_matches", "$arg $pat_file < $seq_file > $out_file" );
3578         }
3579
3580         $fh_in = Maasha::Common::read_open( $out_file );
3581
3582         while ( $entry = Maasha::Fasta::get_entry( $fh_in ) )
3583         {
3584             $result = Maasha::Patscan::parse_scan_result( $entry, $pattern );
3585
3586             if ( $options->{ 'genome' } )
3587             {
3588                 $result->{ "CHR" }     = $result->{ "S_ID" };
3589                 $result->{ "CHR_BEG" } = $result->{ "S_BEG" }; 
3590                 $result->{ "CHR_END" } = $result->{ "S_END" }; 
3591
3592                 delete $result->{ "S_ID" };
3593                 delete $result->{ "S_BEG" };
3594                 delete $result->{ "S_END" };
3595             }
3596             else
3597             {
3598                 $result->{ "S_ID" } = $head_hash{ $result->{ "S_ID" } };
3599             }
3600
3601             put_record( $result, $out );
3602         }
3603
3604         close $fh_in;
3605     }
3606
3607     unlink $pat_file;
3608     unlink $seq_file;
3609     unlink $out_file;
3610 }
3611
3612
3613 sub script_create_blast_db
3614 {
3615     # Martin A. Hansen, September 2007.
3616
3617     # Creates a NCBI BLAST database with formatdb
3618
3619     my ( $in,        # handle to in stream
3620          $out,       # handle to out stream
3621          $options,   # options hash
3622        ) = @_;
3623
3624     # Returns nothing.
3625
3626     my ( $fh, $seq_type, $path, $record, $entry );
3627
3628     $path = $options->{ "database" };
3629
3630     $fh = Maasha::Common::write_open( $path );
3631
3632     while ( $record = get_record( $in ) ) 
3633     {
3634         put_record( $record, $out ) if not $options->{ "no_stream" };
3635
3636         if ( $entry = Maasha::Fasta::biopiece2fasta( $record ) )
3637         {
3638             $seq_type = Maasha::Seq::seq_guess_type( $entry->[ SEQ ] ) if not $seq_type;
3639
3640             Maasha::Fasta::put_entry( $entry, $fh );
3641         }
3642     }
3643
3644     close $fh;
3645
3646     if ( $seq_type eq "protein" ) {
3647         Maasha::Common::run( "formatdb", "-p T -i $path -t $options->{ 'database' }" );
3648     } else {
3649         Maasha::Common::run( "formatdb", "-p F -i $path -t $options->{ 'database' }" );
3650     }
3651
3652     unlink $path;
3653 }
3654
3655
3656 sub script_blast_seq
3657 {
3658     # Martin A. Hansen, September 2007.
3659
3660     # BLASTs sequences in stream against a given database.
3661
3662     my ( $in,        # handle to in stream
3663          $out,       # handle to out stream
3664          $options,   # options hash
3665        ) = @_;
3666
3667     # Returns nothing.
3668
3669     my ( $genome, $q_type, $s_type, $tmp_in, $tmp_out, $fh_in, $fh_out, $record, $line, @fields, $entry );
3670
3671     $options->{ "e_val" }  = 10 if not defined $options->{ "e_val" };
3672     $options->{ "filter" } = "F";
3673     $options->{ "filter" } = "T" if $options->{ "filter" };
3674     $options->{ "cpus" } ||= 1;
3675
3676     $options->{ "database" } = "$ENV{ 'BP_DATA' }/genomes/$options->{ 'genome' }/blast/$options->{ 'genome' }.fna" if $options->{ 'genome' };
3677
3678     $tmp_in  = "$BP_TMP/blast_query.seq";
3679     $tmp_out = "$BP_TMP/blast.result";
3680
3681     $fh_out = Maasha::Filesys::file_write_open( $tmp_in );
3682
3683     while ( $record = get_record( $in ) ) 
3684     {
3685         if ( $entry = Maasha::Fasta::biopiece2fasta( $record ) )
3686         {
3687             $q_type = Maasha::Seq::seq_guess_type( $entry->[ SEQ ] ) if not $q_type;
3688
3689             Maasha::Fasta::put_entry( $entry, $fh_out );
3690         }
3691
3692         put_record( $record, $out );
3693     }
3694
3695     close $fh_out;
3696
3697     if ( -f $options->{ 'database' } . ".phr" ) {
3698         $s_type = "protein";
3699     } else {
3700         $s_type = "nucleotide";
3701     }
3702
3703     if ( not $options->{ 'program' } )
3704     {
3705         if ( $q_type ne "protein" and $s_type ne "protein" ) {
3706             $options->{ 'program' } = "blastn";
3707         } elsif ( $q_type eq "protein" and $s_type eq "protein" ) {
3708             $options->{ 'program' } = "blastp";
3709         } elsif ( $q_type ne "protein" and $s_type eq "protein" ) {
3710             $options->{ 'program' } = "blastx";
3711         } elsif ( $q_type eq "protein" and $s_type ne "protein" ) {
3712             $options->{ 'program' } = "tblastn";
3713         }
3714     }
3715
3716     if ( $options->{ 'verbose' } )
3717     {
3718         Maasha::Common::run(
3719             "blastall",
3720             join( " ",
3721                 "-p $options->{ 'program' }",
3722                 "-e $options->{ 'e_val' }",
3723                 "-a $options->{ 'cpus' }",
3724                 "-m 8",
3725                 "-i $tmp_in",
3726                 "-d $options->{ 'database' }",
3727                 "-F $options->{ 'filter' }",
3728                 "-o $tmp_out",
3729             ),
3730             1
3731         );
3732     }
3733     else
3734     {
3735         Maasha::Common::run(
3736             "blastall",
3737             join( " ",
3738                 "-p $options->{ 'program' }",
3739                 "-e $options->{ 'e_val' }",
3740                 "-a $options->{ 'cpus' }",
3741                 "-m 8",
3742                 "-i $tmp_in",
3743                 "-d $options->{ 'database' }",
3744                 "-F $options->{ 'filter' }",
3745                 "-o $tmp_out",
3746                 "> /dev/null 2>&1"
3747             ),
3748             1
3749         );
3750     }
3751
3752     unlink $tmp_in;
3753
3754     $fh_out = Maasha::Filesys::file_read_open( $tmp_out );
3755
3756     undef $record;
3757
3758     while ( $line = <$fh_out> )
3759     {
3760         chomp $line;
3761
3762         next if $line =~ /^#/;
3763
3764         @fields = split /\s+/, $line;
3765
3766         $record->{ "REC_TYPE" }   = "BLAST";
3767         $record->{ "Q_ID" }       = $fields[ 0 ];
3768         $record->{ "S_ID" }       = $fields[ 1 ];
3769         $record->{ "IDENT" }      = $fields[ 2 ];
3770         $record->{ "ALIGN_LEN" }  = $fields[ 3 ];
3771         $record->{ "MISMATCHES" } = $fields[ 4 ];
3772         $record->{ "GAPS" }       = $fields[ 5 ];
3773         $record->{ "Q_BEG" }      = $fields[ 6 ] - 1; # BLAST is 1-based
3774         $record->{ "Q_END" }      = $fields[ 7 ] - 1; # BLAST is 1-based
3775         $record->{ "S_BEG" }      = $fields[ 8 ] - 1; # BLAST is 1-based
3776         $record->{ "S_END" }      = $fields[ 9 ] - 1; # BLAST is 1-based
3777         $record->{ "E_VAL" }      = $fields[ 10 ];
3778         $record->{ "BIT_SCORE" }  = $fields[ 11 ];
3779
3780         if ( $record->{ "S_BEG" } > $record->{ "S_END" } )
3781         {
3782             $record->{ "STRAND" } = '-';
3783
3784             ( $record->{ "S_BEG" }, $record->{ "S_END" } ) = ( $record->{ "S_END" }, $record->{ "S_BEG" } );
3785         }
3786         else
3787         {
3788             $record->{ "STRAND" } = '+';
3789         }
3790
3791         put_record( $record, $out );
3792     }
3793
3794     close $fh_out;
3795
3796     unlink $tmp_out;
3797 }
3798
3799
3800 sub script_blat_seq
3801 {
3802     # Martin A. Hansen, August 2007.
3803
3804     # BLATs sequences in stream against a given genome.
3805
3806     my ( $in,        # handle to in stream
3807          $out,       # handle to out stream
3808          $options,   # options hash
3809        ) = @_;
3810
3811     # Returns nothing.
3812
3813     my ( $blat_args, $genome_file, $query_file, $fh_in, $fh_out, $type, $record, $result_file, $entries, $entry );
3814
3815     $genome_file = "$ENV{ 'BP_DATA' }/genomes/$options->{ 'genome' }/fasta/$options->{ 'genome' }.fna";
3816
3817     $options->{ 'tile_size' }    ||= 11;
3818     $options->{ 'one_off' }      ||= 0;
3819     $options->{ 'min_identity' } ||= 90;
3820     $options->{ 'min_score' }    ||= 0;
3821     $options->{ 'step_size' }    ||= $options->{ 'tile_size' };
3822
3823     $blat_args .= " -tileSize=$options->{ 'tile_size' }";
3824     $blat_args .= " -oneOff=$options->{ 'one_off' }";
3825     $blat_args .= " -minIdentity=$options->{ 'min_identity' }";
3826     $blat_args .= " -minScore=$options->{ 'min_score' }";
3827     $blat_args .= " -stepSize=$options->{ 'step_size' }";
3828 #    $blat_args .= " -ooc=" . Maasha::Config::genome_blat_ooc( $options->{ "genome" }, 11 ) if $options->{ 'ooc' };
3829
3830     $query_file = "$BP_TMP/blat.seq";
3831
3832     $fh_out = Maasha::Common::write_open( $query_file );
3833
3834     while ( $record = get_record( $in ) ) 
3835     {
3836         if ( $entry = Maasha::Fasta::biopiece2fasta( $record ) )
3837         {
3838             $type = Maasha::Seq::seq_guess_type( $entry->[ SEQ ] ) if not $type;
3839             Maasha::Fasta::put_entry( $entry, $fh_out, 80 );
3840         }
3841
3842         put_record( $record, $out );
3843     }
3844
3845     close $fh_out;
3846
3847     $blat_args .= " -t=dnax" if $type eq "protein";
3848     $blat_args .= " -q=$type";
3849
3850     $result_file = "$BP_TMP/blat.psl";
3851
3852     Maasha::Common::run( "blat", "$genome_file $query_file $blat_args $result_file > /dev/null 2>&1" );
3853
3854     unlink $query_file;
3855
3856     $entries = Maasha::UCSC::psl_get_entries( $result_file );
3857
3858     map { put_record( $_, $out ) } @{ $entries };
3859
3860     unlink $result_file;
3861 }
3862
3863
3864 sub script_soap_seq
3865 {
3866     # Martin A. Hansen, July 2008.
3867
3868     # soap sequences in stream against a given file or genome.
3869
3870     my ( $in,        # handle to in stream
3871          $out,       # handle to out stream
3872          $options,   # options hash
3873        ) = @_;
3874
3875     # Returns nothing.
3876
3877     my ( $genome, $tmp_in, $tmp_out, $fh_in, $fh_out, $record, $line, @fields, $entry, $count, $args );
3878
3879     $options->{ "seed_size" }  ||= 10;
3880     $options->{ "mismatches" } ||= 2;
3881     $options->{ "gap_size" }   ||= 0;
3882     $options->{ "cpus" }       ||= 1;
3883
3884     if ( $options->{ "genome" } ) {
3885         $options->{ "in_file" } = "$ENV{ 'BP_DATA' }/genomes/$options->{ 'genome' }/fasta/$options->{ 'genome' }.fna";
3886     }
3887
3888     $tmp_in  = "$BP_TMP/soap_query.seq";
3889     $tmp_out = "$BP_TMP/soap.result";
3890
3891     $fh_out = Maasha::Common::write_open( $tmp_in );
3892  
3893     $count = 0;
3894
3895     while ( $record = get_record( $in ) ) 
3896     {
3897         if ( $entry = Maasha::Fasta::biopiece2fasta( $record ) )
3898         {
3899             Maasha::Fasta::put_entry( $entry, $fh_out );
3900
3901             $count++;
3902         }
3903
3904         put_record( $record, $out );
3905     }
3906
3907     close $fh_out;
3908
3909     if ( $count > 0 )
3910     {
3911         $args = join( " ",
3912             "-s $options->{ 'seed_size' }",
3913             "-r 2",
3914             "-a $tmp_in",
3915             "-v $options->{ 'mismatches' }",
3916             "-g $options->{ 'gap_size' }",
3917             "-p $options->{ 'cpus' }",
3918             "-d $options->{ 'in_file' }",
3919             "-o $tmp_out",
3920         );
3921
3922         $args .= " > /dev/null 2>&1" if not $options->{ 'verbose' };
3923
3924         Maasha::Common::run( "soap", $args, 1 );
3925
3926         unlink $tmp_in;
3927
3928         $fh_out = Maasha::Common::read_open( $tmp_out );
3929
3930         undef $record;
3931
3932         while ( $line = <$fh_out> )
3933         {
3934             chomp $line;
3935
3936             @fields = split /\t/, $line;
3937
3938             $record->{ "REC_TYPE" }   = "SOAP";
3939             $record->{ "Q_ID" }       = $fields[ 0 ];
3940             $record->{ "SCORE" }      = $fields[ 3 ];
3941             $record->{ "STRAND" }     = $fields[ 6 ];
3942             $record->{ "S_ID" }       = $fields[ 7 ];
3943             $record->{ "S_BEG" }      = $fields[ 8 ] - 1; # soap is 1-based
3944             $record->{ "S_END" }      = $fields[ 8 ] + $fields[ 5 ] - 2;
3945
3946             put_record( $record, $out );
3947         }
3948
3949         close $fh_out;
3950     }
3951
3952     unlink $tmp_out;
3953 }
3954
3955
3956 sub script_match_seq
3957 {
3958     # Martin A. Hansen, August 2007.
3959
3960     # BLATs sequences in stream against a given genome.
3961
3962     my ( $in,        # handle to in stream
3963          $out,       # handle to out stream
3964          $options,   # options hash
3965        ) = @_;
3966
3967     # Returns nothing.
3968
3969     my ( $record, @entries, $results );
3970
3971     $options->{ "word_size" } ||= 20;
3972     $options->{ "direction" } ||= "both";
3973
3974     while ( $record = get_record( $in ) ) 
3975     {
3976         if ( $record->{ "SEQ_NAME" } and $record->{ "SEQ" } ) {
3977             push @entries, [ $record->{ "SEQ_NAME" }, $record->{ "SEQ" } ];
3978         }
3979
3980         put_record( $record, $out );
3981     }
3982
3983     if ( @entries == 1 )
3984     {
3985         $results = Maasha::Match::match_mummer( [ $entries[ 0 ] ], [ $entries[ 0 ] ], $options, $BP_TMP );
3986
3987         map { put_record( $_, $out ) } @{ $results };
3988     }
3989     elsif ( @entries == 2 )
3990     {
3991         $results = Maasha::Match::match_mummer( [ $entries[ 0 ] ], [ $entries[ 1 ] ], $options, $BP_TMP );
3992
3993         map { put_record( $_, $out ) } @{ $results };
3994     }
3995 }
3996
3997
3998 sub script_create_vmatch_index
3999 {
4000     # Martin A. Hansen, January 2008.
4001
4002     # Create a vmatch index from sequences in the stream.
4003
4004     my ( $in,        # handle to in stream
4005          $out,       # handle to out stream
4006          $options,   # options hash
4007        ) = @_;
4008
4009     # Returns nothing.
4010
4011     my ( $record, $file_tmp, $fh_tmp, $type, $entry );
4012
4013     if ( $options->{ "index_name" } )
4014     {
4015         $file_tmp = $options->{ 'index_name' };
4016         $fh_tmp   = Maasha::Common::write_open( $file_tmp );
4017     }
4018
4019     while ( $record = get_record( $in ) ) 
4020     {
4021         if ( $options->{ "index_name" } and $entry = Maasha::Fasta::biopiece2fasta( $record ) )
4022         {
4023             Maasha::Fasta::put_entry( $entry, $fh_tmp );
4024
4025             $type = Maasha::Seq::seq_guess_type( $entry->[ SEQ ] ) if not defined $type;
4026         }
4027
4028         put_record( $record, $out ) if not $options->{ "no_stream" };
4029     }
4030
4031     if ( $options->{ "index_name" } )
4032     {
4033         close $fh_tmp;
4034     
4035         if ( $type eq "protein" ) {
4036             Maasha::Common::run( "mkvtree", "-db $file_tmp -protein -pl $options->{ 'prefix_length' } -allout -indexname $file_tmp > /dev/null 2>&1" );
4037         } else {
4038             Maasha::Common::run( "mkvtree", "-db $file_tmp -dna -pl $options->{ 'prefix_length' } -allout -indexname $file_tmp > /dev/null 2>&1" );
4039         }
4040
4041         unlink $file_tmp;
4042     }
4043 }
4044
4045
4046 sub script_vmatch_seq
4047 {
4048     # Martin A. Hansen, August 2007.
4049
4050     # Vmatches sequences in stream against a given genome.
4051
4052     my ( $in,        # handle to in stream
4053          $out,       # handle to out stream
4054          $options,   # options hash
4055        ) = @_;
4056
4057     # Returns nothing.
4058
4059     my ( @index_files, @records, $result_file, $fh_in, $record, %hash );
4060
4061     $options->{ 'count' } = 1 if $options->{ 'max_hits' };
4062
4063     if ( $options->{ "index_name" } )
4064     {
4065         @index_files = $options->{ "index_name" };
4066     }
4067     else
4068     {
4069         @index_files = Maasha::Common::ls_files( "$ENV{ 'BP_DATA' }/genomes/$options->{ 'genome' }/vmatch" );
4070
4071         map { $_ =~ /^(.+)\.[a-z1]{3,4}$/; $hash{ $1 } = 1 } @index_files;
4072
4073         @index_files = sort keys %hash;
4074     }
4075
4076     while ( $record = get_record( $in ) ) 
4077     {
4078         push @records, $record;
4079
4080         put_record( $record, $out );
4081     }
4082
4083     $result_file = Maasha::Match::match_vmatch( $BP_TMP, \@records, \@index_files, $options );
4084
4085     undef @records;
4086
4087     $fh_in = Maasha::Common::read_open( $result_file );
4088
4089     while ( $record = Maasha::Match::vmatch_get_entry( $fh_in ) ) {
4090         put_record( $record, $out );
4091     }
4092
4093     close $fh_in;
4094
4095     unlink $result_file;
4096 }
4097
4098
4099 sub script_write_fasta
4100 {
4101     # Martin A. Hansen, August 2007.
4102
4103     # Write FASTA entries from sequences in stream.
4104
4105     my ( $in,        # handle to in stream
4106          $out,       # handle to out stream
4107          $options,   # options hash
4108        ) = @_;
4109
4110     # Returns nothing.
4111
4112     my ( $record, $fh, $entry );
4113
4114     $fh = write_stream( $options->{ "data_out" }, $options->{ "compress" } );
4115
4116     while ( $record = get_record( $in ) ) 
4117     {
4118         if ( $entry = Maasha::Fasta::biopiece2fasta( $record ) ) {
4119             Maasha::Fasta::put_entry( $entry, $fh, $options->{ "wrap" } );
4120         }
4121
4122         put_record( $record, $out ) if not $options->{ "no_stream" };
4123     }
4124
4125     close $fh;
4126 }
4127
4128
4129 sub script_write_align
4130 {
4131     # Martin A. Hansen, August 2007.
4132
4133     # Write pretty alignments aligned sequences in stream.
4134
4135     my ( $in,        # handle to in stream
4136          $out,       # handle to out stream
4137          $options,   # options hash
4138        ) = @_;
4139
4140     # Returns nothing.
4141
4142     my ( $fh, $record, @entries );
4143
4144     $fh = write_stream( $options->{ "data_out" } ) ;
4145
4146     while ( $record = get_record( $in ) ) 
4147     {
4148         if ( $record->{ "SEQ_NAME" } and $record->{ "SEQ" } ) {
4149             push @entries, [ $record->{ "SEQ_NAME" }, $record->{ "SEQ" } ];
4150         }
4151
4152         put_record( $record, $out ) if not $options->{ "no_stream" };
4153     }
4154
4155     if ( scalar( @entries ) == 2 ) {
4156         Maasha::Align::align_print_pairwise( $entries[ 0 ], $entries[ 1 ], $fh, $options->{ "wrap" } );
4157     } elsif ( scalar ( @entries ) > 2 ) {
4158         Maasha::Align::align_print_multi( \@entries, $fh, $options->{ "wrap" }, $options->{ "no_ruler" }, $options->{ "no_consensus" } );
4159     }
4160
4161     close $fh if $fh;
4162 }
4163
4164
4165 sub script_write_blast
4166 {
4167     # Martin A. Hansen, November 2007.
4168
4169     # Write data in blast table format (-m8 and 9).
4170
4171     my ( $in,        # handle to in stream
4172          $out,       # handle to out stream
4173          $options,   # options hash
4174        ) = @_;
4175
4176     # Returns nothing.
4177
4178     my ( $fh, $record, $first );
4179
4180     $fh = write_stream( $options->{ "data_out" }, $options->{ "compress" } ) ;
4181
4182     $first = 1;
4183
4184     while ( $record = get_record( $in ) ) 
4185     {
4186         if ( $record->{ "REC_TYPE" } eq "BLAST" )
4187         {
4188             if ( $options->{ "comment" } and $first )
4189             {
4190                 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";
4191
4192                 $first = 0;
4193             }
4194
4195             if ( $record->{ "STRAND" } eq "-" ) {
4196                 ( $record->{ "S_BEG" }, $record->{ "S_END" } ) = ( $record->{ "S_END" }, $record->{ "S_BEG" } );
4197             }
4198
4199             print $fh join( "\t",
4200                 $record->{ "Q_ID" },
4201                 $record->{ "S_ID" },
4202                 $record->{ "IDENT" },
4203                 $record->{ "ALIGN_LEN" },
4204                 $record->{ "MISMATCHES" },
4205                 $record->{ "GAPS" },
4206                 $record->{ "Q_BEG" } + 1,
4207                 $record->{ "Q_END" } + 1,
4208                 $record->{ "S_BEG" } + 1,
4209                 $record->{ "S_END" } + 1,
4210                 $record->{ "E_VAL" },
4211                 $record->{ "BIT_SCORE" }
4212             ), "\n";
4213         }
4214
4215         put_record( $record, $out ) if not $options->{ "no_stream" };
4216     }
4217
4218     close $fh;
4219 }
4220
4221
4222 sub script_write_tab
4223 {
4224     # Martin A. Hansen, August 2007.
4225
4226     # Write data as table.
4227
4228     my ( $in,        # handle to in stream
4229          $out,       # handle to out stream
4230          $options,   # options hash
4231        ) = @_;
4232
4233     # Returns nothing.
4234
4235     my ( $fh, $record, $key, @keys, @vals, $ok, %no_keys, $A, $B );
4236
4237     $options->{ "delimit" } ||= "\t";
4238
4239     map { $no_keys{ $_ } = 1 } @{ $options->{ "no_keys" } };
4240
4241     $fh = write_stream( $options->{ "data_out" }, $options->{ "compress" } );
4242
4243     while ( $record = get_record( $in ) ) 
4244     {
4245         undef @vals;
4246         $ok = 1;
4247         
4248         if ( $options->{ "keys" } )
4249         {
4250             map { $ok = 0 if not exists $record->{ $_ } } @{ $options->{ "keys" } };
4251
4252             if ( $ok )
4253             {
4254                 foreach $key ( @{ $options->{ "keys" }  } )
4255                 {
4256                     if ( exists $record->{ $key } )
4257                     {
4258                         push @keys, $key if $options->{ "comment" };
4259                         push @vals, $record->{ $key };
4260                     }
4261                 }
4262              }
4263         }
4264         else
4265         {
4266             foreach $key ( sort { $A = $a; $B = $b; $A =~ s/^V(\d+)$/$1/; $B =~ s/^V(\d+)$/$1/; $A <=> $B } keys %{ $record } )
4267             {
4268                 next if exists $no_keys{ $key };
4269
4270                 push @keys, $key if $options->{ "comment" };
4271                 push @vals, $record->{ $key };
4272             }
4273         }
4274
4275         if ( @keys and $options->{ "comment" } )
4276         {
4277             print $fh "#", join( $options->{ "delimit" }, @keys ), "\n";
4278
4279             delete $options->{ "comment" };
4280         }
4281
4282         print $fh join( $options->{ "delimit" }, @vals ), "\n" if @vals;
4283
4284         put_record( $record, $out ) if not $options->{ "no_stream" };
4285     }
4286
4287     close $fh;
4288 }
4289
4290
4291 sub script_write_bed
4292 {
4293     # Martin A. Hansen, August 2007.
4294
4295     # Write BED format for the UCSC genome browser using records in stream.
4296
4297     my ( $in,        # handle to in stream
4298          $out,       # handle to out stream
4299          $options,   # options hash
4300        ) = @_;
4301
4302     # Returns nothing.
4303
4304     my ( $cols, $fh, $record, $bed_entry, $new_record );
4305
4306     $cols = $options->{ 'cols' }->[ 0 ];
4307
4308     $fh = write_stream( $options->{ 'data_out' }, $options->{ 'compress' } );
4309
4310     while ( $record = get_record( $in ) ) 
4311     {
4312         $record = Maasha::UCSC::psl2record( $record ) if $record->{ 'tBaseInsert' }; # Dirty addition to allow Affy data from MySQL to be dumped
4313
4314         if ( $bed_entry = Maasha::UCSC::BED::biopiece2bed( $record, $cols ) ) {
4315             Maasha::UCSC::BED::bed_entry_put( $bed_entry, $fh, $cols, 1 );
4316         }
4317
4318         put_record( $record, $out ) if not $options->{ 'no_stream' };
4319     }
4320
4321     close $fh;
4322 }
4323
4324
4325 sub script_write_psl
4326 {
4327     # Martin A. Hansen, August 2007.
4328
4329     # Write PSL output from stream.
4330
4331     my ( $in,        # handle to in stream
4332          $out,       # handle to out stream
4333          $options,   # options hash
4334        ) = @_;
4335
4336     # Returns nothing.
4337
4338     my ( $fh, $record, @output, $first );
4339
4340     $first = 1;
4341
4342     $fh = write_stream( $options->{ "data_out" }, $options->{ "compress" } );
4343
4344     while ( $record = get_record( $in ) ) 
4345     {
4346         put_record( $record, $out ) if not $options->{ "no_stream" };
4347
4348         if ( $record->{ "REC_TYPE" } and $record->{ "REC_TYPE" } eq "PSL" )
4349         {
4350             Maasha::UCSC::psl_put_header( $fh ) if $first;
4351             Maasha::UCSC::psl_put_entry( $record, $fh );
4352             $first = 0;
4353         }
4354     }
4355
4356     close $fh;
4357 }
4358
4359
4360 sub script_write_fixedstep
4361 {
4362     # Martin A. Hansen, Juli 2008.
4363
4364     # Write fixedStep entries from recrods in the stream.
4365
4366     my ( $in,        # handle to in stream
4367          $out,       # handle to out stream
4368          $options,   # options hash
4369        ) = @_;
4370
4371     # Returns nothing.
4372
4373     my ( $fh, $record, $entry );
4374
4375     $fh = write_stream( $options->{ "data_out" }, $options->{ "compress" } );
4376
4377     while ( $record = get_record( $in ) ) 
4378     {
4379         if ( $entry = Maasha::UCSC::Wiggle::biopiece2fixedstep( $record ) ) {
4380             Maasha::UCSC::Wiggle::fixedstep_entry_put( $entry, $fh );
4381         }
4382
4383         put_record( $record, $out ) if not $options->{ "no_stream" };
4384     }
4385
4386     close $fh;
4387 }
4388
4389
4390 sub script_write_2bit
4391 {
4392     # Martin A. Hansen, March 2008.
4393
4394     # Write sequence entries from stream in 2bit format.
4395
4396     my ( $in,        # handle to in stream
4397          $out,       # handle to out stream
4398          $options,   # options hash
4399        ) = @_;
4400
4401     # Returns nothing.
4402
4403     my ( $record, $mask, $tmp_file, $fh_tmp, $fh_in, $fh_out, $entry );
4404
4405     $mask = 1 if not $options->{ "no_mask" };
4406
4407     $tmp_file = "$BP_TMP/write_2bit.fna";
4408     $fh_tmp   = Maasha::Common::write_open( $tmp_file );
4409
4410     $fh_out = write_stream( $options->{ "data_out" } );
4411
4412     while ( $record = get_record( $in ) ) 
4413     {
4414         if ( $entry = Maasha::Fasta::biopiece2fasta( $record ) ) {
4415             Maasha::Fasta::put_entry( $entry, $fh_tmp );
4416         }
4417
4418         put_record( $record, $out ) if not $options->{ "no_stream" };
4419     }
4420
4421     close $fh_tmp;
4422
4423     $fh_in = Maasha::Common::read_open( $tmp_file );
4424
4425     Maasha::TwoBit::fasta2twobit( $fh_in, $fh_out, $mask );
4426
4427     close $fh_in;
4428     close $fh_out;
4429
4430     unlink $tmp_file;
4431 }
4432
4433
4434 sub script_write_solid
4435 {
4436     # Martin A. Hansen, April 2008.
4437
4438     # Write di-base encoded Solid sequence from entries in stream.
4439
4440     my ( $in,        # handle to in stream
4441          $out,       # handle to out stream
4442          $options,   # options hash
4443        ) = @_;
4444
4445     # Returns nothing.
4446
4447     my ( $record, $fh, $entry );
4448
4449     $fh = write_stream( $options->{ "data_out" }, $options->{ "compress" } );
4450
4451     while ( $record = get_record( $in ) ) 
4452     {
4453         if ( $entry = Maasha::Fasta::biopiece2fasta( $record ) )
4454         {
4455             $entry->[ SEQ ] = Maasha::Solid::seq2color_space( uc $entry->[ SEQ ] );
4456
4457             Maasha::Fasta::put_entry( $entry, $fh, $options->{ "wrap" } );
4458         }
4459
4460         put_record( $record, $out ) if not $options->{ "no_stream" };
4461     }
4462
4463     close $fh;
4464 }
4465
4466
4467 sub script_write_ucsc_config
4468 {
4469     # Martin A. Hansen, November 2008.
4470
4471     # Write UCSC Genome Broser configuration (.ra file type) from
4472     # records in the stream.
4473
4474     my ( $in,        # handle to in stream
4475          $out,       # handle to out stream
4476          $options,   # options hash
4477        ) = @_;
4478
4479     # Returns nothing.
4480
4481     my ( $record, $fh );
4482
4483     $fh = write_stream( $options->{ "data_out" } );
4484
4485     while ( $record = get_record( $in ) ) 
4486     {
4487         Maasha::UCSC::ucsc_config_entry_put( $record, $fh ) if $record->{ "REC_TYPE" } eq "UCSC Config";
4488
4489         put_record( $record, $out ) if not $options->{ "no_stream" };
4490     }
4491
4492     close $fh;
4493 }
4494
4495
4496 sub script_plot_seqlogo
4497 {
4498     # Martin A. Hansen, August 2007.
4499
4500     # Calculates and writes a sequence logo for alignments.
4501
4502     my ( $in,        # handle to in stream
4503          $out,       # handle to out stream
4504          $options,   # options hash
4505        ) = @_;
4506
4507     # Returns nothing.
4508
4509     my ( $record, @entries, $logo, $fh );
4510
4511     while ( $record = get_record( $in ) ) 
4512     {
4513         if ( $record->{ "SEQ_NAME" } and $record->{ "SEQ" } ) {
4514             push @entries, [ $record->{ "SEQ_NAME" }, $record->{ "SEQ" } ];
4515         }
4516
4517         put_record( $record, $out ) if not $options->{ "no_stream" };
4518     }
4519
4520     $logo = Maasha::Plot::seq_logo( \@entries );
4521
4522     $fh = write_stream( $options->{ "data_out" } );
4523
4524     print $fh $logo;
4525
4526     close $fh;
4527 }
4528
4529
4530 sub script_plot_phastcons_profiles
4531 {
4532     # Martin A. Hansen, January 2008.
4533
4534     # Plots PhastCons profiles.
4535
4536     my ( $in,        # handle to in stream
4537          $out,       # handle to out stream
4538          $options,   # options hash
4539        ) = @_;
4540
4541     # Returns nothing.
4542
4543     my ( $phastcons_file, $phastcons_index, $index, $fh_phastcons, $record, $scores, $AoA, $plot, $fh );
4544
4545     $options->{ "title" } ||= "PhastCons Profiles";
4546
4547     $phastcons_file  = Maasha::Config::genome_phastcons( $options->{ "genome" } );
4548     $phastcons_index = Maasha::Config::genome_phastcons_index( $options->{ "genome" } );
4549
4550     $index           = Maasha::UCSC::fixedstep_index_retrieve( $phastcons_index );
4551     $fh_phastcons    = Maasha::Common::read_open( $phastcons_file );
4552
4553     while ( $record = get_record( $in ) ) 
4554     {
4555         if ( $record->{ "CHR" } and $record->{ "CHR_BEG" } and $record->{ "CHR_END" } )
4556         {
4557             $scores = Maasha::UCSC::fixedstep_index_lookup( $index, $fh_phastcons, $record->{ "CHR" },
4558                                                                                    $record->{ "CHR_BEG" },
4559                                                                                    $record->{ "CHR_END" },
4560                                                                                    $options->{ "flank" } );
4561
4562             push @{ $AoA }, [ @{ $scores } ];
4563         }
4564
4565         put_record( $record, $out ) if not $options->{ "no_stream" };
4566     }
4567
4568     Maasha::UCSC::phastcons_normalize( $AoA );
4569
4570     $AoA = [ [ Maasha::UCSC::phastcons_mean( $AoA ) ] ] if $options->{ "mean" };
4571     $AoA = [ [ Maasha::UCSC::phastcons_median( $AoA ) ] ] if $options->{ "median" };
4572
4573     $AoA = Maasha::Matrix::matrix_flip( $AoA );
4574
4575     $plot = Maasha::Plot::lineplot_simple( $AoA, $options, $BP_TMP );
4576
4577     $fh = write_stream( $options->{ "data_out" } );
4578
4579     print $fh "$_\n" foreach @{ $plot };
4580
4581     close $fh;
4582 }
4583
4584
4585 sub script_analyze_bed
4586 {
4587     # Martin A. Hansen, March 2008.
4588
4589     # Analyze BED entries in stream.
4590
4591     my ( $in,        # handle to in stream
4592          $out,       # handle to out stream
4593          $options,   # options hash
4594        ) = @_;
4595
4596     # Returns nothing.
4597
4598     my ( $record );
4599
4600     while ( $record = get_record( $in ) ) 
4601     {
4602         $record = Maasha::UCSC::bed_analyze( $record ) if $record->{ "REC_TYPE" } eq "BED";
4603
4604         put_record( $record, $out );
4605     }
4606 }
4607
4608
4609 sub script_analyze_vals
4610 {
4611     # Martin A. Hansen, August 2007.
4612
4613     # Analyze values for given keys in stream.
4614
4615     my ( $in,        # handle to in stream
4616          $out,       # handle to out stream
4617          $options,   # options hash
4618        ) = @_;
4619
4620     # Returns nothing.
4621
4622     my ( $record, $key, @keys, %key_hash, $analysis, $len );
4623
4624     map { $key_hash{ $_ } = 1 } @{ $options->{ "keys" } };
4625
4626     while ( $record = get_record( $in ) ) 
4627     {
4628         foreach $key ( keys %{ $record } )
4629         {
4630             next if $options->{ "keys" } and not exists $key_hash{ $key };
4631
4632             $analysis->{ $key }->{ "COUNT" }++;
4633
4634             if ( Maasha::Calc::is_a_number( $record->{ $key } ) )
4635             {
4636                 $analysis->{ $key }->{ "TYPE" } = "num";
4637                 $analysis->{ $key }->{ "SUM" } += $record->{ $key };
4638                 $analysis->{ $key }->{ "MAX" } = $record->{ $key } if $record->{ $key } > $analysis->{ $key }->{ "MAX" } or not $analysis->{ $key }->{ "MAX" };
4639                 $analysis->{ $key }->{ "MIN" } = $record->{ $key } if $record->{ $key } < $analysis->{ $key }->{ "MIN" } or not $analysis->{ $key }->{ "MIN" };
4640             }
4641             else
4642             {
4643                 $len = length $record->{ $key };
4644
4645                 $analysis->{ $key }->{ "TYPE" } = "alph";
4646                 $analysis->{ $key }->{ "SUM" } += $len;
4647                 $analysis->{ $key }->{ "MAX" } = $len if $len > $analysis->{ $key }->{ "MAX" } or not $analysis->{ $key }->{ "MAX" };
4648                 $analysis->{ $key }->{ "MIN" } = $len if $len < $analysis->{ $key }->{ "MIM" } or not $analysis->{ $key }->{ "MIN" };
4649             }
4650         }
4651
4652         put_record( $record, $out ) if not $options->{ "no_stream" };
4653     }
4654
4655     foreach $key ( keys %{ $analysis } )
4656     {
4657         $analysis->{ $key }->{ "MEAN" } = sprintf "%.2f", $analysis->{ $key }->{ "SUM" } / $analysis->{ $key }->{ "COUNT" };
4658         $analysis->{ $key }->{ "SUM" }  = sprintf "%.2f", $analysis->{ $key }->{ "SUM" };
4659     }
4660
4661     my ( $keys, $types, $counts, $mins, $maxs, $sums, $means );
4662
4663     $keys   = "KEY  ";
4664     $types  = "TYPE ";
4665     $counts = "COUNT";
4666     $mins   = "MIN  ";
4667     $maxs   = "MAX  ";
4668     $sums   = "SUM  ";
4669     $means  = "MEAN ";
4670
4671     if ( $options->{ "keys" } ) {
4672         @keys = @{ $options->{ "keys" } };
4673     } else {
4674         @keys = keys %{ $analysis };
4675     }
4676
4677     foreach $key ( @keys )
4678     {
4679         $keys   .= sprintf "% 15s", $key;
4680         $types  .= sprintf "% 15s", $analysis->{ $key }->{ "TYPE" };
4681         $counts .= sprintf "% 15s", $analysis->{ $key }->{ "COUNT" };
4682         $mins   .= sprintf "% 15s", $analysis->{ $key }->{ "MIN" };
4683         $maxs   .= sprintf "% 15s", $analysis->{ $key }->{ "MAX" };
4684         $sums   .= sprintf "% 15s", $analysis->{ $key }->{ "SUM" };
4685         $means  .= sprintf "% 15s", $analysis->{ $key }->{ "MEAN" };
4686     }
4687
4688     print $out "$keys\n";
4689     print $out "$types\n";
4690     print $out "$counts\n";
4691     print $out "$mins\n";
4692     print $out "$maxs\n";
4693     print $out "$sums\n";
4694     print $out "$means\n";
4695 }
4696
4697
4698 sub script_head_records
4699 {
4700     # Martin A. Hansen, August 2007.
4701
4702     # Display the first sequences in stream.
4703
4704     my ( $in,        # handle to in stream
4705          $out,       # handle to out stream
4706          $options,   # options hash
4707        ) = @_;
4708
4709     # Returns nothing.
4710
4711     my ( $record, $count );
4712
4713     $options->{ "num" } ||= 10;
4714
4715     $count = 0;
4716
4717     while ( $record = get_record( $in ) ) 
4718     {
4719         $count++;
4720
4721         put_record( $record, $out );
4722
4723         last if $count == $options->{ "num" };
4724     }
4725 }
4726
4727
4728 sub script_remove_keys
4729 {
4730     # Martin A. Hansen, August 2007.
4731
4732     # Remove keys from stream.
4733
4734     my ( $in,        # handle to in stream
4735          $out,       # handle to out stream
4736          $options,   # options hash
4737        ) = @_;
4738
4739     # Returns nothing.
4740
4741     my ( $record, $new_record );
4742
4743     while ( $record = get_record( $in ) ) 
4744     {
4745         if ( $options->{ "keys" } )
4746         {
4747             map { delete $record->{ $_ } } @{ $options->{ "keys" } };
4748         }
4749         elsif ( $options->{ "save_keys" } )
4750         {
4751             map { $new_record->{ $_ } = $record->{ $_ } if exists $record->{ $_ } } @{ $options->{ "save_keys" } };
4752
4753             $record = $new_record;
4754         }
4755
4756         put_record( $record, $out ) if keys %{ $record };
4757     }
4758 }
4759
4760
4761 sub script_remove_adaptor
4762 {
4763     # Martin A. Hansen, August 2008.
4764
4765     # Find and remove adaptor from sequences in the stream.
4766
4767     my ( $in,        # handle to in stream
4768          $out,       # handle to out stream
4769          $options,   # options hash
4770        ) = @_;
4771
4772     # Returns nothing.
4773
4774     my ( $record, $adaptor, $seq, $adaptor_len, $seq_len, $offset, $max_match, $max_mismatch, $pos );
4775
4776     $options->{ "remove" } ||= "after";
4777
4778     $max_mismatch = $options->{ "mismatches" } || 0;
4779     $offset       = $options->{ "offset" };
4780
4781     if ( not defined $offset ) {
4782         $offset = 0;
4783     } else {
4784         $offset--;
4785     }
4786
4787     $adaptor      = uc $options->{ "adaptor" };
4788     $adaptor_len  = length $adaptor;
4789
4790     while ( $record = get_record( $in ) ) 
4791     {
4792         if ( $record->{ "SEQ" } )
4793         {
4794             $seq     = uc $record->{ "SEQ" };
4795             $seq_len = length $seq;
4796
4797             $pos = Maasha::Common::index_m( $seq, $adaptor, $seq_len, $adaptor_len, $offset, $max_mismatch );
4798
4799             $record->{ "ADAPTOR_POS" } = $pos;
4800
4801             if ( $pos >= 0 and $options->{ "remove" } ne "skip" )
4802             {
4803                 if ( $options->{ "remove" } eq "after" )
4804                 {
4805                     $record->{ "SEQ" }     = substr $record->{ "SEQ" }, 0, $pos;
4806                     $record->{ "SEQ_LEN" } = $pos;
4807                 }
4808                 else
4809                 {
4810                     $record->{ "SEQ" }     = substr $record->{ "SEQ" }, $pos + $adaptor_len;
4811                     $record->{ "SEQ_LEN" } = length $record->{ "SEQ" };
4812                 }
4813             }
4814
4815             put_record( $record, $out );
4816         }
4817         else
4818         {
4819             put_record( $record, $out );
4820         }
4821     }
4822 }
4823
4824
4825 sub script_remove_mysql_tables
4826 {
4827     # Martin A. Hansen, November 2008.
4828
4829     # Remove MySQL tables from values in stream.
4830
4831     my ( $in,        # handle to in stream
4832          $out,       # handle to out stream
4833          $options,   # options hash
4834        ) = @_;
4835
4836     # Returns nothing.
4837
4838     my ( $record, %table_hash, $dbh, $table );
4839
4840     $options->{ "user" }     ||= Maasha::UCSC::ucsc_get_user();
4841     $options->{ "password" } ||= Maasha::UCSC::ucsc_get_password();
4842
4843     map { $table_hash{ $_ } = 1 } @{ $options->{ 'tables' } };
4844
4845     while ( $record = get_record( $in ) )
4846     {
4847         map { $table_hash{ $record->{ $_ } } = 1 } @{ $options->{ 'keys' } };
4848
4849         put_record( $record, $out ) if not $options->{ 'no_stream' };
4850     }
4851
4852     $dbh = Maasha::SQL::connect( $options->{ "database" }, $options->{ "user" }, $options->{ "password" } );
4853
4854     foreach $table ( sort keys %table_hash )
4855     {
4856         if ( Maasha::SQL::table_exists( $dbh, $table ) )
4857         {
4858             print STDERR qq(Removing table "$table" from database "$options->{ 'database' }" ... ) if $options->{ 'verbose' };
4859             Maasha::SQL::delete_table( $dbh, $table );
4860             print STDERR "done.\n" if $options->{ 'verbose' };
4861         }
4862         else
4863         {
4864             print STDERR qq(WARNING: table "$table" not found in database "$options->{ 'database' }\n");
4865         }
4866     }
4867
4868     Maasha::SQL::disconnect( $dbh );
4869 }
4870
4871
4872 sub script_remove_ucsc_tracks
4873 {
4874     # Martin A. Hansen, November 2008.
4875
4876     # Remove track from MySQL tables and config file.
4877
4878     my ( $in,        # handle to in stream
4879          $out,       # handle to out stream
4880          $options,   # options hash
4881        ) = @_;
4882
4883     # Returns nothing.
4884
4885     my ( $record, %track_hash, $fh_in, $fh_out, $track, @tracks, @new_tracks, $dbh );
4886
4887     $options->{ 'user' }        ||= Maasha::UCSC::ucsc_get_user();
4888     $options->{ 'password' }    ||= Maasha::UCSC::ucsc_get_password();
4889     $options->{ 'config_file' } ||= "$ENV{ 'HOME' }/ucsc/my_tracks.ra";
4890
4891     map { $track_hash{ $_ } = 1 } @{ $options->{ 'tracks' } };
4892
4893     while ( $record = get_record( $in ) )
4894     {
4895         map { $track_hash{ $record->{ $_ } } = 1 } @{ $options->{ 'keys' } };
4896
4897         put_record( $record, $out ) if not $options->{ 'no_stream' };
4898     }
4899
4900     # ---- locate track in config file ----
4901
4902     $fh_in = Maasha::Common::read_open( $options->{ 'config_file' } );
4903     
4904     while ( $track = Maasha::UCSC::ucsc_config_entry_get( $fh_in ) ) {
4905         push @tracks, $track;
4906     }
4907
4908     close $fh_in;
4909
4910     map { push @new_tracks, $_ if not exists $track_hash{ $_->{ 'track' } } } @tracks;
4911
4912     print STDERR qq(WARNING: track not found in config file: "$options->{ 'config_file' }"\n) if scalar @tracks == scalar @new_tracks;
4913
4914     rename "$options->{ 'config_file' }", "$options->{ 'config_file' }~";
4915
4916     $fh_out = Maasha::Common::write_open( $options->{ 'config_file' } );
4917
4918     map { Maasha::UCSC::ucsc_config_entry_put( $_, $fh_out ) } @new_tracks;
4919
4920     close $fh_out;
4921
4922     # ---- locate track in database ----
4923
4924     $dbh = Maasha::SQL::connect( $options->{ "database" }, $options->{ "user" }, $options->{ "password" } );
4925
4926     foreach $track ( sort keys %track_hash )
4927     {
4928         if ( Maasha::SQL::table_exists( $dbh, $track ) )
4929         {
4930             print STDERR qq(Removing table "$track" from database "$options->{ 'database' }" ... ) if $options->{ 'verbose' };
4931             Maasha::SQL::delete_table( $dbh, $track );
4932             print STDERR "done.\n" if $options->{ 'verbose' };
4933         }
4934         else
4935         {
4936             print STDERR qq(WARNING: table "$track" not found in database "$options->{ 'database' }\n");
4937         }
4938     }
4939
4940     Maasha::SQL::disconnect( $dbh );
4941
4942     Maasha::Common::run( "ucscMakeTracks.pl", "-b > /dev/null 2>&1" );
4943 }
4944
4945
4946 sub script_rename_keys
4947 {
4948     # Martin A. Hansen, August 2007.
4949
4950     # Rename keys in stream.
4951
4952     my ( $in,        # handle to in stream
4953          $out,       # handle to out stream
4954          $options,   # options hash
4955        ) = @_;
4956
4957     # Returns nothing.
4958
4959     my ( $record );
4960
4961     while ( $record = get_record( $in ) ) 
4962     {
4963         if ( exists $record->{ $options->{ "keys" }->[ 0 ] } )
4964         {
4965             $record->{ $options->{ "keys" }->[ 1 ] } = $record->{ $options->{ "keys" }->[ 0 ] };
4966
4967             delete $record->{ $options->{ "keys" }->[ 0 ] };
4968         }
4969
4970         put_record( $record, $out );
4971     }
4972 }
4973
4974
4975 sub script_uniq_vals
4976 {
4977     # Martin A. Hansen, August 2007.
4978
4979     # Find unique values in stream.
4980
4981     my ( $in,        # handle to in stream
4982          $out,       # handle to out stream
4983          $options,   # options hash
4984        ) = @_;
4985
4986     # Returns nothing.
4987
4988     my ( %hash, $record );
4989
4990     while ( $record = get_record( $in ) ) 
4991     {
4992         if ( $record->{ $options->{ "key" } } )
4993         {
4994             if ( not $hash{ $record->{ $options->{ "key" } } } and not $options->{ "invert" } )
4995             {
4996                 put_record( $record, $out );
4997
4998                 $hash{ $record->{ $options->{ "key" } } } = 1;
4999             }
5000             elsif ( $hash{ $record->{ $options->{ "key" } } } and $options->{ "invert" } )
5001             {
5002                 put_record( $record, $out );
5003             }
5004             else
5005             {
5006                 $hash{ $record->{ $options->{ "key" } } } = 1;
5007             }
5008         }
5009         else
5010         {
5011             put_record( $record, $out );
5012         }
5013     }
5014 }
5015
5016
5017 sub script_merge_vals
5018 {
5019     # Martin A. Hansen, August 2007.
5020
5021     # Rename keys in stream.
5022
5023     my ( $in,        # handle to in stream
5024          $out,       # handle to out stream
5025          $options,   # options hash
5026        ) = @_;
5027
5028     # Returns nothing.
5029
5030     my ( $record, @join, $i );
5031
5032     $options->{ "delimit" } ||= '_';
5033
5034     while ( $record = get_record( $in ) ) 
5035     {
5036         if ( exists $record->{ $options->{ "keys" }->[ 0 ] } )
5037         {
5038             @join = $record->{ $options->{ "keys" }->[ 0 ] };
5039             
5040             for ( $i = 1; $i < @{ $options->{ "keys" } }; $i++ ) {
5041                 push @join, $record->{ $options->{ "keys" }->[ $i ] } if exists $record->{ $options->{ "keys" }->[ $i ] };
5042             }
5043
5044             $record->{ $options->{ "keys" }->[ 0 ] } = join $options->{ "delimit" }, @join;
5045         }
5046
5047         put_record( $record, $out );
5048     }
5049 }
5050
5051
5052 sub script_merge_records
5053 {
5054     # Martin A. Hansen, July 2008.
5055
5056     # Merges records in the stream based on identical values of two given keys.
5057
5058     my ( $in,        # handle to in stream
5059          $out,       # handle to out stream
5060          $options,   # options hash
5061        ) = @_;
5062
5063     # Returns nothing.
5064
5065     my ( $merge, $record, $file1, $file2, $fh1, $fh2, $key1, $key2, @keys1, @keys2, @vals1, @vals2,
5066          $num1, $num2, $num, $cmp, $i );
5067
5068     $merge = $options->{ "merge" } || "AandB";
5069
5070     $file1 = "$BP_TMP/merge_records1.tmp";
5071     $file2 = "$BP_TMP/merge_records2.tmp";
5072
5073     $fh1   = Maasha::Common::write_open( $file1 );
5074     $fh2   = Maasha::Common::write_open( $file2 );
5075
5076     $key1  = $options->{ "keys" }->[ 0 ];
5077     $key2  = $options->{ "keys" }->[ 1 ];
5078
5079     $num   = $key2 =~ s/n$//;
5080     $num1  = 0;
5081     $num2  = 0;
5082
5083     while ( $record = get_record( $in ) ) 
5084     {
5085         if ( exists $record->{ $key1 } )
5086         {
5087             @keys1 = $key1;
5088             @vals1 = $record->{ $key1 };
5089
5090             delete $record->{ $key1 };
5091
5092             map { push @keys1, $_; push @vals1, $record->{ $_ } } keys %{ $record };
5093
5094             print $fh1 join( "\t", @vals1 ), "\n";
5095
5096             $num1++;
5097         }
5098         elsif ( exists $record->{ $key2 } )
5099         {
5100             @keys2 = $key2;
5101             @vals2 = $record->{ $key2 };
5102
5103             delete $record->{ $key2 };
5104
5105             map { push @keys2, $_; push @vals2, $record->{ $_ } } keys %{ $record };
5106
5107             print $fh2 join( "\t", @vals2 ), "\n";
5108
5109             $num2++;
5110         }
5111     }
5112
5113     close $fh1;
5114     close $fh2;
5115
5116     if ( $num )
5117     {
5118         Maasha::Common::run( "sort", "-k 1,1n $file1 > $file1.sort" ) and rename "$file1.sort", $file1;
5119         Maasha::Common::run( "sort", "-k 1,1n $file2 > $file2.sort" ) and rename "$file2.sort", $file2;
5120     }
5121     else
5122     {
5123         Maasha::Common::run( "sort", "-k 1,1 $file1 > $file1.sort" ) and rename "$file1.sort", $file1;
5124         Maasha::Common::run( "sort", "-k 1,1 $file2 > $file2.sort" ) and rename "$file2.sort", $file2;
5125     }
5126
5127     $fh1 = Maasha::Common::read_open( $file1 );
5128     $fh2 = Maasha::Common::read_open( $file2 );
5129
5130     @vals1 = Maasha::Common::get_fields( $fh1 );
5131     @vals2 = Maasha::Common::get_fields( $fh2 );
5132
5133     while ( $num1 > 0 and $num2 > 0 )
5134     {
5135         undef $record;
5136
5137         if ( $num ) {
5138             $cmp = $vals1[ 0 ] <=> $vals2[ 0 ];
5139         } else {
5140             $cmp = $vals1[ 0 ] cmp $vals2[ 0 ];
5141         }
5142
5143         if ( $cmp < 0 )
5144         {
5145             if ( $merge =~ /^(AorB|AnotB)$/ )
5146             {
5147                 for ( $i = 0; $i < @keys1; $i++ ) {
5148                     $record->{ $keys1[ $i ] } = $vals1[ $i ];
5149                 }
5150
5151                 put_record( $record, $out );
5152             }
5153
5154             @vals1 = Maasha::Common::get_fields( $fh1 );
5155             $num1--;
5156         }
5157         elsif ( $cmp > 0 )
5158         {
5159             if ( $merge =~ /^(BorA|BnotA)$/ )
5160             {
5161                 for ( $i = 0; $i < @keys2; $i++ ) {
5162                     $record->{ $keys2[ $i ] } = $vals2[ $i ];
5163                 }
5164
5165                 put_record( $record, $out );
5166             }
5167
5168             @vals2 = Maasha::Common::get_fields( $fh2 );
5169             $num2--;
5170         }
5171         else
5172         {
5173             if ( $merge =~ /^(AandB|AorB|BorA)$/ )
5174             {
5175                 for ( $i = 0; $i < @keys1; $i++ ) {
5176                     $record->{ $keys1[ $i ] } = $vals1[ $i ];
5177                 }
5178
5179                 for ( $i = 1; $i < @keys2; $i++ ) {
5180                     $record->{ $keys2[ $i ] } = $vals2[ $i ];
5181                 }
5182             
5183                 put_record( $record, $out );
5184             }
5185
5186             @vals1 = Maasha::Common::get_fields( $fh1 );
5187             @vals2 = Maasha::Common::get_fields( $fh2 );
5188             $num1--;
5189             $num2--;
5190         }
5191     }
5192
5193     close $fh1;
5194     close $fh2;
5195
5196     unlink $file1;
5197     unlink $file2;
5198
5199     if ( $num1 > 0 and $merge =~ /^(AorB|AnotB)$/ )
5200     {
5201         undef $record;
5202
5203         for ( $i = 0; $i < @keys1; $i++ ) {
5204             $record->{ $keys1[ $i ] } = $vals1[ $i ];
5205         }
5206
5207         put_record( $record, $out );
5208     }
5209
5210     if ( $num2 > 0 and $merge =~ /^(BorA|BnotA)$/ )
5211     {
5212         undef $record;
5213
5214         for ( $i = 0; $i < @keys2; $i++ ) {
5215             $record->{ $keys2[ $i ] } = $vals2[ $i ];
5216         }
5217
5218         put_record( $record, $out );
5219     }
5220 }
5221
5222
5223 sub script_grab
5224 {
5225     # Martin A. Hansen, August 2007.
5226
5227     # Grab for records in stream.
5228
5229     my ( $in,        # handle to in stream
5230          $out,       # handle to out stream
5231          $options,   # options hash
5232        ) = @_;
5233
5234     # Returns nothing.
5235
5236     my ( $keys, $vals_only, $keys_only, $invert, $patterns, $pattern, $regex, $record, $key, $op, $val, %lookup_hash, $found );
5237
5238     $keys      = $options->{ 'keys' };
5239     $vals_only = $options->{ 'vals_only' };
5240     $keys_only = $options->{ 'keys_only' };
5241     $invert    = $options->{ 'invert' };
5242
5243     if ( $options->{ 'patterns' } )
5244     {
5245         $patterns = [ split ",", $options->{ 'patterns' } ];
5246     }
5247     elsif ( -f $options->{ 'patterns_in' } )
5248     {
5249         $patterns = Maasha::Patscan::read_patterns( $options->{ 'patterns_in' } );
5250     }
5251     elsif ( $options->{ 'regex' } )
5252     {
5253         if ( $options->{ 'case_insensitive' } ) {
5254             $regex = qr/$options->{ 'regex' }/i;
5255         } else {
5256             $regex = qr/$options->{ 'regex' }/;
5257         }
5258     }
5259     elsif ( -f $options->{ 'exact_in' } )
5260     {
5261         $patterns = Maasha::Patscan::read_patterns( $options->{ 'exact_in' } );
5262
5263         map { $lookup_hash{ $_ } = 1 } @{ $patterns };
5264
5265         undef $patterns;
5266     }
5267     elsif ( $options->{ 'eval' } )
5268     {
5269         if ( $options->{ 'eval' } =~ /^([^><=! ]+)\s*(>=|<=|>|<|=|!=|eq|ne)\s*(.+)$/ )
5270         {
5271             $key = $1;
5272             $op  = $2;
5273             $val = $3;
5274         }
5275     } 
5276
5277     while ( $record = get_record( $in ) ) 
5278     {
5279         $found = 0;
5280
5281         if ( %lookup_hash ) {
5282             $found = grab_lookup( \%lookup_hash, $record, $keys, $vals_only, $keys_only );
5283         } elsif ( $patterns ) {
5284             $found = grab_patterns( $patterns, $record, $keys, $vals_only, $keys_only );
5285         } elsif ( $regex ) {
5286             $found = grab_regex( $regex, $record, $keys, $vals_only, $keys_only );
5287         } elsif ( $op ) {
5288             $found = grab_eval( $key, $op, $val, $record );
5289         }
5290
5291         if ( $found and not $invert ) {
5292             put_record( $record, $out );
5293         } elsif ( not $found and $invert ) {
5294             put_record( $record, $out );
5295         }
5296     }
5297 }
5298
5299
5300 sub script_compute
5301 {
5302     # Martin A. Hansen, August 2007.
5303
5304     # Evaluate extression for records in stream.
5305
5306     my ( $in,        # handle to in stream
5307          $out,       # handle to out stream
5308          $options,   # options hash
5309        ) = @_;
5310
5311     # Returns nothing.
5312
5313     my ( $record, $eval_key, @keys, $eval_val );
5314
5315     while ( $record = get_record( $in ) ) 
5316     {
5317         if ( $options->{ "eval" } )
5318         {
5319             if ( $options->{ "eval" } =~ /^(\S+)\s*=\s*(.+)$/ )
5320             {
5321                 $eval_key = $1;
5322                 $eval_val = $2;
5323
5324                 if ( not @keys )
5325                 {
5326                     @keys = split /\s+|\+|-|\*|\/|\*\*/, $eval_val;
5327
5328                     @keys = grep { exists $record->{ $_ } } @keys;
5329                 }
5330
5331                 map { $eval_val =~ s/\Q$_\E/$record->{ $_ }/g } @keys;
5332
5333                 $record->{ $eval_key } = eval "$eval_val";
5334                 Maasha::Common::error( qq(eval "$eval_key = $eval_val" failed -> $@) ) if $@;
5335             }
5336             else
5337             {
5338                 Maasha::Common::error( qq(Bad compute expression: "$options->{ 'eval' }"\n) );
5339             }
5340         } 
5341
5342         put_record( $record, $out );
5343     }
5344 }
5345
5346
5347 sub script_flip_tab
5348 {
5349     # Martin A. Hansen, June 2008.
5350
5351     # Flip a table.
5352
5353     my ( $in,        # handle to in stream
5354          $out,       # handle to out stream
5355          $options,   # options hash
5356        ) = @_;
5357
5358     # Returns nothing.
5359
5360     my ( $record, $key, $A, $B, @rows, @matrix, $row, $i );
5361
5362     while ( $record = get_record( $in ) ) 
5363     {
5364         undef @rows;
5365
5366         foreach $key ( sort { $A = $a; $B = $b; $A =~ s/^V(\d+)$/$1/; $B =~ s/^V(\d+)$/$1/; $A <=> $B } keys %{ $record } )
5367         {
5368             push @rows, $record->{ $key };
5369
5370         }
5371
5372         push @matrix, [ @rows ];
5373     }
5374
5375     undef $record;
5376
5377     @matrix = Maasha::Matrix::matrix_flip( \@matrix );
5378
5379     foreach $row ( @matrix )
5380     {
5381         for ( $i = 0; $i < @{ $row }; $i++ ) {
5382             $record->{ "V$i" } = $row->[ $i ];
5383         }
5384
5385         put_record( $record, $out );
5386     }
5387 }
5388
5389
5390 sub script_add_ident
5391 {
5392     # Martin A. Hansen, May 2008.
5393
5394     # Add a unique identifier to each record in stream.
5395
5396     my ( $in,        # handle to in stream
5397          $out,       # handle to out stream
5398          $options,   # options hash
5399        ) = @_;
5400
5401     # Returns nothing.
5402
5403     my ( $record, $key, $prefix, $i );
5404
5405     $key    = $options->{ "key" }    || "ID";
5406     $prefix = $options->{ "prefix" } || "ID";
5407
5408     $i = 0;
5409
5410     while ( $record = get_record( $in ) ) 
5411     {
5412         $record->{ $key } = sprintf( "$prefix%08d", $i );
5413
5414         put_record( $record, $out );
5415
5416         $i++;
5417     }
5418 }
5419
5420
5421 sub script_count_records
5422 {
5423     # Martin A. Hansen, August 2007.
5424
5425     # Count records in stream.
5426
5427     my ( $in,        # handle to in stream
5428          $out,       # handle to out stream
5429          $options,   # options hash
5430        ) = @_;
5431
5432     # Returns nothing.
5433
5434     my ( $record, $count, $result, $fh, $line );
5435
5436     $count = 0;
5437
5438     if ( $options->{ "no_stream" } )
5439     {
5440         while ( $line = <$in> )
5441         {
5442             chomp $line;
5443
5444             $count++ if $line eq "---";
5445         }
5446     }
5447     else
5448     {
5449         while ( $record = get_record( $in ) ) 
5450         {
5451             put_record( $record, $out );
5452
5453             $count++;
5454         }
5455     }
5456
5457     $result = { "RECORDS_COUNT" => $count };
5458
5459     $fh = write_stream( $options->{ "data_out" } );
5460
5461     put_record( $result, $fh );
5462
5463     close $fh;
5464 }
5465
5466
5467 sub script_random_records
5468 {
5469     # Martin A. Hansen, August 2007.
5470
5471     # Pick a number or random records from stream.
5472
5473     my ( $in,        # handle to in stream
5474          $out,       # handle to out stream
5475          $options,   # options hash
5476        ) = @_;
5477
5478     # Returns nothing.
5479
5480     my ( $record, $tmp_file, $fh_out, $fh_in, $count, $i, %rand_hash, $rand, $max );
5481
5482     $options->{ "num" } ||= 10;
5483
5484     $tmp_file = "$BP_TMP/random_records.tmp";
5485
5486     $fh_out = Maasha::Common::write_open( $tmp_file );
5487
5488     $count = 0;
5489
5490     while ( $record = get_record( $in ) ) 
5491     {
5492         put_record( $record, $fh_out );
5493
5494         $count++;
5495     }
5496
5497     close $fh_out;
5498
5499     $max = 0;
5500     $i   = 0;
5501
5502     Maasha::Common::error( qq(Requested random records > records in stream) ) if $options->{ "num" } > $count;
5503
5504     while ( $i < $options->{ "num" } )
5505     {
5506         $rand = int( rand( $count ) );
5507     
5508         if ( not exists $rand_hash{ $rand } )
5509         {
5510             $rand_hash{ $rand } = 1;
5511
5512             $max = $rand if $rand > $max;
5513
5514             $i++;
5515         }
5516     }
5517
5518     $fh_in = Maasha::Common::read_open( $tmp_file );
5519
5520     $count = 0;
5521
5522     while ( $record = get_record( $fh_in ) ) 
5523     {
5524         put_record( $record, $out ) if exists $rand_hash{ $count };
5525
5526         last if $count == $max;
5527
5528         $count++;
5529     }
5530
5531     close $fh_in;
5532
5533     unlink $tmp_file;
5534 }
5535
5536
5537 sub script_sort_records
5538 {
5539     # Martin A. Hansen, August 2007.
5540
5541     # Sort to sort records according to keys.
5542
5543     my ( $in,        # handle to in stream
5544          $out,       # handle to out stream
5545          $options,   # options hash
5546        ) = @_;
5547
5548     # Returns nothing.
5549
5550     my ( @keys, $key, @sort_cmd, $sort_str, $sort_sub, @records, $record, $i );
5551
5552     foreach $key ( @{ $options->{ "keys" } } )
5553     {
5554         if ( $key =~ s/n$// ) {
5555             push @sort_cmd, qq(\$a->{ "$key" } <=> \$b->{ "$key" });
5556         } else {
5557             push @sort_cmd, qq(\$a->{ "$key" } cmp \$b->{ "$key" });
5558         }
5559     }
5560
5561     $sort_str = join " or ", @sort_cmd;
5562     $sort_sub = eval "sub { $sort_str }";   # NB security issue!
5563
5564     while ( $record = get_record( $in ) ) {
5565         push @records, $record;
5566     }
5567
5568     @records = sort $sort_sub @records;
5569
5570     if ( $options->{ "reverse" } )
5571     {
5572         for ( $i = scalar @records - 1; $i >= 0; $i-- ) {
5573             put_record( $records[ $i ], $out );
5574         }
5575     }
5576     else
5577     {
5578         for ( $i = 0; $i < scalar @records; $i++ ) {
5579             put_record( $records[ $i ], $out );
5580         }
5581     }
5582 }
5583
5584
5585 sub script_count_vals
5586 {
5587     # Martin A. Hansen, August 2007.
5588
5589     # Count records in stream.
5590
5591     my ( $in,        # handle to in stream
5592          $out,       # handle to out stream
5593          $options,   # options hash
5594        ) = @_;
5595
5596     # Returns nothing.
5597
5598     my ( $num, $record, %count_hash, @records, $tmp_file, $fh_out, $fh_in, $cache );
5599
5600     $tmp_file = "$BP_TMP/count_cache.tmp";
5601
5602     $fh_out   = Maasha::Common::write_open( $tmp_file );
5603
5604     $cache    = 0;
5605     $num      = 0;
5606
5607     while ( $record = get_record( $in ) ) 
5608     {
5609         map { $count_hash{ $_ }{ $record->{ $_ } }++ if exists $record->{ $_ } } @{ $options->{ "keys" } };
5610
5611         push @records, $record;
5612
5613         if ( scalar @records > 5_000_000 )   # too many records to hold in memory - use disk cache
5614         {
5615             map { put_record( $_, $fh_out ) } @records;
5616
5617             undef @records;
5618
5619             $cache = 1;
5620         }
5621
5622         print STDERR "verbose: records read $num\n" if ( $options->{ 'verbose' } and ( $num % 1_000_000 ) == 0 );
5623
5624         $num++;
5625     }
5626
5627     close $fh_out;
5628
5629     if ( $cache )
5630     {
5631         $num   = 0;
5632
5633         $fh_in = Maasha::Common::read_open( $tmp_file );
5634
5635         while ( $record = get_record( $fh_in ) )
5636         {
5637             map { $record->{ $_ . "_COUNT" } = $count_hash{ $_ }{ $record->{ $_ } } if exists $record->{ $_ } } @{ $options->{ "keys" } };
5638
5639             put_record( $record, $out );
5640
5641             print STDERR "verbose: cache read $num\n" if ( $options->{ 'verbose' } and ( $num % 1_000_000 ) == 0 );
5642
5643             $num++;
5644         }
5645     
5646         close $fh_in;
5647     }
5648
5649     foreach $record ( @records )
5650     {
5651         map { $record->{ $_ . "_COUNT" } = $count_hash{ $_ }{ $record->{ $_ } } if exists $record->{ $_ } } @{ $options->{ "keys" } };
5652
5653         put_record( $record, $out );
5654     }
5655
5656     unlink $tmp_file;
5657 }
5658
5659
5660 sub script_plot_histogram
5661 {
5662     # Martin A. Hansen, September 2007.
5663
5664     # Plot a simple histogram for a given key using GNU plot.
5665
5666     my ( $in,        # handle to in stream
5667          $out,       # handle to out stream
5668          $options,   # options hash
5669        ) = @_;
5670
5671     # Returns nothing.
5672
5673     my ( $record, %data_hash, $max, @data_list, $i, $result, $fh );
5674
5675     $options->{ "title" } ||= "Histogram";
5676     $options->{ "sort" }  ||= "num";
5677
5678     while ( $record = get_record( $in ) ) 
5679     {
5680         $data_hash{ $record->{ $options->{ "key" } } }++ if defined $record->{ $options->{ "key" } };
5681
5682         put_record( $record, $out ) if not $options->{ "no_stream" };
5683     }
5684
5685     if ( $options->{ "sort" } eq "num" ) {
5686         map { push @data_list, [ $_, $data_hash{ $_ } ] } sort { $a <=> $b } keys %data_hash;
5687     } else {
5688         map { push @data_list, [ $_, $data_hash{ $_ } ] } sort keys %data_hash;
5689     }
5690
5691     $result = Maasha::Plot::histogram_simple( \@data_list, $options );
5692
5693     $fh = write_stream( $options->{ "data_out" } );
5694
5695     print $fh "$_\n" foreach @{ $result };
5696
5697     close $fh;
5698 }
5699
5700
5701 sub script_plot_lendist
5702 {
5703     # Martin A. Hansen, August 2007.
5704
5705     # Plot length distribution using GNU plot.
5706
5707     my ( $in,        # handle to in stream
5708          $out,       # handle to out stream
5709          $options,   # options hash
5710        ) = @_;
5711
5712     # Returns nothing.
5713
5714     my ( $record, %data_hash, $max, @data_list, $i, $result, $fh );
5715
5716     $options->{ "title" } ||= "Length Distribution";
5717
5718     while ( $record = get_record( $in ) ) 
5719     {
5720         $data_hash{ $record->{ $options->{ "key" } } }++ if defined $record->{ $options->{ "key" } };
5721
5722         put_record( $record, $out ) if not $options->{ "no_stream" };
5723     }
5724
5725     $max = Maasha::Calc::list_max( [ keys %data_hash ] );
5726
5727     for ( $i = 0; $i < $max; $i++ ) {
5728         push @data_list, [ $i, $data_hash{ $i } || 0 ];
5729     }
5730
5731     $result = Maasha::Plot::histogram_lendist( \@data_list, $options );
5732
5733     $fh = write_stream( $options->{ "data_out" } );
5734
5735     print $fh "$_\n" foreach @{ $result };
5736
5737     close $fh;
5738 }
5739
5740
5741 sub script_plot_chrdist
5742 {
5743     # Martin A. Hansen, August 2007.
5744
5745     # Plot chromosome distribution using GNU plot.
5746
5747     my ( $in,        # handle to in stream
5748          $out,       # handle to out stream
5749          $options,   # options hash
5750        ) = @_;
5751
5752     # Returns nothing.
5753
5754     my ( $record, %data_hash, @data_list, $elem, $sort_key, $count, $result, $fh );
5755
5756     $options->{ "title" } ||= "Chromosome Distribution";
5757
5758     while ( $record = get_record( $in ) ) 
5759     {
5760         if ( $record->{ "CHR" } ) {                                                             # generic
5761             $data_hash{ $record->{ "CHR" } }++;
5762         } elsif ( $record->{ "REC_TYPE" } eq "PATSCAN" and $record->{ "S_ID" } =~ /^chr/i ) {   # patscan
5763             $data_hash{ $record->{ "S_ID" } }++;
5764         } elsif ( $record->{ "REC_TYPE" } eq "PSL" and $record->{ "S_ID" } =~ /^chr/i ) {       # BLAT / PSL
5765             $data_hash{ $record->{ "S_ID" } }++;
5766         } elsif ( $record->{ "REC_TYPE" } eq "BLAST" and $record->{ "S_ID" } =~ /^chr/i ) {     # BLAST
5767             $data_hash{ $record->{ "S_ID" } }++;
5768         }
5769
5770         put_record( $record, $out ) if not $options->{ "no_stream" };
5771     }
5772
5773     foreach $elem ( keys %data_hash )
5774     {
5775         $sort_key = $elem;
5776
5777         $sort_key =~ s/chr//i;
5778     
5779         $sort_key =~ s/^X(.*)/99$1/;
5780         $sort_key =~ s/^Y(.*)/99$1/;
5781         $sort_key =~ s/^Z(.*)/999$1/;
5782         $sort_key =~ s/^M(.*)/9999$1/;
5783         $sort_key =~ s/^U(.*)/99999$1/;
5784
5785         $count = $sort_key =~ tr/_//;
5786
5787         $sort_key =~ s/_.*/"999999" x $count/ex;
5788
5789         push @data_list, [ $elem, $data_hash{ $elem }, $sort_key ];
5790     }
5791
5792     @data_list = sort { $a->[ 2 ] <=> $b->[ 2 ] } @data_list;
5793
5794     $result = Maasha::Plot::histogram_chrdist( \@data_list, $options );
5795
5796     $fh = write_stream( $options->{ "data_out" } );
5797
5798     print $fh "$_\n" foreach @{ $result };
5799
5800     close $fh;
5801 }
5802
5803
5804 sub script_plot_karyogram
5805 {
5806     # Martin A. Hansen, August 2007.
5807
5808     # Plot hits on karyogram.
5809
5810     my ( $in,        # handle to in stream
5811          $out,       # handle to out stream
5812          $options,   # options hash
5813        ) = @_;
5814
5815     # Returns nothing.
5816
5817     my ( %options, $record, @data, $fh, $result, %data_hash );
5818
5819     $options->{ "genome" }     ||= "human";
5820     $options->{ "feat_color" } ||= "black";
5821
5822     while ( $record = get_record( $in ) ) 
5823     {
5824         if ( $record->{ "CHR" } and $record->{ "CHR_BEG" } and $record->{ "CHR_END" } )
5825         {
5826             push @{ $data_hash{ $record->{ "CHR" } } }, [ $record->{ "CHR_BEG" }, $record->{ "CHR_END" }, $options->{ "feat_color" } ];
5827         }
5828
5829         put_record( $record, $out ) if not $options->{ "no_stream" };
5830     }
5831
5832     $result = Maasha::Plot::karyogram( \%data_hash, \%options );
5833
5834     $fh = write_stream( $options->{ "data_out" } );
5835
5836     print $fh $result;
5837
5838     close $fh;
5839 }
5840
5841
5842 sub script_plot_matches
5843 {
5844     # Martin A. Hansen, August 2007.
5845
5846     # Plot matches in 2D generating a dotplot.
5847
5848     my ( $in,        # handle to in stream
5849          $out,       # handle to out stream
5850          $options,   # options hash
5851        ) = @_;
5852
5853     # Returns nothing.
5854
5855     my ( $record, @data, $fh, $result, %data_hash );
5856
5857     $options->{ "direction" } ||= "both";
5858
5859     while ( $record = get_record( $in ) ) 
5860     {
5861         if ( defined $record->{ "Q_BEG" } and defined $record->{ "S_BEG" } and $record->{ "Q_END" } and $record->{ "S_END" } ) {
5862             push @data, $record;
5863         }
5864
5865         put_record( $record, $out ) if not $options->{ "no_stream" };
5866     }
5867
5868     $options->{ "title" }  ||= "plot_matches";
5869     $options->{ "xlabel" } ||= $data[ 0 ]->{ "Q_ID" };
5870     $options->{ "ylabel" } ||= $data[ 0 ]->{ "S_ID" };
5871
5872     $result = Maasha::Plot::dotplot_matches( \@data, $options, $BP_TMP );
5873
5874     $fh = write_stream( $options->{ "data_out" } );
5875
5876     print $fh "$_\n" foreach @{ $result };
5877
5878     close $fh;
5879 }
5880
5881
5882 sub script_length_vals
5883 {
5884     # Martin A. Hansen, August 2007.
5885
5886     # Determine the length of the value for given keys.
5887
5888     my ( $in,        # handle to in stream
5889          $out,       # handle to out stream
5890          $options,   # options hash
5891        ) = @_;
5892
5893     # Returns nothing.
5894
5895     my ( $record, $key );
5896
5897     while ( $record = get_record( $in ) ) 
5898     {
5899         foreach $key ( @{ $options->{ "keys" } } )
5900         {
5901             if ( $record->{ $key } ) {
5902                 $record->{ $key . "_LEN" } = length $record->{ $key };
5903             }
5904         }
5905
5906         put_record( $record, $out );
5907     }
5908 }
5909
5910
5911 sub script_sum_vals
5912 {
5913     # Martin A. Hansen, August 2007.
5914
5915     # Calculates the sums for values of given keys.
5916
5917     my ( $in,        # handle to in stream
5918          $out,       # handle to out stream
5919          $options,   # options hash
5920        ) = @_;
5921
5922     # Returns nothing.
5923
5924     my ( $record, $key, %sum_hash, $fh );
5925
5926     while ( $record = get_record( $in ) ) 
5927     {
5928         foreach $key ( @{ $options->{ "keys" } } )
5929         {
5930             if ( $record->{ $key } ) {
5931                 $sum_hash{ $key } += $record->{ $key };
5932             }
5933         }
5934
5935         put_record( $record, $out ) if not $options->{ "no_stream" };
5936     }
5937
5938     $fh = write_stream( $options->{ "data_out" } );
5939
5940     foreach $key ( @{ $options->{ "keys" } } ) {
5941         put_record( { $key . "_SUM" => $sum_hash{ $key } || 0 } , $fh );
5942     }
5943
5944     close $fh;
5945 }
5946
5947
5948 sub script_mean_vals
5949 {
5950     # Martin A. Hansen, August 2007.
5951
5952     # Calculate the mean of values of given keys.
5953
5954     my ( $in,        # handle to in stream
5955          $out,       # handle to out stream
5956          $options,   # options hash
5957        ) = @_;
5958
5959     # Returns nothing.
5960
5961     my ( $record, $key, %sum_hash, %count_hash, $mean, $fh );
5962
5963     while ( $record = get_record( $in ) ) 
5964     {
5965         foreach $key ( @{ $options->{ "keys" } } )
5966         {
5967             if ( $record->{ $key } )
5968             {
5969                 $sum_hash{ $key } += $record->{ $key };
5970                 $count_hash{ $key }++;
5971             }
5972         }
5973
5974         put_record( $record, $out ) if not $options->{ "no_stream" };
5975     }
5976
5977     $fh = write_stream( $options->{ "data_out" } );
5978
5979     foreach $key ( @{ $options->{ "keys" } } )
5980     {
5981         if ( $count_hash{ $key } ) {
5982             $mean = sprintf( "%.2f", ( $sum_hash{ $key } / $count_hash{ $key } ) );
5983         } else {
5984             $mean = "N/A";
5985         }
5986
5987         put_record( { $key . "_MEAN" => $mean } , $fh );
5988     }
5989
5990     close $fh;
5991 }
5992
5993
5994 sub script_median_vals
5995 {
5996     # Martin A. Hansen, March 2008.
5997
5998     # Calculate the median values of given keys.
5999
6000     my ( $in,        # handle to in stream
6001          $out,       # handle to out stream
6002          $options,   # options hash
6003        ) = @_;
6004
6005     # Returns nothing.
6006
6007     my ( $record, $key, %median_hash, $median, $fh );
6008
6009     while ( $record = get_record( $in ) ) 
6010     {
6011         foreach $key ( @{ $options->{ "keys" } } ) {
6012             push @{ $median_hash{ $key } }, $record->{ $key } if defined $record->{ $key };
6013         }
6014
6015         put_record( $record, $out ) if not $options->{ "no_stream" };
6016     }
6017
6018     $fh = write_stream( $options->{ "data_out" } );
6019
6020     foreach $key ( @{ $options->{ "keys" } } )
6021     {
6022         if ( $median_hash{ $key } ) {
6023             $median = Maasha::Calc::median( $median_hash{ $key } );
6024         } else {
6025             $median = "N/A";
6026         }
6027
6028         put_record( { $key . "_MEDIAN" => $median } , $fh );
6029     }
6030
6031     close $fh;
6032 }
6033
6034
6035 sub script_max_vals
6036 {
6037     # Martin A. Hansen, February 2008.
6038
6039     # Determine the maximum values of given keys.
6040
6041     my ( $in,        # handle to in stream
6042          $out,       # handle to out stream
6043          $options,   # options hash
6044        ) = @_;
6045
6046     # Returns nothing.
6047
6048     my ( $record, $key, $fh, %max_hash, $max_record );
6049
6050     while ( $record = get_record( $in ) ) 
6051     {
6052         foreach $key ( @{ $options->{ "keys" } } )
6053         {
6054             if ( $record->{ $key } )
6055             {
6056                 $max_hash{ $key } = $record->{ $key } if $record->{ $key } > $max_hash{ $key };
6057             }
6058         }
6059
6060         put_record( $record, $out ) if not $options->{ "no_stream" };
6061     }
6062
6063     $fh = write_stream( $options->{ "data_out" } );
6064
6065     foreach $key ( @{ $options->{ "keys" } } )
6066     {
6067         $max_record->{ $key . "_MAX" } = $max_hash{ $key };
6068     }
6069
6070     put_record( $max_record, $fh );
6071
6072     close $fh;
6073 }
6074
6075
6076 sub script_min_vals
6077 {
6078     # Martin A. Hansen, February 2008.
6079
6080     # Determine the minimum values of given keys.
6081
6082     my ( $in,        # handle to in stream
6083          $out,       # handle to out stream
6084          $options,   # options hash
6085        ) = @_;
6086
6087     # Returns nothing.
6088
6089     my ( $record, $key, $fh, %min_hash, $min_record );
6090
6091     while ( $record = get_record( $in ) ) 
6092     {
6093         foreach $key ( @{ $options->{ "keys" } } )
6094         {
6095             if ( defined $record->{ $key } )
6096             {
6097                 if ( exists $min_hash{ $key } ) {
6098                     $min_hash{ $key } = $record->{ $key } if $record->{ $key } < $min_hash{ $key };
6099                 } else {
6100                     $min_hash{ $key } = $record->{ $key }; 
6101                 }
6102             }
6103         }
6104
6105         put_record( $record, $out ) if not $options->{ "no_stream" };
6106     }
6107
6108     $fh = write_stream( $options->{ "data_out" } );
6109
6110     foreach $key ( @{ $options->{ "keys" } } )
6111     {
6112         $min_record->{ $key . "_MIN" } = $min_hash{ $key };
6113     }
6114
6115     put_record( $min_record, $fh );
6116
6117     close $fh;
6118 }
6119
6120
6121 sub script_upload_to_ucsc
6122 {
6123     # Martin A. Hansen, August 2007.
6124
6125     # Calculate the mean of values of given keys.
6126
6127     # This routine has developed into the most ugly hack. Do something!
6128
6129     my ( $in,        # handle to in stream
6130          $out,       # handle to out stream
6131          $options,   # options hash
6132        ) = @_;
6133
6134     # Returns nothing.
6135
6136     my ( $record, $file, $wib_file, $wig_file, $wib_dir, $fh_out, $i, $first, $format, $type, $columns, $append, $entry );
6137
6138     $options->{ "short_label" } ||= $options->{ 'table' };
6139     $options->{ "long_label" }  ||= $options->{ 'table' };
6140     $options->{ "group" }       ||= $ENV{ "LOGNAME" };
6141     $options->{ "priority" }    ||= 1;
6142     $options->{ "visibility" }  ||= "pack";
6143     $options->{ "color" }       ||= join( ",", int( rand( 255 ) ), int( rand( 255 ) ), int( rand( 255 ) ) );
6144     $options->{ "chunk_size" }  ||= 10_000_000_000;    # Due to 32-bit UCSC compilation really large tables cannot be loaded in one go.
6145
6146     $file   = "$BP_TMP/ucsc_upload.tmp";
6147     $append = 0;
6148     $first  = 1;
6149     $i      = 0;
6150
6151     $fh_out = Maasha::Common::write_open( $file );
6152
6153     while ( $record = get_record( $in ) ) 
6154     {
6155         put_record( $record, $out ) if not $options->{ "no_stream" };
6156
6157         if ( $record->{ "REC_TYPE" } eq "fixed_step" )
6158         {
6159             $format = "WIGGLE";
6160
6161             if ( $entry = Maasha::UCSC::Wiggle::biopiece2fixedstep( $record ) ) {
6162                 Maasha::UCSC::Wiggle::fixedstep_entry_put( $entry, $fh_out );
6163             }
6164         }
6165         elsif ( $record->{ "REC_TYPE" } eq "PSL" )
6166         {
6167             $format = "PSL";
6168
6169             Maasha::UCSC::psl_put_header( $fh_out ) if $first;
6170             Maasha::UCSC::psl_put_entry( $record, $fh_out );
6171             
6172             $first = 0;
6173         }
6174         elsif ( $record->{ "REC_TYPE" } eq "BED" and $record->{ "SEC_STRUCT" } )
6175         {
6176             # chrom chromStart  chromEnd    name    score   strand  size    secStr  conf 
6177
6178             $format  = "BED_SS";
6179
6180             print $fh_out join ( "\t",
6181                 $record->{ "CHR" },
6182                 $record->{ "CHR_BEG" },
6183                 $record->{ "CHR_END" } + 1,
6184                 $record->{ "Q_ID" },
6185                 $record->{ "SCORE" },
6186                 $record->{ "STRAND" },
6187                 $record->{ "SIZE" },
6188                 $record->{ "SEC_STRUCT" },
6189                 $record->{ "CONF" },
6190             ), "\n";
6191         }
6192         elsif ( $record->{ "REC_TYPE" } eq "BED" )
6193         {
6194             $format  = "BED";
6195             $columns = $record->{ "BED_COLS" };
6196
6197             if ( $entry = Maasha::UCSC::BED::biopiece2bed( $record, $columns ) ) {
6198                 Maasha::UCSC::BED::bed_entry_put( $entry, $fh_out, $columns, 1 );
6199             }
6200         }
6201         elsif ( $record->{ "REC_TYPE" } eq "PATSCAN" and $record->{ "CHR" } )
6202         {
6203             $format  = "BED";
6204             $columns = 6;
6205
6206             if ( $entry = Maasha::UCSC::BED::biopiece2bed( $record, $columns ) ) {
6207                 Maasha::UCSC::BED::bed_entry_put( $entry, $fh_out, $columns, 1 );
6208             }
6209         }
6210         elsif ( $record->{ "REC_TYPE" } eq "BLAST" and $record->{ "S_ID" } =~ /^chr/ )
6211         {
6212             $format  = "BED";
6213             $columns = 6;
6214
6215             $record->{ "SCORE" } = $record->{ "BIT_SCORE" } * 1000;
6216
6217             if ( $entry = Maasha::UCSC::BED::biopiece2bed( $record, $columns ) ) {
6218                 Maasha::UCSC::BED::bed_entry_put( $entry, $fh_out, $columns, 1 );
6219             }
6220         }
6221         elsif ( $record->{ "REC_TYPE" } eq "VMATCH" and $record->{ "S_ID" } =~ /^chr/i )
6222         {
6223             $format  = "BED";
6224             $columns = 6;
6225
6226             if ( $entry = Maasha::UCSC::BED::biopiece2bed( $record, $columns ) ) {
6227                 Maasha::UCSC::BED::bed_entry_put( $entry, $fh_out, $columns, 1 );
6228             }
6229         }
6230
6231         if ( $i == $options->{ "chunk_size" } )
6232         {
6233             close $fh_out;
6234
6235             if ( $format eq "BED" ) {
6236                 Maasha::UCSC::bed_upload_to_ucsc( $BP_TMP, $file, $options, $append );
6237             } elsif ( $format eq "PSL" ) {
6238                 Maasha::UCSC::psl_upload_to_ucsc( $file, $options, $append ); 
6239             }
6240
6241             unlink $file;
6242
6243             $first = 1;
6244
6245             $append = 1;
6246
6247             $fh_out = Maasha::Common::write_open( $file );
6248         }
6249
6250         $i++;
6251     }
6252
6253     close $fh_out;
6254
6255     if ( exists $options->{ "database" } and $options->{ "table" } )
6256     {
6257         if ( $format eq "BED" )
6258         {
6259             $type = "bed $columns";
6260
6261             Maasha::UCSC::bed_upload_to_ucsc( $BP_TMP, $file, $options, $append );
6262         }
6263         elsif ( $format eq "BED_SS" )
6264         {
6265             $type = "type bed 6 +";
6266         
6267             Maasha::UCSC::bed_upload_to_ucsc( $BP_TMP, $file, $options, $append );
6268         }
6269         elsif ( $format eq "PSL" )
6270         {
6271             $type = "psl";
6272
6273             Maasha::UCSC::psl_upload_to_ucsc( $file, $options, $append ); 
6274         }
6275         elsif ( $format eq "WIGGLE" )
6276         {
6277             $options->{ "visibility" } = "full";
6278
6279             $wig_file = "$options->{ 'table' }.wig";
6280             $wib_file = "$options->{ 'table' }.wib";
6281
6282             $wib_dir  = "$ENV{ 'HOME' }/ucsc/wib";
6283
6284             Maasha::Common::dir_create_if_not_exists( $wib_dir );
6285
6286             if ( $options->{ 'verbose' } ) {
6287                 `cd $BP_TMP && wigEncode $file $wig_file $wib_file`;
6288             } else {
6289                 `cd $BP_TMP && wigEncode $file $wig_file $wib_file > /dev/null 2>&1`;
6290             }
6291
6292             Maasha::Common::run( "mv", "$BP_TMP/$wib_file $wib_dir" );
6293
6294             unlink $file;
6295
6296             $file = $wig_file;
6297
6298             $type = "wig 0";
6299
6300             Maasha::UCSC::wiggle_upload_to_ucsc( $BP_TMP, $wib_dir, $file, $options );
6301         }
6302
6303         unlink $file;
6304
6305         Maasha::UCSC::ucsc_update_config( $options, $type );
6306     }
6307 }
6308
6309
6310 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
6311
6312
6313 sub grab_lookup
6314 {
6315     # Martin A. Hansen, November 2009.
6316
6317     # Uses keys from a lookup hash to search records. Optionally, a list of
6318     # keys can be given so the lookup is limited to these, also, flags
6319     # can be given to limit lookup to keys or vals only. Returns 1 if lookup
6320     # succeeded, else 0.
6321
6322     my ( $lookup_hash,   # hashref with patterns
6323          $record,        # hashref
6324          $keys,          # list of keys   - OPTIONAL
6325          $vals_only,     # only vals flag - OPTIONAL
6326          $keys_only,     # only keys flag - OPTIONAL
6327        ) = @_;
6328
6329     # Returns boolean.
6330
6331     if ( $keys )
6332     {
6333         map { return 1 if exists $lookup_hash->{ $record->{ $_ } } } @{ $keys };
6334     }
6335     else
6336     {
6337         if ( not $vals_only ) {
6338             map { return 1 if exists $lookup_hash->{ $_ } } keys %{ $record };
6339         }
6340
6341         if ( not $keys_only ) {
6342             map { return 1 if exists $lookup_hash->{ $record->{ $_ } } } keys %{ $record };
6343         }
6344     }
6345
6346     return 0;
6347 }
6348
6349
6350 sub grab_patterns
6351 {
6352     # Martin A. Hansen, November 2009.
6353
6354     # Uses patterns to match records containing the pattern as a substring.
6355     # Returns 1 if the record is matched, else 0.
6356
6357     my ( $patterns,   # list of patterns
6358          $record,     # hashref
6359          $keys,       # list of keys   - OPTIONAL
6360          $vals_only,  # only vals flag - OPTIONAL
6361          $keys_only,  # only keys flag - OPTIONAL
6362        ) = @_;
6363
6364     # Returns boolean.
6365
6366     my ( $pattern );
6367
6368     foreach $pattern ( @{ $patterns } )
6369     {
6370         if ( $keys )
6371         {
6372             map { return 1 if index( $record->{ $_ }, $pattern ) >= 0 } @{ $keys };
6373         }
6374         else
6375         {
6376             if ( not $vals_only ) {
6377                 map { return 1 if index( $_, $pattern ) >= 0 } keys %{ $record };
6378             }
6379
6380             if ( not $keys_only ) {
6381                 map { return 1 if index( $record->{ $_ }, $pattern ) >= 0 } keys %{ $record };
6382             }
6383         }
6384     }
6385
6386     return 0;
6387 }
6388
6389
6390 sub grab_regex
6391 {
6392     # Martin A. Hansen, November 2009.
6393
6394     # Uses regex to match records.
6395     # Returns 1 if the record is matched, else 0.
6396
6397     my ( $regex,      # regex to match
6398          $record,     # hashref
6399          $keys,       # list of keys   - OPTIONAL
6400          $vals_only,  # only vals flag - OPTIONAL
6401          $keys_only,  # only keys flag - OPTIONAL
6402        ) = @_;
6403
6404     # Returns boolean.
6405
6406     if ( $keys )
6407     {
6408         map { return 1 if $record->{ $_ } =~ /$regex/ } @{ $keys };
6409     }
6410     else
6411     {
6412         if ( not $vals_only ) {
6413             map { return 1 if $_ =~ /$regex/ } keys %{ $record };
6414         }
6415
6416         if ( not $keys_only ) {
6417             map { return 1 if $record->{ $_ } =~ /$regex/ } keys %{ $record };
6418         }
6419     }
6420
6421     return 0;
6422 }
6423
6424
6425 sub grab_eval
6426 {
6427     # Martin A. Hansen, November 2009.
6428
6429     # Test if the value of a given record key evaluates according
6430     # to a given operator. Returns 1 if eval is OK, else 0.
6431
6432     my ( $key,     # record key
6433          $op,      # operator
6434          $val,     # value
6435          $record,  # hashref
6436        ) = @_;
6437     
6438     # Returns boolean.
6439
6440     if ( defined $record->{ $key } ) 
6441     {
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 "<=" and $record->{ $key } <= $val );
6446         return 1 if ( $op eq "=" and $record->{ $key } == $val );
6447         return 1 if ( $op eq "!=" and $record->{ $key } != $val );
6448         return 1 if ( $op eq "eq" and $record->{ $key } eq $val );
6449         return 1 if ( $op eq "ne" and $record->{ $key } ne $val );
6450     }
6451
6452     return 0;
6453 }
6454
6455
6456 sub read_stream
6457 {
6458     # Martin A. Hansen, July 2007.
6459
6460     # Opens a stream to STDIN or a file,
6461
6462     my ( $path,   # path - OPTIONAL
6463        ) = @_;
6464
6465     # Returns filehandle.
6466
6467     my ( $fh );
6468
6469     if ( not -t STDIN ) {
6470         $fh = Maasha::Common::read_stdin();
6471     } elsif ( not $path ) {
6472 #        Maasha::Common::error( qq(no data stream) );
6473     } else {
6474         $fh = Maasha::Common::read_open( $path );
6475     }
6476     
6477 #    $fh->autoflush(1) if $fh;  # Disable file buffer for debugging.
6478
6479     return $fh;
6480 }
6481
6482
6483 sub write_stream
6484 {
6485     # Martin A. Hansen, August 2007.
6486
6487     # Opens a stream to STDOUT or a file.
6488
6489     my ( $path,   # path          - OPTIONAL
6490          $gzip,   # compress data - OPTIONAL
6491        ) = @_;
6492
6493     # Returns filehandle.
6494
6495     my ( $fh );
6496
6497     if ( $path ) {
6498         $fh = Maasha::Common::write_open( $path, $gzip );
6499     } else {
6500         $fh = Maasha::Common::write_stdout();
6501     }
6502
6503     return $fh;
6504 }
6505
6506
6507 sub get_record
6508 {
6509     # Martin A. Hansen, July 2007.
6510
6511     # Reads one record at a time and converts that record
6512     # to a Perl data structure (a hash) which is returned.
6513
6514     my ( $fh,   # handle to stream
6515        ) = @_;
6516
6517     # Returns a hash. 
6518
6519     my ( $block, @lines, $line, $key, $value, %record );
6520
6521     local $/ = "\n---\n";
6522
6523     $block = <$fh>;
6524
6525     chomp $block;
6526
6527     return if not defined $block;
6528
6529     @lines = split "\n", $block;
6530
6531     foreach $line ( @lines )
6532     {
6533         ( $key, $value ) = split ": ", $line, 2;
6534
6535         $record{ $key } = $value;
6536     }
6537
6538     return wantarray ? %record : \%record;
6539 }
6540
6541
6542 sub put_record
6543 {
6544     # Martin A. Hansen, July 2007.
6545
6546     # Given a Perl datastructure (a hash ref) emits this to STDOUT or a filehandle.
6547
6548     my ( $data,   # data structure
6549          $fh,     # file handle - OPTIONAL
6550        ) = @_;
6551
6552     # Returns nothing.
6553
6554     if ( scalar keys %{ $data } )
6555     {
6556         if ( $fh )
6557         {
6558             map { print $fh "$_: $data->{ $_ }\n" } keys %{ $data };
6559             print $fh "---\n";
6560         }
6561         else
6562         {
6563             map { print "$_: $data->{ $_ }\n" } keys %{ $data };
6564             print "---\n";
6565         }
6566     }
6567
6568     undef $data;
6569 }
6570
6571
6572 sub getopt_files
6573 {
6574     # Martin A. Hansen, November 2007.
6575
6576     # Extracts files from an explicit GetOpt::Long argument
6577     # allowing for the use of glob. E.g.
6578     # --data_in=test.fna
6579     # --data_in=test.fna,test2.fna
6580     # --data_in=*.fna
6581     # --data_in=test.fna,/dir/*.fna
6582
6583     my ( $option,   # option from GetOpt::Long
6584        ) = @_;
6585
6586     # Returns a list.
6587
6588     my ( $elem, @files );
6589
6590     foreach $elem ( split ",", $option )
6591     {
6592         if ( -f $elem ) {
6593             push @files, $elem;
6594         } elsif ( $elem =~ /\*/ ) {
6595             push @files, glob( $elem );
6596         }
6597     }
6598
6599     return wantarray ? @files : \@files;
6600 }
6601
6602
6603 sub sig_handler
6604 {
6605     # Martin A. Hansen, April 2008.
6606
6607     # Removes temporary directory and exits gracefully.
6608     # This subroutine is meant to be run always as the last
6609     # thing even if a script is dies or is interrupted
6610     # or killed. 
6611
6612     my ( $sig,   # signal from the %SIG
6613        ) = @_;
6614
6615     # print STDERR "signal->$sig<-\n";
6616
6617     chomp $sig;
6618
6619     sleep 1;
6620
6621     if ( -d $BP_TMP )
6622     {
6623         if ( $sig =~ /MAASHA_ERROR/ ) {
6624             print STDERR "\nProgram '$script' had an error"                     . "  -  Please wait for temporary data to be removed\n";
6625         } elsif ( $sig eq "INT" ) {
6626             print STDERR "\nProgram '$script' interrupted (ctrl-c was pressed)" . "  -  Please wait for temporary data to be removed\n";
6627         } elsif ( $sig eq "TERM" ) {
6628             print STDERR "\nProgram '$script' terminated (someone used kill?)"  . "  -  Please wait for temporary data to be removed\n";
6629         } else {
6630             print STDERR "\nProgram '$script' died->$sig"                       . "  -  Please wait for temporary data to be removed\n";
6631         }
6632
6633         clean_tmp();
6634     }
6635
6636     exit( 0 );
6637 }
6638
6639
6640 sub clean_tmp
6641 {
6642     # Martin A. Hansen, July 2008.
6643
6644     # Cleans out any unused temporary files and directories in BP_TMP.
6645
6646     # Returns nothing.
6647
6648     my ( $tmpdir, @dirs, $curr_pid, $dir, $user, $sid, $pid );
6649
6650     $tmpdir = $ENV{ 'BP_TMP' } || Maasha::Common::error( 'No BP_TMP variable in environment.' );
6651
6652     $curr_pid = Maasha::Common::get_processid();
6653
6654     @dirs = Maasha::Common::ls_dirs( $tmpdir );
6655
6656     foreach $dir ( @dirs )
6657     {
6658         if ( $dir =~ /^$tmpdir\/(.+)_(\d+)_(\d+)_bp_tmp$/ )
6659         {
6660             $user = $1;
6661             $sid  = $2;
6662             $pid  = $3;
6663
6664             if ( $user eq Maasha::Common::get_user() )
6665             {
6666                 if ( not Maasha::Common::process_running( $pid ) )
6667                 {
6668                     # print STDERR "Removing stale dir: $dir\n";
6669                     Maasha::Common::dir_remove( $dir );
6670                 }
6671                 elsif ( $pid == $curr_pid )
6672                 {
6673                     # print STDERR "Removing current dir: $dir\n";
6674                     # Maasha::Common::dir_remove( $dir );
6675                 }
6676             }
6677         }
6678     }
6679 }
6680
6681
6682 END
6683 {
6684     clean_tmp();
6685 }
6686
6687
6688 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
6689
6690 1;
6691
6692 __END__