#!/usr/bin/perl -w
use strict;

if($#ARGV < 1) {
	print <<EOF;
usage: $0 sdfile[.gz|.bz2|.lzma] j
j = number of mol in one chunk
EOF
	exit 0;
}

my $filename = $ARGV[0];		# read the first argument as filename
@ARGV = map {
	/\.(gz|Z)$/ ? "gunzip < $_ |" :
	/\.bz2$/ ? "bunzip2 < $_ |" :
	/\.lzma$/ ? "unlzma < $_ |" : $_
} @ARGV;

open(F, shift(@ARGV));	
my $numberPerChunk = shift(@ARGV);	# next is the number of mol in one chunk in the command line
my $count = 1;				# the actual counter
my $chunkCount = 1;
my $output = "$filename.$chunkCount";

open(my $fh, '>>', $output) or die "Could not open file '$output' $!";

while(<F>) {
	if($count == $numberPerChunk) {	# if we are at the requested chunk count
		close $fh;
		print "$output file created\n"; 
		$count = 1;
		++$chunkCount;
		$output = "$filename.$chunkCount";
		open($fh, '>>', $output) or die "Could not open file '$output' $!";
	} 

	print $fh "$_";
	if(/\$\$\$\$/){			# at the very last line of the record
		$count++;
	}
}
close(F);
