#!/usr/bin/perl
$code="xx";
$st=0;
while(<>){
    if ($st == 0 &&  getbegcode($_,$code) ){
	open(HDLR,"> $code");
	$st = 1;
    }
    elsif ($st == 1){
        if (getendcode($_)){
	    $st = 2;
	}
	else {
	    print HDLR $_;
	}
    }
    elsif ($st == 2 && ($newcode = getbegcode($_,$code)) ){
	print "newcode:$newcode\n$code\n";
	if ($newcode == 1){
	    close HDLR;
            open (HDLR, "> $code");
            $st = 1;
	}
	else{
	    $st = 1;
	}
    }
}
close(HDLR) if ($st == 1);


sub getbegcode{
    if ($_[0] =~ /^\s*\\begin\{code\}\s*%\s*file\s*:\s*\b(.*)\s*$/){
	$aux = $1;
	print "matched:\n$aux\n$code\n";
	return 2 if  ($code =~ /^$aux$/);
        print "matched:1\n";
        $_[1] = $aux;
        return 1;
    }
    else{
        #print $_[0];
	return 0;
    }
}

sub getendcode{
    return 1 if ($_[0] =~ /^\s*\\end\{code\}/);
    return 0;
}
