#!/usr/bin/perl
$file="fw.bin";
$num=0;
$vshift=0x43550;
$fnum=255;

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

for($i=0;$i<$fnum;$i++){
  sysread(IN,$buf,32);
  for($j=0;$j<12;$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++){
    printf " ";
  }
  $nsize[$num]=ord(substr($buf,14,1))*256*256+
               ord(substr($buf,13,1))*256+ord(substr($buf,12,1));
  $nstart[$num]=$vshift+ord(substr($buf,18,1))*256*256+
                ord(substr($buf,17,1))*256+ord(substr($buf,16,1));
  printf (" %03d %03d",$nstart[$num],$nsize[$num]);
  $num++;
  printf "\n";
  if(substr($buf,31,1)eq"E"){
    last;
  }
}
close(IN);

# sort file
for($i=0;$i<$num-1;$i++){
  for($j=0;$j<$num-$i-1;$j++){
    if($nstart[$j]>$nstart[$j+1]){
      $tmpname=$nname[$j];
      $tmpstart=$nstart[$j];
      $tmpsize=$nsize[$j];
      $nname[$j]=$nname[$j+1];
      $nstart[$j]=$nstart[$j+1];
      $nsize[$j]=$nsize[$j+1];
      $nname[$j+1]=$tmpname;
      $nstart[$j+1]=$tmpstart;
      $nsize[$j+1]=$tmpsize;
    }
  }
}

open(IN, $file);
binmode(IN);
for($i=0;$i<$num;$i++){
  if($i==0){
    sysread(IN,$buf,$nstart[$i]);
  }else{
    sysread(IN,$buf,$nstart[$i]-$nstart[$i-1]-$nsize[$i-1]);
  }
  sysread(IN,$buf,$nsize[$i]);
  
  open(OUT, "> $nname[$i]");
  binmode(OUT);
  print OUT $buf;
  close(OUT);
}

close(IN);
