<?php

require_once('BitStream.php');

$marker_name_table =
  array(
0xD8 => 'SOI(Start of Image)',
    
0xE0 => 'APP0',
    
0xDB => 'DQT',
    
0xC4 => 'DHT',
    
0xC0 => 'SOF0',
    
0xC1 => 'SOF1',
    
0xDD => 'DRI',
    
0xDA => 'SOS',
    
0xD9 => 'EOT(End Of Immage)',
    
0xE0 => 'APP0',
    );

list(
$program$file) = $argv;

if (! 
is_readable($file)) {
  
fprintf(STDERR"Cant' read file($file)\n");
  exit(
1);
}

$data file_get_contents($file);

$bs = new BitStream($data);

while ((
$marker1 $bs->getByte()) == 0xFF) {
  
$marker2 $bs->getByte();
  
printf("MARKER: %s(FF%02X)\n"$marker_name_table{$marker2}, $marker2);
  switch(
$marker2) {
  case 
'0xD8'// SOI Start
  
case '0xD9'// EOI End
  
break;
  default:
    
$length $bs->getBytesBE(2);
    
$data $bs->getStrings($length 2);
    print 
"length=$length\n";
  }
}

$byteoffset $bs->getByteOffset();
printf("END: %02X, 0x%x(=%d)\n"$marker1$byteoffset$byteoffset);
for(
$i=0$i<10$i++) {
  
printf(" %02X"$bs->getByte());
 }
printf("\n");


/*
  case '0xDA'; // SOS
    $length = $bs->getBytesBE(2);
    $n_component = $bs->getByte();
    print "length=$length n_component=$n_component\n";
    for ($i=0; $i<$n_component; $i++) {
      $component_id = $bs->getByte();
      $huffman_code_num = $bs->getByte();
      print("\tcomponent_id=$component_id huffman_code_num=$huffman_code_num\n");
    }
    $spectrum1 = $bs->getByte();
    $spectrum2 = $bs->getByte();
    $spectrum3 = $bs->getByte();
    print "spectrum=$spectrum1:$spectrum2:$spectrum3\n";
  break;

 */