#!/usr/bin/perl

open(CALC, "calc-reciprocal-out.txt") || die "failed to open calc: $!\n";

$file="../../../programs/pluto/modulus_reciprocals.c";
open(RECIPROCALS, ">$file") || die "Can not write to $file: $!\n";

print RECIPROCALS "/*\n * this file generated by testing/crypto/reducent-01/gen-reciprocal.pl \n";
print RECIPROCALS " * ";
print RECIPROCALS "by ".$ENV{'LOGNAME'}." on ";
print RECIPROCALS `date`;
print RECIPROCALS " */\n\n";

while(<CALC>) {
  chop;

  if(/^Group (.*) Tries/) {
    $groupnum=$1;
    next;
  }

  if(/^Reciprocal: (.*)$/) {
    $reciprocal=$1;

    $reciprocal =~ y/a-f/A-Z/;

    $bitlen = length($reciprocal) * 4;
    $i = 0;
    $str = substr($reciprocal, 0, 2);
    substr($reciprocal, 0, 2)="";
    print RECIPROCALS sprintf("u_char modp%d_recvalue[] = { \n  ", $bitlen);
    while(length($str) > 0) {
      print RECIPROCALS "0x$str";
      $i++;
      $str = substr($reciprocal, 0, 2);
      substr($reciprocal, 0, 2)="";

      if(length($str)) {
	print RECIPROCALS ", ";
      }
      if($i==8 && length($str)) {
	print RECIPROCALS "\n  ";
	$i=0;
      }

    }
    print RECIPROCALS " };\n";
    print RECIPROCALS sprintf("chunk_t modp%d_reciprocal = { .ptr = modp%d_recvalue,", $bitlen, $bitlen);
    print RECIPROCALS "   .len = ".($bitlen/8)."};\n\n";
  }
}
