#!/Perl

print "Hello, World...\n";
if( !defined( $ENV{'USERPROFILE'} ) ) {
	print "Can NOT locate USERPROFILE in ENVironment!\n";
	exit(1);
}
my $ff = $ENV{'USERPROFILE'} . '\\Favorites';
if( !( -d $ff ) ) {
	print "Folder $ff is NOT a directory!\n";
}
my $logfil = "templog.csv";
my $basedir = $ff;
my $blen = length($basedir);
my ($fn,$ffn,$LF);
my @dirs = ($ff);
my @fils = ();
open $LF, ">$logfil" or die "Can NOT open LOG file $logfil!\n";
##print "Processing $ff ...\n";
##opendir( DIRHAND, $ff );
##my @files = readdir( DIRHAND );
##closedir( DIRHAND );
##print "Found " . scalar @files . " entries ...\n";
##get_lists(@files);
my $fcnt = scalar @fils;
my $dcnt = scalar @dirs;
#print "Found $fcnt files, and $dcnt directories ...\n";
while (scalar @dirs) {
	local @dir2 = @dirs;
	@dirs = ();
	while ($fn = shift @dir2) {
		do_dir($fn);
	}
}
$fcnt = scalar @fils;
$dcnt = scalar @dirs;
print "Total: $fcnt URL files ...\n";
foreach $fn (@fils) {
	# process each file
	local $FH;
	if ( open( $FH, $fn ) ) {
		local @lns = <$FH>; # slurp in the lines
		local $sn = sb($fn);
		###prt( "Processing " . sb($fn) . " of " . scalar @lns . " lines ...\n");
		close( $FH );
		local $line;
		foreach $line (@lns) {
			if( $line =~ /^URL=/ ) {
				local $u = substr($line,4); ## ~ s/^URL=//;
				prt( "\"$sn\",$u" );
			}
		}
	} else {
		print "Unable to open file $fn ...\n";
	}
}


sub get_lists {
	###foreach $fn (@files) {
	while ($fn = shift @_) {
		next if ($fn eq '.');
		next if ($fn eq '..');
		$ffn = $ff . '\\' . $fn;
		if( -d $ffn ) {
			push(@dirs, $ffn);
		} else {
			if ($fn =~ /\.url$/i) {
				push(@fils, $ffn);
			} else {
				print "Discarding file $ffn ...\n";
			}
		}
	}
	$fcnt = scalar @fils;
	$dcnt = scalar @dirs;
	print "Found $fcnt files, and $dcnt directories ...\n";
}

sub do_dir {
	local ($dn) = @_;
	print "Processing $dn ...\n";
	opendir(DIRH, $dn);
	local @f = readdir(DIRH);
	closedir(DIRH);
	print "Found " . scalar @f . " entries ...\n";
	$ff = $dn;
	get_lists(@f);
}

sub prt {
	#print @_;
	print $LF @_;
}

sub sb {
	local ($f) = @_;
	local $b2 = quotemeta($basedir);
	###$f =~ s/^$basedir//;
	###$f = substr( $f, (length($basedir) + 1) );
	##$f = substr( $f, ($blen + 1), (length($f) - $blen - 5) );
	$f =~ s/^$b2\\//;
	$f =~ s/\.url$//;
	return $f;
}

#eof
