#
# Split a fasta file into chunks of about the same size.
#

use strict;
use Getopt::Long::Descriptive;
use File::Temp;

my($opt, $usage) = describe_options("%c %o fasta-input output-basename size ",
				    ["help|h", "show this help message"]);
print($usage->text), exit 0 if $opt->help;
die($usage->text) if @ARGV < 1;

my $nr_file = shift;
my $out_base = shift;
my $block_size = shift;

open(F, "<", $nr_file) or die "Cannot open $nr_file: $!";

my $out_idx = 1;
my $out_file = sprintf("$out_base%04d", $out_idx++);
open(OUT, ">", $out_file) or die "Cannot write $out_file: $!";
my $cur_size = 0;

while (<F>)
{
    if (/^>/)
    {
	if ($cur_size > $block_size)
	{
	    close(OUT);
	    my $out_file = sprintf("$out_base%04d", $out_idx++);
	    open(OUT, ">", $out_file) or die "Cannot write $out_file: $!";
	    $cur_size = 0;
	}
    }
    print OUT $_;
    $cur_size += length($_);
}
close(OUT);
close(F);
