<?php

$rs = shell_exec('echo %CD%');
define('BAT_FOLDER', trim($rs));
define('DIR_ORIGINAL', 'images_original');
define('DIR_COMPRESSED', 'images_compressed');
define('CONVERT', __DIR__.'/ImageMagick/convert.exe');
define('QUALITY', (int) @file_get_contents(__DIR__. '/../compress.txt'));
define('LINEBREAK', "\r\n");

if (QUALITY <= 0 || QUALITY > 100)
	die('Invalid compression value inside compress.txt. Please select a value between 1 and 100.'.LINEBREAK);

echo "Starting compressing at quality " . QUALITY .'%.'.LINEBREAK;

process_images();

echo "Compression finished!".LINEBREAK;
echo "You can close this window.".LINEBREAK;
echo "Compressed images are located in the \"images_compressed\" folder.".LINEBREAK;

function process_images($dir = '') {
	$list = scandir2(DIR_ORIGINAL.'/'.$dir);
	foreach ($list as $f) {
		if ($f == 'Thumbs.db') continue;
		$path = $dir .'/'. $f;
		if (is_dir(DIR_ORIGINAL.'/'.$path)) {
			if (!is_dir(DIR_COMPRESSED.'/'.$path))
				mkdir(DIR_COMPRESSED.'/'.$path);
			process_images($path);
		}
		else {
            if (!preg_match('/(png|jpg|jpeg)$/i', $f)) {
                die('Not an image : "'.DIR_ORIGINAL.'/'.$f .'". Skipped.'.LINEBREAK);
				continue;
			}
			
			$full_path_file = BAT_FOLDER . '/' . DIR_ORIGINAL.$path;
			$compressed = str_replace(DIR_ORIGINAL. '/', DIR_COMPRESSED. '/', $full_path_file);
			$exec = '"'.CONVERT.'" -quality '.QUALITY.'% "'.$full_path_file.'" "'.$compressed.'"';
			//var_dump($exec);die;
			shell_exec($exec);
			echo "Compressing \"" .substr($path, 1).'"...'.LINEBREAK;
        }
	}
}

function scandir2($folder) {
	$list = scandir($folder);
	unset($list[0]);
	unset($list[1]);
	return $list;
}