#!/usr/bin/perl

use Getopt::Long; # Parses options
use Cwd; # Gets current working directory
use LWP::Simple; # Contains wget

# Parse command line options
# @param See sub help.
{
	my ($num_of_images, $target_dir, $keywords, $help) = 
	(10, getcwd(), "", ""); # Sets default values for options

	# Parses command line arguments into option variables	
	GetOptions(
		'n=i' => \$num_of_images, 
		't=s' => \$target_dir,
		'help|?' => \$help);
	$keywords = join(' ', @ARGV);

	# Deals with options and does actual work.
	if ($help || scalar @ARGV == 0) {
		help(); 
	} else {
		mkdir($target_dir); # Fails gracefully if directory exists.
		chdir($target_dir);
		crawl($num_of_images, $keywords);
	}
}

# Prints out help
sub help {
	print "usage : $0 [options] keyword1 keyword2 ...\n";
	print "options:\n";
	print "  -n  number of images to download (default: 10)\n";
	print "  -t  where to put the images. (default: cwd)\n";
}

# Actually does work. Expects 2 arguments.
# @param Number of images to save, what keywords to use.
sub crawl {
	my ($num_of_images, $keywords) = (shift, shift);
	
	for (my ($current_page, $i) = (1, 0);; $current_page++) {
		# Parses current page into valid images we want to save.
		my @tbp = parseURL("http://www.flickr.com/search/?q=$keywords&page=$current_page");
		if (scalar @tbp == 0) {
			die "No more search results.";
		}

		# Saves each image into the right place.
		foreach my $image (@tbp) {
			if ($num_of_images == $i++) { # Checks to see if finished
				return;
			}

			saveImage($image, "$i.jpg");
		}
	}
}

# Parses page, returns all valid images to get.
# @param URL to parse.
# @return Array containing all valid img links.
sub parseURL {
	my ($content, @tbr) = (get(shift), ()) 
		or die "Couldn't retrieve URL.";

	foreach my $line (split(/<*.>/, $content)) {
		# Gets all img urls, filters out rel links
		if ($line =~ /^<img src="(http:\/\/.*?)"/i) { 
			# Images we want are on static. Filters out buddy icons.
			my $url = $1;
			if ($url =~ /static/ && $url !~ /buddyicons/) {
				push(@tbr, "$url");
			}
		}
	}
	
	return @tbr;
}

# Saves image to correct file. Working directory already set.
# @param Image url to save, filename to save to.
sub saveImage {
	my ($url, $filename) = (shift, shift) 
		or die "Couldn't retrieve image.";

	print "Saving image $filename\n";
	getstore($url, $filename);
}	

