#!/usr/bin/perl
###############################################################################

BEGIN{ unshift( @INC, 'PDB' ); }

local $SIG{__DIE__} = sub { my $msg = shift; print "<H2>DIE: $msg</H2>\n"; };
require 5.002;
use Pdb;

my $path = 'data';
my $db = new Pdb( $path );
my $filename = 'Members';
my $ext = 'new';

%Ind = (
#	ID			=> "ID.$ext",		# This is really a %map hash
	Company		=> "Name.$ext",
	FName		=> "FName.$ext",
	SName		=> "SName.$ext",
	LName		=> "LName.$ext",
	WCountry	=> "Country.$ext",
	WState		=> "State.$ext",
	WCity		=> "City.$ext",
	Email		=> "Email.$ext",
	Joined		=> "Joined.$ext",
);

if( $ENV{SCRIPT_NAME} )
{
	print <<EOF;
Content-type: text/plain

EOF
}

###############################################################################

unless( $db->Open( $filename ) )
{
	print "Couldn't Open '$db->{path}$filename' table\n";
	exit;
}

###############################################################################

%ord;	# The hash mapping business names to record indexes - it gets sorted then
%map;	# Maps Member IDs into database record numbers

print "Building alphabetical list of Shops to Index...\n";

$db->GoTop();
while( $db->ValidPos )
{
	my( $name, $id ) = $db->GetFields( 'Company', 'ID' );
	$id = int( $id );
	if( $map{$id} )
	{
		print "Duplicate for $id at $map{$id} and $db->{rec}\n";
	}
	else
	{
		push( @{$ord{$name}}, $id );	# May have multiple entries with same business name
	}
	$map{$id} = $db->{rec};	# In case of multiples use the latest
	$db->Next();
}

@ord;

for( sort keys %ord )
{
	push( @ord, @{$ord{$_}} );
}

undef %ord;

print "Building indexes in memory...\n";

foreach( @ord )
{
	$db->GoTo( $map{$_} );
	for $ind ( keys %Ind )
	{
		my $val = $db->GetFields( $ind );
		push( @{$IndVal{$ind}{$val}}, $_ );		# Store this memberID for $val
	}
}

$db->Close();

###############################################################################

if( open( MAP, "> $path/ID.$ext" ) )
{
	for( sort {int($a) <=> int($b)} keys %map )
	{
		print MAP int($_), ':', int($map{$_}), "\n";
	}
	close( MAP );
}
else
{
	print "Couldn't create Main ID map '$path/ID.$ext'\n";
}

for $ind ( keys %Ind )
{
	print "Saving Index $ind...\n";
	if( open( IND, "> $path/$Ind{$ind}" ) )
	{
		print " ... '$Ind{$ind}' with ", scalar keys %{$IndVal{$ind}}, " keys\n";
		for( sort keys %{$IndVal{$ind}} )
		{
			print IND "$_:@{$IndVal{$ind}{$_}}\n";
		}
		close( IND );
	}
	else
	{
		print "Couldn't create Index '$path/$Ind{$ind}'\n";
	}
}

###############################################################################
