#!/usr/bin/perl
$file="firmware-pci-jp-V01033B";
$num=0;
$vshift0=0x37;
$vshift1=0x370df;
$vshift2=0x29;
$fnum=47;

open(IN, $file);
binmode(IN);
sysread(IN,$buf,$vshift0);

sysread(IN,$buf,$vshift1);
open(OUT, "> code.bin");
binmode(OUT);
print OUT $buf;
close(OUT);

sysread(IN,$buf,$vshift2);
#$fnum=ord(substr($buf,15,1))*256+ord(substr($buf,14,1));
print "$fnum files\n";

for($i=0;$i<$fnum;$i++){
  sysread(IN,$buf,32);
  for($j=0;$j<13;$j++){
    if(ord(substr($buf,$j,1))==0){
      last;
    }
  }
  $fn=substr($buf,0,$j);
  printf "$fn";
  $nname[$num]=$fn;
  for($j=0;$j<13-length($fn);$j++){
    print " ";
  }
#  for($j=20;$j<32;$j++){
#    printf "%02x ",ord(substr($buf,$j,1));
#  }
  $nsize[$num]=ord(substr($buf,22,1))*256*256+
               ord(substr($buf,21,1))*256+
               ord(substr($buf,20,1));
  $nstart[$num]=ord(substr($buf,26,1))*256*256+
                ord(substr($buf,25,1))*256+
                ord(substr($buf,24,1));
  $nflag[$num]=ord(substr($buf,28,1));
  printf (" %03d %03d",$nstart[$num],$nsize[$num]);
  if($nflag[$num]==1){
    print " gzip";
  }
  $num++;
  printf "\n";
}

for($i=0;$i<$num;$i++){
  if($nsize[$i]==0){
    next;
  }
  sysread(IN,$buf,$nsize[$i]);
#  printf "$nname[$i]\n";
  open(OUT, "> $nname[$i]");
  binmode(OUT);
  print OUT $buf;
  close(OUT);
  sysread(IN,$buf,1);
}

close(IN);
