<?php
header("Content-type: image/JPEG");
set_error_handler ('my_error_handler');


function my_error_handler ($errno, $errstr, $errfile, $errline) {
       // other stuff... 
    //
}

// Image Resize
function createthumb($IMAGE_SOURCE,$THUMB_X,$THUMB_Y){
  //$BACKUP_FILE = $OUTPUT_FILE . "_backup.jpg";
  //copy($IMAGE_SOURCE,$BACKUP_FILE);
  $IMAGE_PROPERTIES = GetImageSize($IMAGE_SOURCE);
  if (!$IMAGE_PROPERTIES[2] == 2) {
    return(0);
  } else {
    $SRC_IMAGE = ImageCreateFromJPEG($IMAGE_SOURCE);
    $SRC_X = ImageSX($SRC_IMAGE);
    $SRC_Y = ImageSY($SRC_IMAGE);
    if (($THUMB_Y == "0") && ($THUMB_X == "0")) {
      return(0);
    } elseif ($THUMB_Y == "0") {
      $SCALEX = $THUMB_X/($SRC_X-1);
      $THUMB_Y = $SRC_Y*$SCALEX;
    } elseif ($THUMB_X == "0") {
      $SCALEY = $THUMB_Y/($SRC_Y-1);
      $THUMB_X = $SRC_X*$SCALEY;
    }
    $THUMB_X = (int)($THUMB_X);
    $THUMB_Y = (int)($THUMB_Y);
    $DEST_IMAGE = imagecreatetruecolor($THUMB_X, $THUMB_Y);
    //unlink($BACKUP_FILE);
    if (!imagecopyresized($DEST_IMAGE, $SRC_IMAGE, 0, 0, 0, 0, $THUMB_X, $THUMB_Y, $SRC_X, $SRC_Y)) {
	imagedestroy($dest_image);
      return $SRC_IMAGE;
    } else {
      imagedestroy($SRC_IMAGE);
        return $DEST_IMAGE;
      }
    }
}





if(isset($_REQUEST['numimages'])){
  $imageCount = (int)$_REQUEST['numimages'];
} else {
  $imageCount = 2;
}
$square=sqrt($imageCount);
if ($imageCount ==12) {
  $rowMod=1;
  $colMod=1;
  $im=imagecreatetruecolor(3*640,4*480);
  for ($currentImage =1; $currentImage <= $imageCount; $currentImage++){
  $row=ceil(($currentImage/3));
  $col=($currentImage-1)%3+1;
  //echo("row:{$row} col:{$col}");  
  $currentImageName="http://blue.caad.ed.ac.uk/branded/SL/imagessquare/mobileImage{$currentImage}.jpg";
  
  //if (remoteFileExists($currentImageName)){
    //echo($currentImageName);
	 $tempImage=createthumb($currentImageName,640,480,$currentImageName);
	 imagecopy($im,$tempImage,640*($col-1),480*($row-1),0,0,640,480);
	 imagedestroy($tempImage);
  //}
}

} else {
$rowMod=0;
$colMod=0;

$im = imagecreatetruecolor($square * 640, $square * 480)
    or die("Cannot Initialize new GD image stream");
for ($currentImage =1; $currentImage <= $imageCount; $currentImage++){
  $row=ceil(($currentImage/$square));
  $col=($currentImage-1)%$square+1;
  //echo("row:{$row} col:{$col}");  
  $currentImageName="http://blue.caad.ed.ac.uk/branded/SL/images/mobileImage{$currentImage}.jpg";
  
  //if (remoteFileExists($currentImageName)){
    //echo($currentImageName);
	 $tempImage=createthumb($currentImageName,640,480,$currentImageName);
	 imagecopy($im,$tempImage,640*($col-1),480*($row-1),0,0,640,480);
	 imagedestroy($tempImage);
  //}
}

}


imagejpeg($im);
imagedestroy($im);


?>
