<?php
##
## exif file rename by san2@2010.11.03
##
## - 2011.03.17: ms rename to 'i'
## - 2010.11.03: new build
##
## usage: php this_filename [--test|--preview] <dirname>
##
function str2float($str)
{
  list(
$a,$b) = explode('/',$str);
  
$float sprintf('%.1f',$a/$b);

  return 
$float;
}

## check exif module
##
if(!function_exists('exif_read_data'))
{
  echo 
'Your PHP version is not support EXIF'."\n"// error
  
exit(1);
}

## check argv
##
if(preg_match(';--(test|preview);i',$_SERVER['argv'][1]))
{
  
$preview TRUE;
  
$path preg_replace(';/+$;','',$_SERVER['argv'][2]);
}
else 
$path preg_replace(';/+$;','',$_SERVER['argv'][1]);

if(
is_dir($path)) $path $path.'/*';

$files glob($path);

if(!
$files)
{
  echo 
'usage: php '.$_SERVER['argv'][0].' [--test|--preview] <dirname>'."\n"// error_log() not work in win32
  
exit(1); // error
}

echo 
"target : $path \n";

foreach(
$files AS $fname)
{
  if(
is_dir($fname)) continue;
  if(!
$exif exif_read_data($fname,IFD0+EXIF,TRUE)) continue;

  
$model str_replace(' ','.',$exif['IFD0']['Model']);
  
$iso $exif['EXIF']['ISOSpeedRatings'];
  
$exptime $exif['EXIF']['ExposureTime'];
  
$flength $exif['EXIF']['FocalLength'];
  
$fnumber $exif['EXIF']['FNumber'];

  if(!
$model || !$iso) continue;

  
## exposure time
  ##
  
if(preg_match(';/1$;',$exptime)) $exptime preg_replace(';/1$;','',$exptime).'s';
  else if(
preg_match(';^1/;',$exptime)) $exptime preg_replace(';^1/;','',$exptime).'i';
  else 
$exptime str2float($exptime).'s';

  
## focal length
  ##
  
if(preg_match(';/1$;',$flength)) $flength preg_replace(';/1$;','',$flength);
  else 
$flength str2float($flength);
  
  
## F number
  ##
  
if(preg_match(';^0/;',$fnumber)) $fnumber 0;
  else 
$fnumber str2float($fnumber);

  if(
$model$model .= '-';
  if(
$iso$iso 'ISO'.$iso.'-';
  if(
$exptime$exptime .= '-';

  
$flength $flength $flength.'mm-' '';
  
$fnumber $fnumber 'F'.$fnumber.'-' '';
  
$addstr preg_replace(';[-]+$;','',$model.$iso.$exptime.$flength.$fnumber);

  
$tail substr(strrchr($fname,'.'),1);
  
$toname preg_replace(";\.$tail$;",'-'.$addstr.'.'.$tail,$fname);

  
//if($preview) echo "$fname => $toname\n";
  
if($previewprintf('%-40s => %s'."\n",$fname,$toname);
  else
  {
    
$r rename($fname,$toname);
    if(
$rprintf('%-40s => %s'."\n",$fname,$toname);
    else 
printf('%-40s <= %s'."\n",$fname,'rename ERROR');
  }
}

?>