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