#!/usr/local/bin/php
<?php
/*
 *  Crop images in a stack to maximum common size.
 *
 * Usage: cropstack.php files...
 *
 *  $Id: cropstack.php,v 1.3 2018/06/30 03:28:58 grog Exp grog $
 *
 *  TODO: Add -v (verbose) option
 */

$verbose = 0;
$width = 99999;
$height = 99999;
$maxwidth = 0;
$maxheight = 0;
$widths = array ();
$heights = array ();
for ($arg = 1; $arg < $argc; $arg++)			/* go through parms */
  {
  $identity = explode (" ", system ("identify $argv[$arg]"));
  $imagesize = $identity [3];
  echo "=== imagesize $argv[$arg] $imagesize\n";
  $widths [$arg] = preg_replace ("/x.*/", "", $imagesize);
  $heights [$arg] =  preg_replace ("/.*x/", "", $imagesize);
  if ($verbose)
    echo "===== height $heights[$arg]\n";
  /* Find the maximum commen dimensions */
  if ($width > $widths [$arg])
	  $width = $widths [$arg];
  if ($height > $heights [$arg])
	  $height = $heights [$arg];
  /*
   * And note what the maxima are.  We may not need to do anything.
   */
  if ($maxwidth < $widths [$arg])
	  $maxwidth = $widths [$arg];
  if ($maxheight < $heights [$arg])
	  $maxheight = $heights [$arg];
  /* printf ("XXX width $width, height $height\n"); */
  }
/*
 * OK.  Do we need to do anything?
 */
if (($width < $maxwidth) || ($height < $maxheight))
  {
  for ($arg = 1; $arg < $argc; $arg++)			/* go through parms */
	{
/*	echo "=== arg $arg width $widths[$arg] height $heights[$arg]\n"; */
	if (($widths [$arg] > $width)
		|| ($heights [$arg] > $height) )			/* yes */
	  {
	  echo "==== Reducing image $argv[$arg] from $widths[$arg],$heights[$arg] to $width,$height\n";
	  system ("mv $argv[$arg]  $argv[$arg].tmp");
/*	  echo ("==== convert -crop $width" . "x$height $argv[$arg].tmp $argv[$arg]\n"); */
	  system ("convert -crop $width" . "x$height $argv[$arg].tmp $argv[$arg]");
	  system ("exifcopy $argv[$arg].tmp $argv[$arg]");
	  system ("rm $argv[$arg].tmp");
	  }
	}
  }
else
  printf ("=== No adjustment needed\n");
