#!/usr/bin/perl
$file="webpages.bin";
$num=0;
$vshift=16;
$fnum=256;

open(IN, $file);
binmode(IN);

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 " ";
  }
  for($j=12;$j<19;$j++){
    printf (" %02x",ord(substr($buf,$j,1)));
  }
  $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;
  }
}

# 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;
    }
  }
}

for($i=0;$i<$num;$i++){
  if($i!=0){
    sysread(IN,$buf,$nstart[$i]-$nstart[$i-1]-$nsize[$i-1]);
  }
  sysread(IN,$buf,$nsize[$i]);
#  $nname[$i] =~ s/\\/\//g;
#  $spos=0;
#  while(index($nname[$i],"\/",$spos) > 0){
#    $ndir=substr($nname[$i],0,index($nname[$i],"\/",$spos));
#    $spos=index($nname[$i],"\/",$spos)+1;
#    unless(-d $ndir){
#      mkdir($ndir);
#    }
#  }
  
#  printf "$nname[$i]\n";
  open(OUT, "> $nname[$i]");
  binmode(OUT);
  print OUT $buf;
  close(OUT);
}

close(IN);
