#!/usr/bin/perl
#
use LWP::Simple;

$URL 		= 'http://number-logic.com/archive';
$TPLFILE	= 'tpl_sudoku.tex'; # name of the template used to generate tex file
$OUTFILE	= 'sudoki.tex';     # name of the output tex file

my $content = get ($URL);

# follow all links and download sudokus
while ($content =~ /fill_puzzle\("(.*?)"\).*?25px;">(.*?) at.*?center>(.*?)</gsi){
	my @sudoku; 
	my $caption = "$2 ($3)";
	my $str = $1;
	$str =~ s/\./ /g;
	my @arr = split (//,$str);
	for ($i=0;$i<81;$i++){
		$sudoku[int($i/9)][$i%9] = $arr[$i];
	}
	
	my $sudo = toLatex(toText(@sudoku),$caption);
	push @sudokistack, $sudo;
}

# create the string containing all the sudokus
# (why here? 'cause this way, if you want, you can execute 
# other operations on the stack)
for (reverse @sudokistack){
	$sudoki .= $_;
}

# load template file
my $TPL = "";
open (IN, "<$TPLFILE") || die "Could not open template file $TPLFILE!\n\n";;
while (<IN>){ 
	$TPL .= $_; 
}
close IN;

$TPL =~ s/###SUDOKI###/$sudoki/;

open (OUT, ">$OUTFILE");
print OUT $TPL;
close OUT;


exit;

# --------------------------------------------------------------------------
# function toText receives an array containing the sudoku and returns a 
# string representing it 
# 
sub toText {
	# @sudoku is the 9x9 array containing the sudoku
	my @sudoku = @_;
	# $sudo is the string which will contain the sudoku once
	# converted in plain text
	my $sudo = "";

	for ($i=0;$i<9;$i++){
		$sudo .= "|"; # line starts here
		for ($j=0;$j<9;$j++){
			$sudo .= $sudoku[$i][$j]."|"; # sudoku cell
		}
		$sudo .= ".\n"; # end of line
	}
	return $sudo;
}

# --------------------------------------------------------------------------
# toLatex function receives a sudoky in the string format returned by toText
# and a caption to insert below the sudoku. It then returns LaTeX text,
# containing the code needed to display the sudoku
#
sub toLatex {
	my ($sudo,$caption) = @_;
	my $tex = "";
	$tex .= "\\begin{sudoku}\n$sudo\\end{sudoku}\n"; #sudoku
	$tex .= "\\begin{center}\n$caption\n\\end{center}\n"; #caption
	if ($flag){
		# insert a pagebreak every 2 sudoku
		$tex .= "\n\\pagebreak\n\n";
		$flag = 0;
	}else{
		$tex .= "\n\\verb||\n\n";
		$flag = 1;
	}
	return $tex;
}

# --------------------------------------------------------------------------
# --------------------------------------------------------------------------
