#!/usr/bin/perl

if ($#ARGV < 6) {
    die "Not enough parameters!\n";
} else {
    $LOC = $ARGV[0];
    ($SEL,$CREG) = split(":",$ARGV[1]);
    @letters = @ARGV[2,3,4,5,6];
    $ALL = $ARGV[7];
};

chdir $LOC || die "Error: cannot chdir to $LOC\n";
foreach $letter (@letters) {
    $start = 1;
    $total = '?';
    ($name,$fname) = split(':',$letter);
    download($start,$total,$name,$fname);
    $total = `../.extract.pl $fname $start`;
    chomp $total;
    $pages = ($total - ($total % 25)) / 25;
    if (($total % 25) != 0) { $pages++; };
    if ($ALL) {
	for ($r=1; $r<$pages; $r++) {
	    $start += 25;
	    download($start,$total,$name,$fname);
	    $dagoeba = `../.extract.pl $fname $start`;
	};
    } else {
	open FILE, ">>.count";
	print FILE "$fname   $total  $pages\n";
	close FILE;
    };
};
exit;

sub download($$$) {
    my ($start,$total,$name,$fname) = @_;
    $fname = $fname . "_" . $start . ".html";
    open FILE, ">>.status";
    print FILE localtime(time) . " downloading: $fname $start/$total\n";
    close FILE;
    if (! -e $fname) {
        system( "curl 'http://db.infotel.bg:8889/phone/plsql/F_PRINT_REZ?ST=$start&BR=n&CREG=$CREG&SEL=$SEL&CSURNAME=$name&CNAME=&CPATNAME=&CADDRESS=&ekod_pr=' -x cache.internet-bg.net:3128 -A 'Mozilla/4.74 [fy] (WinME; U)' > $fname 2> /dev/null" );
    };
};
