<?php
require_once "/main.inc";
define("CHUNKSIZE", 512);

function imagexy($im)
{
	return array(imagesx($im), imagesy($im));
}

class ImageScrambler
{
	public $source=null;
	public $seed=null;
	
	public function __construct($image, $rndr)
	{
		$this->source=$image;
		$this->seed = $rndr;
		
		srand($rndr);
	}
	private function getAreas()
	{
		$v = imagexy($this->source);
		$xv = $v[0] % CHUNKSIZE;
		$yv = $v[1] % CHUNKSIZE;
		$ret = array();
		$i=0;
		for($y=0;$i<$yv;$y++)
		{
			for($x=0;$x<$xv;$x++)
			{
				$ret[$i++] = array($x*CHUNKSIZE, $y*CHUNKSIZE,CHUNKSIZE,CHUNKSIZE);
			}
		}
		return $ret;
	}
	private function _swap($ar,$i,$j)
	{
		$cp = $ar[$i];
		$ar[$i] = $ar[$j];
		$ar[$j] = $cp;
	}
	private function scrambleArea($ar)
	{
		for($i=count($ar)-1;$i>=0;$i--)
		{
			$this->_swap($ar, $i, rand(0, $i));
		}
		return $ar;
	}
	
	public function scramble()
	{
		$area = $this->getAreas();
		$sarea = $this->scrambleArea($area);
		$nw = imagecreate(imagesx($this->source), imagesy($this->source));
		for($i=0;count($area);$i+=2)
		{
			imagecopy($nw, $this->source, $sarea[$i+1][0], $sarea[$i+1][1], $sarea[$i][0], $sarea[$i][1],CHUNKSIZE,CHUNKSIZE);
		}
		imagedestroy($this->source);
		$this->source=$nw;
		return $sarea;
	}
	public function destroy()
	{
		imagedestroy($this->$source);
	}
}
?>