#!/usr/bin/perl

use strict; use warnings;

my $max_file_size = 10*1024*1024; # 10Mb is max file size

my ($device, $block_size) = @ARGV;

unless (-r $device && $block_size) {
	die "syntax: recoverjpegs device block_size\n";
}

open DEVICE, $device;

my $block;
my $n = 0;
my $in_file = 0;
my $size = 0;
while (read DEVICE, $block, $block_size) {
	if ($block =~ /^\xff\xd8/ and $block =~ /JFIF/) {
		++$n;
		my $filename = sprintf("%06d", $n).".jpg";
		print "$filename\n";
		open OUT, ">", $filename;
		print OUT $block;
		$size = $block_size;
		$in_file = 1;
	} elsif ($in_file) {
		if ($block =~ /^\0*\Z/s || $size >= $max_file_size) {
			$in_file = 0;
		} else {
			print OUT $block;
			$size += $block_size;
		}
	}
}
