#!/usr/bin/env perl

#
# Copyright (C) Nicolas Thierry-Mieg, 2009.
#
#
# This is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This script is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this script; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA


# take as argument an STD design file.
# create several partial STD design files in current dir:
# each file has q*q*$partsPerBatch variables (starting at 0),
# there are as many pools as in the original STD design,
# and the pools are those represented by the correct $partsPerBatch 
# q**2-blocks.

use strict ;
use warnings ;


# number of q**2-blocs in a partial design (output) file
# for building micro-pools: $partsPerBatch = 1
# for decoding the 384 pools, use 6 and for the 1536 use 2
my $partsPerBatch = 6 ;

(@ARGV != 1) && die "need one arg: an STD design file\n" ;

my $stdFile = $ARGV[0] ;

($stdFile =~ /STD\.n(\d+)\.q(\d+)\.k(\d+)$/) 
    || die "cannot parse name of $stdFile\n" ;

my ($n,$q,$k) = ($1,$2,$3) ;
my $baseName = "STD.n$n.q$q.k$k" ;

my $outDir = "$baseName.parts$partsPerBatch/" ;
(-e $outDir) && die "$outDir already exists, (re)move it\n" ;
system("mkdir $outDir") ;

open(INPUT, "$stdFile") || die "cannot open $stdFile for reading\n" ;

while(<INPUT>)
{
    chomp ;
    
    my @vars = split(/:/,$_) ;

    my $part = 1 ;
    open(OUT, ">>$outDir/$baseName.part$part") || die "cannot open $outDir/$baseName.part$part for appending\n"  ;
    
    while(defined(my $var = shift(@vars)))
    {
	if ($var < $q*$q*$part*$partsPerBatch)
	{
	    $var -= $q*$q*($part-1)*$partsPerBatch ;
	    print OUT "$var:" ;
	    # if no more vars, add newline to last part file
	    (@vars == 0) && print OUT "\n" ;
	}

	else
	{
	    print OUT "\n" ;
	    $part++ ;
	    close(OUT) ;
	    open(OUT, ">>$outDir/$baseName.part$part") || die  "cannot open $outDir/$baseName.part$part for appending\n";
	    $var -= $q*$q*($part-1)*$partsPerBatch ;
	    print OUT "$var:" ;
	}
    }

    close(OUT) ;
    
}


