<?php
if (count($_SERVER['argv']) != 2) {
	die('Usage: manga.php fileid');
}

$fileid = trim($_SERVER['argv'][1]);

$first = @file_get_contents('http://www.mangatraders.com/view/file/'.urlencode($fileid));
if ($first === false) {
	die("404\n");
}

$matches = array();
preg_match_all('/option value="(\d+)/', $first, $matches);
$pages = count($matches[1]) - 1;

echo "File $fileid ($pages pages)\n";

for ($i = 1; $i < ($pages + 1); $i++) {
	
	echo sprintf("[%3d] ", $i);
	
	$output_name = dirname(__FILE__).'/mangatraders_'.$fileid.'_'.sprintf("%03d", $i);
	if (file_exists($output_name.'.jpg') || file_exists($output_name.'.png')) {
		echo "exists, skipping\n";
		continue;
	}	
	
	$page = file_get_contents('http://www.mangatraders.com/view/file/'.urlencode($fileid).'/page/'.$i);
	
	$matches = array();
	preg_match('/<img id="image" src="([^"]+)"/', $page, $matches);
	
	$url = $matches[1];
	
	echo $url;
	
	$img = file_get_contents($url);
	file_put_contents(
		$output_name.'.'.substr($url, strlen($url)-3),
		$img
	);
	
	echo " done\n";
	
}

echo "All pages downloaded.\n";