###########################################################################
#
# CICPlug.pm
# A component of the Greenstone digital library software
# from the New Zealand Digital Library Project at the 
# University of Waikato, New Zealand.
#
# Copyright (C) 2005 New Zealand Digital Library Project
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
###########################################################################

package CICPlug;


use BasPlug;
use DBI;
use strict;


sub BEGIN {
    @CICPlug::ISA = ('BasPlug');
}


my $arguments =
  [ 
    { 'name' => "images_directory",
      'type' => "string",
      'deft' => "",
      'reqd' => "yes" },
    { 'name' => "cache_directory",
      'type' => "string",
      'deft' => &util::filename_cat($ENV{'GSDLHOME'}, "tmp"),
      'reqd' => "no" },
    { 'name' => "large_image_options",
      'type' => "string",
      'deft' => "",
      'reqd' => "no" },
    { 'name' => "large_image_type",
      'type' => "string",
      'deft' => "jpg",
      'reqd' => "no" },
    { 'name' => "large_image_width",
      'type' => "string",
      'deft' => "1250",
      'reqd' => "no" },
    { 'name' => "medium_image_options",
      'type' => "string",
      'deft' => "",
      'reqd' => "no" },
    { 'name' => "medium_image_type",
      'type' => "string",
      'deft' => "jpg",
      'reqd' => "no" },
    { 'name' => "medium_image_width",
      'type' => "string",
      'deft' => "375",
      'reqd' => "no" },
    { 'name' => "small_image_options",
      'type' => "string",
      'deft' => "",
      'reqd' => "no" },
    { 'name' => "small_image_type",
      'type' => "string",
      'deft' => "jpg",
      'reqd' => "no" },
    { 'name' => "small_image_width",
      'type' => "string",
      'deft' => "125",
      'reqd' => "no" }
  ];

my $options = { 'name'     => "CICPlug",
		'desc'     => "{CICPlug.desc}",
		'abstract' => "no",
		'inherits' => "yes" };


sub get_default_process_exp
{
    return q^(?i)\.mdb$^;
}


sub new
{
    my ($class) = shift (@_);
    my ($pluginlist,$inputargs,$hashArgOptLists) = @_;
    push(@$pluginlist, $class);

    if (defined $arguments) { push(@{$hashArgOptLists->{"ArgList"}}, @{$arguments}); }
    if (defined $options) { push(@{$hashArgOptLists->{"OptList"}}, $options); }

    my $self = (defined $hashArgOptLists) ? new BasPlug($pluginlist,$inputargs,$hashArgOptLists) : new BasPlug($pluginlist,$inputargs);

    return bless $self, $class;
}


my $state_abbr_to_name_mapping = {
    "AL" => "Alabama",
    "AK" => "Alaska",
    "AZ" => "Arizona",
    "AR" => "Arkansas",
    "CA" => "California",
    "CO" => "Colorado",
    "CT" => "Connecticut",
    "DE" => "Delaware",
    "FL" => "Florida",
    "GA" => "Georgia",
    "HI" => "Hawaii",
    "ID" => "Idaho",
    "IL" => "Illinois",
    "IN" => "Indiana",
    "IA" => "Iowa",
    "KS" => "Kansas",
    "KY" => "Kentucky",
    "LA" => "Louisiana",
    "ME" => "Maine",
    "MD" => "Maryland",
    "MA" => "Massachusetts",
    "MI" => "Michigan",
    "MN" => "Minnesota",
    "MS" => "Mississippi",
    "MO" => "Missouri",
    "MT" => "Montana",
    "NE" => "Nebraska",
    "NV" => "Nevada",
    "NH" => "New Hampshire",
    "NJ" => "New Jersey",
    "NM" => "New Mexico",
    "NY" => "New York",
    "NC" => "North Carolina",
    "ND" => "North Dakota",
    "OH" => "Ohio",
    "OK" => "Oklahoma",
    "OR" => "Oregon",
    "PA" => "Pennsylvania",
    "RI" => "Rhode Island",
    "SC" => "South Carolina",
    "SD" => "South Dakota",
    "TN" => "Tennessee",
    "TX" => "Texas",
    "UT" => "Utah",
    "VT" => "Vermont",
    "VA" => "Virginia",
    "WA" => "Washington",
    "WV" => "West Virginia",
    "WI" => "Wisconsin",
    "WY" => "Wyoming"
    };


my $place_type_id_to_name_mapping = {
    "1" => "Individual building",
    "2" => "Landscape site",
    "3" => "Campus arrangement",
    "4" => "Building group",
};


sub read
{
    my $self = shift (@_);
    my ($pluginfo, $base_dir, $file, $metadata, $processor, $maxdocs, $total_count, $gli) = @_;

    $self->{'filename'} = &util::filename_cat($base_dir, $file);
    if ($self->{'filename'} !~ /$self->{'process_exp'}/ || !-f $self->{'filename'}) {
	return undef;
    }
    $self->{'processor'} = $processor;
    $self->{'gli'} = $gli;

    # Open connection to Access database
    my $dbh = DBI->connect('dbi:ODBC:CIC-HCAP');

    $self->process_institutions($dbh);
    $self->process_places($dbh);
    $self->process_designers($dbh);

    return 1;
}


sub process_institutions
{
    my $self = shift(@_);
    my $dbh = shift(@_);

    # Prepare SQL statement for getting everything from the Institution table
    my $institution_sql_statement = "SELECT * FROM tblInstitution";  # WHERE Institution_ID<200";
    my $institution_sql_handle = $dbh->prepare($institution_sql_statement);
    $institution_sql_handle->{LongReadLen} = 65536;
    $institution_sql_handle->execute() or die "Could not execute SQL statement.";

    # Prepare SQL statement for getting the Institution places
    my $institution_places_sql_statement = "SELECT Entry_ID,Current_name FROM tblPlace WHERE PlaceType>0 AND Institution_ID=?";
    my $institution_places_sql_handle = $dbh->prepare($institution_places_sql_statement);
    $institution_places_sql_handle->{LongReadLen} = 65536;

    # Prepare SQL statement for getting the Institution best place image location
    my $institution_best_place_image_location_sql_statement = "SELECT Location FROM tblImages WHERE FileType=1 AND FileName=?";
    my $institution_best_place_image_location_sql_handle = $dbh->prepare($institution_best_place_image_location_sql_statement);
    $institution_best_place_image_location_sql_handle->{LongReadLen} = 65536;

    # Prepare SQL statement for getting the Institution places images
    my $institution_places_images_sql_statement = "SELECT FileName FROM tblImages,tblPlace WHERE tblImages.FileType=1 AND tblImages.Entry_ID=tblPlace.Entry_ID AND tblPlace.Institution_ID=?";
    my $institution_places_images_sql_handle = $dbh->prepare($institution_places_images_sql_statement);
    $institution_places_images_sql_handle->{LongReadLen} = 65536;

    # Prepare SQL statement for getting the Institution campus plans
    my $institution_campus_plans_sql_statement = "SELECT * FROM tblCampusMaps WHERE Electronic=1 AND Institution_ID=?";
    my $institution_campus_plans_sql_handle = $dbh->prepare($institution_campus_plans_sql_statement);
    $institution_campus_plans_sql_handle->{LongReadLen} = 65536;

    # Create a document object for each institution
    my %institution_state_to_name_mapping;
    my %institution_name_to_id_mapping;
    while (my $row_hashref = $institution_sql_handle->fetchrow_hashref) {
	# Skip any institutions that didn't respond
	next if !defined($row_hashref->{"City"});

	my $institution_id = $row_hashref->{"Institution_ID"};
	# print STDERR "       Institution $institution_id\n";
	my $institution_doc_obj = new doc($self->{'filename'} . "-", "indexed_doc");
	$institution_doc_obj->set_OID("i$institution_id");
	&new_metadata_entry($institution_doc_obj, "DocumentType", "Institution");

	# For some reason the hyphen seems to be lost from the Zip field, so add it back in
	my $institution_zip = $row_hashref->{"Zip"};
	if ($institution_zip =~ /^(\d\d\d\d\d)(\d\d\d\d)$/) {
	    $row_hashref->{"Zip"} = $1 . "-" . $2;
	}

	# Map state to full name
	$row_hashref->{"State"} = $state_abbr_to_name_mapping->{$row_hashref->{"State"}};

	# Get the places in this institution
	my $institution_random_place_id;
	my $institution_places_list_html = "";
	$institution_places_sql_handle->execute($institution_id) or die "Could not execute SQL statement.";
	while (my $institution_places_match_hashref = $institution_places_sql_handle->fetchrow_hashref) {
	    my $institution_place_id = $institution_places_match_hashref->{"Entry_ID"};
	    my $institution_place_name = $institution_places_match_hashref->{"Current_name"};
	    $institution_places_list_html .= "<span class=\"cictext\"><a href=\"_gwcgi_?a=d&d=p$institution_place_id\">$institution_place_name</a></span><br />\n";
	}
	&new_metadata_entry($institution_doc_obj, "InstitutionPlacesListHTML", $institution_places_list_html);

	# Get the best place image for this institution
	my $institution_best_place_image_name = $row_hashref->{"Best_image"};
	if (!defined($institution_best_place_image_name) || $institution_best_place_image_name eq "") {
	    # Some institutions have no electronic images, and thus have no best image
	    $institution_places_images_sql_handle->execute($institution_id) or die "Could not execute SQL statement.";
	    if (defined($institution_places_images_sql_handle->fetchrow_hashref())) {
		print STDERR "<ProcessingError n='Institution $institution_id' p='CICPlug' r='No best image'>\n" if ($self->{'gli'});
		print STDERR "Error: Institution $institution_id -- No best image.\n";
		$self->{'num_not_processed'}++;
		next;
	    }
	    &new_metadata_entry($institution_doc_obj, "InstitutionBestPlaceImageHTML", "");
	}
	else {
	    # Get the file location of the best place image for this institution
	    $institution_best_place_image_location_sql_handle->execute($institution_best_place_image_name) or die "Could not execute SQL statement.";
	    my $institution_best_place_image_location = $institution_best_place_image_location_sql_handle->fetchrow();
	    if (!defined($institution_best_place_image_location) || $institution_best_place_image_location eq "") {
		print STDERR "<ProcessingError n='Institution $institution_id' p='CICPlug' r='Could not match best image $institution_best_place_image_name to a file'>\n" if ($self->{'gli'});
		print STDERR "Error: Institution $institution_id -- Could not match best image $institution_best_place_image_name to a file.\n";
		$self->{'num_not_processed'}++;
		next;
	    }

	    $self->new_place_image($institution_doc_obj, $institution_best_place_image_location, "medium");
	    $self->new_place_image($institution_doc_obj, $institution_best_place_image_location, "large");

	    my $institution_best_place_image_large_file_name = $institution_best_place_image_name . "-large.jpg";
	    $institution_best_place_image_large_file_name =~ s/ /%20/g;
	    my $institution_best_place_image_large_file_link = "_httpcollection_/index/assoc/[assocfilepath]/$institution_best_place_image_large_file_name";
	    my $institution_best_place_image_medium_file_name = $institution_best_place_image_name . "-medium.jpg";
	    $institution_best_place_image_medium_file_name =~ s/ /%20/g;
	    my $institution_best_place_image_medium_file_link = "_httpcollection_/index/assoc/[assocfilepath]/$institution_best_place_image_medium_file_name";
	    &new_metadata_entry($institution_doc_obj, "InstitutionBestPlaceImageHTML", "<a href=\"$institution_best_place_image_large_file_link\"><img src=\"$institution_best_place_image_medium_file_link\"/><br /><span class=\"cictext\">$institution_best_place_image_name</span></a>");
	}

	# Get institution campus plans
	my $institution_campus_plans_list_html = "";
	$institution_campus_plans_sql_handle->execute($institution_id) or die "Could not execute SQL statement.";
	while (my $institution_campus_plans_match_hashref = $institution_campus_plans_sql_handle->fetchrow_hashref) {
	    my $institution_campus_plan_name = $institution_campus_plans_match_hashref->{"NameAndFormat"};
	    my $institution_campus_plan_image_location = $institution_campus_plans_match_hashref->{"Location_electronic"};

	    # Deal with PDF files separately: don't convert, just associate
	    if ($institution_campus_plan_image_location =~ /\.pdf$/i) {
		# Convert the server location of the file into the local location of the file
		my $institution_campus_plan_pdf_file_path = $institution_campus_plan_image_location;
		$institution_campus_plan_pdf_file_path =~ s/^[A-Z]:/$self->{'images_directory'}/;

		if (-f $institution_campus_plan_pdf_file_path) {
		    my $institution_campus_plan_pdf_file_name = $institution_campus_plan_name . ".pdf";
		    $institution_campus_plan_pdf_file_name =~ s/ /%20/g;
		    my $institution_campus_plan_pdf_file_link = "_httpcollection_/index/assoc/[assocfilepath]/$institution_campus_plan_pdf_file_name";
		    $institution_campus_plans_list_html .= "<a href=\"$institution_campus_plan_pdf_file_link\"><span class=\"cictext\">$institution_campus_plan_name (PDF)</span></a><br />";

		    $institution_doc_obj->associate_file($institution_campus_plan_pdf_file_path, $institution_campus_plan_name . ".pdf", undef, $institution_doc_obj->get_top_section());
		}
		else {
		    print STDERR "<ProcessingError n='$institution_campus_plan_pdf_file_path' p='CICPlug' r='Does not exist'>\n" if ($self->{'gli'});
		    print STDERR "Error: File $institution_campus_plan_pdf_file_path does not exist.\n";
		}
	    }
	    else {
		$self->new_place_image($institution_doc_obj, $institution_campus_plan_image_location, "large");

		my $institution_campus_plan_image_large_file_name = $institution_campus_plan_name . "-large.jpg";
		$institution_campus_plan_image_large_file_name =~ s/ /%20/g;
		my $institution_campus_plan_image_large_file_link = "_httpcollection_/index/assoc/[assocfilepath]/$institution_campus_plan_image_large_file_name";
		$institution_campus_plans_list_html .= "<a href=\"$institution_campus_plan_image_large_file_link\"><span class=\"cictext\">$institution_campus_plan_name</span></a><br />";
	    }
	}
	&new_metadata_entry($institution_doc_obj, "InstitutionCampusPlansListHTML", $institution_campus_plans_list_html);

	# Add each field from the table as metadata
	foreach my $key (keys(%$row_hashref)) {
	    my $value = $row_hashref->{$key};
	    if (defined($value)) {
		&new_metadata_entry($institution_doc_obj, $key, $value);
	    }
	}

	$institution_doc_obj->add_utf8_text($institution_doc_obj->get_top_section(), "Some dummy text.");
	$self->{'processor'}->process($institution_doc_obj);
	$self->{'num_processed'}++;

	# Build mappings for creating the static macrofiles
	my $institution_name = $row_hashref->{"Institution_Name"};
	$institution_name_to_id_mapping{$institution_name} = $institution_id;
	my $institution_state = $row_hashref->{"State"};
	push(@{$institution_state_to_name_mapping{$institution_state}}, $institution_name);
    }

    # Write the institutions.dm macrofile
    &write_static_browser_macrofile("institutions", \%institution_name_to_id_mapping, "i");

    # Write the states.dm macrofile
    &write_state_browser_macrofile("states", \%institution_state_to_name_mapping, \%institution_name_to_id_mapping);
}


sub process_places
{
    my $self = shift(@_);
    my $dbh = shift(@_);

    # Prepare SQL statement for getting everything from the Place table
    my $place_sql_statement = "SELECT * FROM tblPlace";
    my $place_sql_handle = $dbh->prepare($place_sql_statement);
    $place_sql_handle->{LongReadLen} = 65536;
    $place_sql_handle->execute() or die "Could not execute SQL statement.";

    # Prepare SQL statement for getting the Place institution
    my $place_institution_sql_statement = "SELECT Institution_Name FROM tblInstitution,tblPlace WHERE tblInstitution.Institution_ID=tblPlace.Institution_ID and tblPlace.Entry_ID=?";
    my $place_institution_sql_handle = $dbh->prepare($place_institution_sql_statement);

    # Prepare SQL statement for getting the Place "date of construction"
    my $place_construction_date_sql_statement = "SELECT Date FROM tblConstruction_and_Dates WHERE Entry_ID=?";
    my $place_construction_date_sql_handle = $dbh->prepare($place_construction_date_sql_statement);

    # Prepare SQL statement for getting the Place images
    my $place_images_sql_statement = "SELECT FileName,Location FROM tblImages WHERE FileType=1 AND Entry_ID=?";
    my $place_images_sql_handle = $dbh->prepare($place_images_sql_statement);
    $place_images_sql_handle->{LongReadLen} = 65536;

    # Prepare SQL statement for getting the Place materials
    my $place_materials_sql_statement = "SELECT * FROM tblDescription_building WHERE Entry_ID=?";
    my $place_materials_sql_handle = $dbh->prepare($place_materials_sql_statement);
    $place_materials_sql_handle->{LongReadLen} = 65536;

    # Prepare SQL statement for getting the Place building styles
    my $place_styles_sql_statement = "SELECT Architectural_Classification FROM tblArchTypes,jnxtblArchPlace WHERE tblArchTypes.ArchType_ID=jnxtblArchPlace.ArchType_ID AND Entry_ID=?";
    my $place_styles_sql_handle = $dbh->prepare($place_styles_sql_statement);
    $place_styles_sql_handle->{LongReadLen} = 65536;

    # Prepare SQL statement for getting the Place functions
    my $place_functions_sql_statement = "SELECT Function,Year,Prefix FROM tblFunction_and_dates WHERE Entry_ID=?";
    my $place_functions_sql_handle = $dbh->prepare($place_functions_sql_statement);
    $place_functions_sql_handle->{LongReadLen} = 65536;

    # Prepare SQL statement for getting the Place significance
    my $place_significance_sql_statement = "SELECT SigType FROM tblSigTypes,SigPlace WHERE tblSigTypes.SigTypes_ID=SigPlace.SigType_ID+1 AND SigPlace.Entry_ID=?";
    my $place_significance_sql_handle = $dbh->prepare($place_significance_sql_statement);
    $place_significance_sql_handle->{LongReadLen} = 65536;

    # Prepare SQL statement for getting the Place references
    my $place_references_sql_statement = "SELECT Bibliography FROM tblReferences WHERE Entry_ID=?";
    my $place_references_sql_handle = $dbh->prepare($place_references_sql_statement);
    $place_references_sql_handle->{LongReadLen} = 65536;

    # Prepare SQL statement for getting the Place narrative
    my $place_narrative_sql_statement = "SELECT Narrative FROM tblSignificance_Narrative WHERE Entry_ID=?";
    my $place_narrative_sql_handle = $dbh->prepare($place_narrative_sql_statement);
    $place_narrative_sql_handle->{LongReadLen} = 65536;

    # Prepare SQL statement for getting the Place state
    my $place_state_sql_statement = "SELECT State FROM tblInstitution,tblPlace WHERE tblInstitution.Institution_ID=tblPlace.Institution_ID AND Entry_ID=?";
    my $place_state_sql_handle = $dbh->prepare($place_state_sql_statement);
    $place_state_sql_handle->{LongReadLen} = 65536;

    # Create a document object for each place
    my %place_type_to_names_mapping;
    my %place_style_to_names_mapping;
    my %place_date_to_names_mapping;
    my %place_function_to_names_mapping;
    my %place_name_to_id_mapping;
    my %place_id_to_institution_name_mapping;
    while (my $row_hashref = $place_sql_handle->fetchrow_hashref) {
	my $place_id = $row_hashref->{"Entry_ID"};
	# print STDERR "       Place $place_id\n";
	my $place_doc_obj = new doc($self->{'filename'} . "-", "indexed_doc");
	$place_doc_obj->set_OID("p$place_id");
	&new_metadata_entry($place_doc_obj, "DocumentType", "Place");

	# Convert the place type ID into a name
	$row_hashref->{"PlaceType"} = $place_type_id_to_name_mapping->{$row_hashref->{"PlaceType"}};

	# Add each field from the table as metadata
	foreach my $key (keys(%$row_hashref)) {
	    my $value = $row_hashref->{$key};
	    if (defined($value)) {
		&new_metadata_entry($place_doc_obj, $key, $value);
	    }
	}

	# Get place name
	my $place_name = $row_hashref->{"Current_name"};
	if (!defined($place_name)) {
	    print STDERR "<ProcessingError n='Place $place_id' p='CICPlug' r='Missing place name'>\n" if ($self->{'gli'});
	    print STDERR "Error: Place $place_id -- Missing place name.\n";
	    $self->{'num_not_processed'}++;
	    next;
	}

	# Get place type
	my $place_type = $row_hashref->{"PlaceType"};
	if (!defined($place_type)) {
	    print STDERR "<ProcessingError n='Place $place_id' p='CICPlug' r='Missing place type'>\n" if ($self->{'gli'});
	    print STDERR "Error: Place $place_id -- Missing place type.\n";
	    $self->{'num_not_processed'}++;
	    next;
	}

	# Get place date of construction, except for landscape sites which have no date
	$place_construction_date_sql_handle->execute($place_id) or die "Could not execute SQL statement.";
	my $place_construction_date_value = $place_construction_date_sql_handle->fetchrow();
	if (!defined($place_construction_date_value) && $place_type eq "Landscape site") {
	    # Landscape sites may not have a construction date
	    $place_construction_date_value = "";
	}
	if (!defined($place_construction_date_value)) {
	    print STDERR "<ProcessingError n='Place $place_id' p='CICPlug' r='Missing construction date'>\n" if ($self->{'gli'});
	    print STDERR "Error: Place $place_id -- Missing construction date.\n";
	    $self->{'num_not_processed'}++;
	    next;
	}
	&new_metadata_entry($place_doc_obj, "Construction_date", $place_construction_date_value);

	# Create place styles mapping
	$place_styles_sql_handle->execute($place_id) or die "Could not execute SQL statement.";
	while (my $place_styles_match_hashref = $place_styles_sql_handle->fetchrow_hashref()) {
	    my $place_style = $place_styles_match_hashref->{"Architectural_Classification"};
	    push(@{$place_style_to_names_mapping{$place_style}}, $place_name);
	    &new_metadata_entry($place_doc_obj, "Style", $place_style);
	}

	# Get place institution
	$place_institution_sql_handle->execute($place_id) or die "Could not execute SQL statement.";
	my $place_institution = $place_institution_sql_handle->fetchrow();
	&new_metadata_entry($place_doc_obj, "Institution_name", $place_institution);
	$place_id_to_institution_name_mapping{$place_id} = ", " . $place_institution;

	# Get place state (for searching)
	$place_state_sql_handle->execute($place_id) or die "Could not execute SQL statement.";
	my $place_state_abbr = $place_state_sql_handle->fetchrow();
	&new_metadata_entry($place_doc_obj, "State", $place_state_abbr . " " . $state_abbr_to_name_mapping->{$place_state_abbr});

	# Create place dates mapping
	my $place_time_period = $place_construction_date_value;
	if ($place_construction_date_value =~ /^(\d\d\d\d).*$/) {
	    $place_construction_date_value =~ s/^(\d\d\d\d).*$/$1/;
	    if ($place_construction_date_value < 1800) { $place_time_period = "pre-1800"; }
	    elsif ($place_construction_date_value < 1850) { $place_time_period = "1800-1850"; }
	    elsif ($place_construction_date_value < 1900) { $place_time_period = "1850-1900"; }
	    elsif ($place_construction_date_value < 1945) { $place_time_period = "1900-1945"; }
	    elsif ($place_construction_date_value < 1995) { $place_time_period = "1945-1995"; }
	    else { $place_time_period = "post-1995"; }
	    push(@{$place_date_to_names_mapping{$place_time_period}}, $place_name);
	}
	&new_metadata_entry($place_doc_obj, "Time_period", $place_time_period);

	# Get place materials (individual buildings only)
	if ($row_hashref->{"PlaceType"} eq "Individual building") {
	    $place_materials_sql_handle->execute($place_id) or die "Could not execute SQL statement.";
	    my $place_materials_match_hashref = $place_materials_sql_handle->fetchrow_hashref();
	    &new_metadata_entry($place_doc_obj, "MaterialFoundation", $place_materials_match_hashref->{"foundation"} || "");
	    &new_metadata_entry($place_doc_obj, "MaterialRoof", $place_materials_match_hashref->{"roof"} || "");
	    &new_metadata_entry($place_doc_obj, "MaterialWalls", $place_materials_match_hashref->{"walls"} || "");
	}

	# Get place functions
	my $place_functions = "";
	my $place_functions_table_html = "";
	$place_functions_sql_handle->execute($place_id) or die "Could not execute SQL statement.";
	while (my $place_functions_match_hashref = $place_functions_sql_handle->fetchrow_hashref()) {
	    my $place_function = $place_functions_match_hashref->{"Function"};
	    if (!defined($place_function)) {
		print STDERR "<ProcessingError n='Place $place_id' p='CICPlug' r='Missing function'>\n" if ($self->{'gli'});
		print STDERR "Error: Place $place_id -- Missing function.\n";
		next;
	    }
	    my $place_year = $place_functions_match_hashref->{"Year"};
	    if (!defined($place_year)) {
		print STDERR "<ProcessingError n='Place $place_id' p='CICPlug' r='Missing function year'>\n" if ($self->{'gli'});
		print STDERR "Error: Place $place_id -- Missing function year.\n";
		next;
	    }
	    my $place_year_prefix = $place_functions_match_hashref->{"Prefix"} || "";
	    $place_functions .= "$place_function ";
	    $place_functions_table_html .= "<tr><td valign=\"top\"><nobr>$place_year_prefix $place_year</nobr>&nbsp;</td><td valign=\"top\">$place_function</td></tr>";

	    # Create place functions mapping
	    $place_function =~ s/\(.*?\)//g;
	    $place_function =~ s/^\s*//;
	    $place_function =~ s/\s*$//;
	    next if ($place_function eq "");
	    push(@{$place_function_to_names_mapping{$place_function}}, $place_name);
	}
	&new_metadata_entry($place_doc_obj, "Functions", $place_functions);
	&new_metadata_entry($place_doc_obj, "PlaceFunctionsTableHTML", "<table cellpadding=\"0\" cellspacing=\"0\">" . $place_functions_table_html . "</table>");

	# Get place significance
	$place_significance_sql_handle->execute($place_id) or die "Could not execute SQL statement.";
	while (my $place_significance_match_hashref = $place_significance_sql_handle->fetchrow_hashref()) {
	    my $place_significance = $place_significance_match_hashref->{"SigType"};
	    &new_metadata_entry($place_doc_obj, "Significance", lc($place_significance));
	}

	# Get place references
	$place_references_sql_handle->execute($place_id) or die "Could not execute SQL statement.";
	my $place_references = $place_references_sql_handle->fetchrow();
	if (defined($place_references)) {
	    &new_metadata_entry($place_doc_obj, "References", &rtf_to_html($place_references));
	}

	# Get place narrative
	$place_narrative_sql_handle->execute($place_id) or die "Could not execute SQL statement.";
	my $place_narrative = $place_narrative_sql_handle->fetchrow();
	if (defined($place_narrative)) {
	    $place_narrative = &rtf_to_html($place_narrative);
	    $place_narrative =~ s/<br \/>(\s|\n)*$//;  # Remove any trailing <br /> tags
	    &new_metadata_entry($place_doc_obj, "Narrative", $place_narrative);
	}

	# Get place images
	my $place_images_html = "";
	$place_images_sql_handle->execute($place_id) or die "Could not execute SQL statement.";
	while (my $place_images_match_hashref = $place_images_sql_handle->fetchrow_hashref) {
	    my $place_image_location = $place_images_match_hashref->{"Location"};
	    $self->new_place_image($place_doc_obj, $place_image_location, "small");
	    $self->new_place_image($place_doc_obj, $place_image_location, "large");

	    my $place_image_name = $place_images_match_hashref->{"FileName"};
	    my $place_image_large_file_name = $place_image_name . "-large.jpg";
	    $place_image_large_file_name =~ s/ /%20/g;
	    my $place_image_large_file_link = "_httpcollection_/index/assoc/[assocfilepath]/$place_image_large_file_name";
	    my $place_image_small_file_name = $place_image_name . "-small.jpg";
	    $place_image_small_file_name =~ s/ /%20/g;
	    my $place_image_small_file_link = "_httpcollection_/index/assoc/[assocfilepath]/$place_image_small_file_name";
	    $place_images_html .= "<tr><td valign=\"top\"><a href=\"$place_image_large_file_link\"><img src=\"$place_image_small_file_link\"/></a></td><td valign=\"top\"><a href=\"$place_image_large_file_link\"><span class=\"cictext\">$place_image_name</span></a></td></tr>\n";
	}

	&new_metadata_entry($place_doc_obj, "PlaceImagesHTML", "<table>" . $place_images_html . "</table>");

	$place_doc_obj->add_utf8_text($place_doc_obj->get_top_section(), "Some dummy text.");
	$self->{'processor'}->process($place_doc_obj);
	$self->{'num_processed'}++;

	# Build mappings for creating the static macrofiles
	$place_name_to_id_mapping{$place_name} = $place_id;
	push(@{$place_type_to_names_mapping{$place_type}}, $place_name);
    }

    &write_bilevel_static_browser_macrofile("types", \%place_type_to_names_mapping, \%place_name_to_id_mapping, \%place_id_to_institution_name_mapping, "p", 2);
    &write_bilevel_static_browser_macrofile("styles", \%place_style_to_names_mapping, \%place_name_to_id_mapping, \%place_id_to_institution_name_mapping, "p", 2);
    &write_bilevel_static_browser_macrofile("dates", \%place_date_to_names_mapping, \%place_name_to_id_mapping, \%place_id_to_institution_name_mapping, "p", 2);
    &write_bilevel_static_browser_macrofile("functions", \%place_function_to_names_mapping, \%place_name_to_id_mapping, \%place_id_to_institution_name_mapping, "p", 2);
}


sub process_designers
{
    my $self = shift(@_);
    my $dbh = shift(@_);

    # Prepare SQL statement for getting all the Architects from the Place table
    my $designer_sql_statement = "SELECT Architect_Name,Entry_ID FROM tblConstruction_and_dates";
    my $designer_sql_handle = $dbh->prepare($designer_sql_statement);
    $designer_sql_handle->{LongReadLen} = 65536;
    $designer_sql_handle->execute() or die "Could not execute SQL statement.";

    # Prepare SQL statement for getting the Place images
    my $place_images_sql_statement = "SELECT FileName,Location FROM tblImages WHERE FileType=1 AND Entry_ID=?";
    my $place_images_sql_handle = $dbh->prepare($place_images_sql_statement);
    $place_images_sql_handle->{LongReadLen} = 65536;

    # Get a list of all the designers, and the places they worked on
    my %designer_name_to_place_ids_mapping;
    my %designer_name_to_id_mapping;
    my $designer_count = 0;
    while (my $designer_hashref = $designer_sql_handle->fetchrow_hashref) {
	my $designer_names_string = $designer_hashref->{"Architect_Name"};
	next if !defined($designer_names_string);
	foreach my $designer_name (split(/;/, $designer_names_string)) {
	    $designer_name =~ s/\(.*?\)//g;
	    $designer_name =~ s/^\s*//;
	    $designer_name =~ s/\s*$//;

	    if (!defined($designer_name_to_id_mapping{$designer_name})) {
		$designer_count++;
		$designer_name_to_id_mapping{$designer_name} = "$designer_count";
	    }

	    push(@{$designer_name_to_place_ids_mapping{$designer_name}}, $designer_hashref->{"Entry_ID"});
	}
    }

    # Create a document object for each designer
    foreach my $designer_name (keys %designer_name_to_place_ids_mapping) {
  	my $designer_id = $designer_name_to_id_mapping{$designer_name};
  	# print STDERR "       Designer $designer_id\n";
  	my $designer_doc_obj = new doc($self->{'filename'} . "-", "indexed_doc");
  	$designer_doc_obj->set_OID("d$designer_id");
  	&new_metadata_entry($designer_doc_obj, "DocumentType", "Designer");

  	&new_metadata_entry($designer_doc_obj, "Designer_name", $designer_name);

  	my $designer_places_image_html = "";
  	foreach my $designer_place_id (@{$designer_name_to_place_ids_mapping{$designer_name}}) {
  	    # Get the first image for this place
  	    $place_images_sql_handle->execute($designer_place_id) or die "Could not execute SQL statement.";
  	    my $designer_place_image_match_hashref = $place_images_sql_handle->fetchrow_hashref();
	    if (defined($designer_place_image_match_hashref)) {
		my $designer_place_image_location = $designer_place_image_match_hashref->{"Location"};
		$self->new_place_image($designer_doc_obj, $designer_place_image_location, "small");

		my $designer_place_image_name = $designer_place_image_match_hashref->{"FileName"};
		my $designer_place_image_small_file_name = $designer_place_image_name . "-small.jpg";
		$designer_place_image_small_file_name =~ s/ /%20/g;
		my $designer_place_image_small_file_link = "_httpcollection_/index/assoc/[assocfilepath]/$designer_place_image_small_file_name";
		$designer_places_image_html .= "<tr><td valign=\"top\"><a href=\"_gwcgi_?a=d&d=p$designer_place_id\"><img src=\"$designer_place_image_small_file_link\"/></a></td><td valign=\"top\"><a href=\"_gwcgi_?a=d&d=p$designer_place_id\"><span class=\"cictext\">$designer_place_image_name</span></a></td></tr>\n";
	    }
	}

  	&new_metadata_entry($designer_doc_obj, "DesignerPlacesImageHTML", "<table>" . $designer_places_image_html . "</table>");

  	$designer_doc_obj->add_utf8_text($designer_doc_obj->get_top_section(), "Some dummy text.");
  	$self->{'processor'}->process($designer_doc_obj);
	$self->{'num_processed'}++;
    }

    # Write the designers.dm macrofile
    &write_static_browser_macrofile("designers", \%designer_name_to_id_mapping, "d", 2);
}


sub new_metadata_entry
{
    my ($doc_obj, $metadata_name, $metadata_value) = (@_);

    # Don't bother with empty metadata
    return if ($metadata_value eq "");

    # Spaces aren't allowed in metadata names
    $metadata_name =~ s/ /_/g;

    # Fix up non-ASCII values
    $metadata_value =~ s/’/'/g;  # ' # (for Emacs)
    $metadata_value =~ s/“/"/g;
    $metadata_value =~ s/”/"/g;
    $metadata_value =~ s/–/-/g;
    $metadata_value =~ s/\347/c/g;  # !! TO DO
    $metadata_value =~ s/\351/e/g;  # !! TO DO

    # Remove '#' characters around links
    if ($metadata_value =~ /\#(.*?)\#/) {
	$metadata_value = $1;
    }

    $doc_obj->add_utf8_metadata($doc_obj->get_top_section(), $metadata_name, $metadata_value);
}


sub rtf_to_html
{
    my $rtf_string = shift(@_);
    $rtf_string =~ s/\{(.*?)\}//g;
    $rtf_string =~ s/\\rquote /'/g;  # ' # (for Emacs)
    $rtf_string =~ s/\\pard//g;
    $rtf_string =~ s/\\par/<br \/>/g;
    $rtf_string =~ s/\\i0 /<\/i>/g;
    $rtf_string =~ s/\\i /<i>/g;
    $rtf_string =~ s/\\~/ /g;
    $rtf_string =~ s/\\([A-Za-z0-9]+)//g;
    $rtf_string =~ s/\}//g;

    # Assume non-ASCII is ISO 8859-1, and convert into HTML entities
    while ($rtf_string =~ /\\'([a-z0-9][a-z0-9])/) {
        my $dec = hex($1);
	$rtf_string =~ s/\\'$1/&#$dec\;/;
    }

    return $rtf_string;
}


sub new_place_image
{
    my $self = shift(@_);
    my ($doc_obj, $place_image_location, $place_image_size) = (@_);

    # Don't bother with empty values
    return if ($place_image_location eq "");

    # Convert the server location of the file into the local location of the file
    my $place_image_file_path = $place_image_location;
    $place_image_file_path =~ s/^[A-Z]:/$self->{'images_directory'}/;

    # Create a new section for each image of the place
    my $place_image_section = $doc_obj->insert_section($doc_obj->get_end_child($doc_obj->get_top_section()));
    $doc_obj->add_utf8_text($place_image_section, "Some dummy text.");
    $doc_obj->add_utf8_metadata($place_image_section, "Title", "1");

    if (!-f $place_image_file_path) {
	print STDERR "<ProcessingError n='$place_image_file_path' p='CICPlug' r='Does not exist'>\n" if ($self->{'gli'});
	print STDERR "Error: Image $place_image_file_path does not exist.\n";
	return;
    }

    my $place_image_file_name = $place_image_file_path;
    $place_image_file_name =~ s/^.*?([^\\]+)$/$1/;
    my ($image_file_root) = ($place_image_file_name =~ /^(.+)\./);

    # Scale the original image to make the place image
    my $image_width = $self->{$place_image_size . '_image_width'};
    my $image_options = "-scale $image_width " . $self->{$place_image_size . '_image_options'};
    my $image_file_name = $image_file_root . "-$place_image_size." . $self->{$place_image_size . '_image_type'};

    my $original_image_file_path = $place_image_file_path;
    my $image_type = $place_image_size;

    my $original_image_file_date = (stat($original_image_file_path))[9];
    my $image_file_path = &util::filename_cat($self->{'cache_directory'}, $image_file_name);
    my $image_command = "convert -verbose $image_options \"$original_image_file_path\" \"$image_file_path\"";
    my $image_height;

    # Check if this image has already been generated by looking for a ".inf" file in the tmp directory
    $image_file_name =~ /^(.*?)\.[^\.]+$/;
    my $image_info_file_name = $1 . ".inf";
    my $image_info_file_path = &util::filename_cat($self->{'cache_directory'}, $image_info_file_name);
    if (-e $image_info_file_path) {
	open(IMAGE_INFO_FILE, "<$image_info_file_path");
	my @image_info = <IMAGE_INFO_FILE>;
	close(IMAGE_INFO_FILE);

	# Read the original image file date and image command from the file and check they match
	my $old_original_image_file_date = $image_info[0];
	$old_original_image_file_date =~ s/\n$//;
	my $old_image_command = $image_info[1];
	$old_image_command =~ s/\n$//;
	if ($old_original_image_file_date eq $original_image_file_date && lc($old_image_command) eq lc($image_command)) {
	    # print STDERR "Already generated $image_file_name...\n";
	    $image_width = $image_info[2];
	    $image_width =~ s/\n$//;
	    $image_height = $image_info[3];
	    $image_height =~ s/\n$//;
	}
    }

    # Generate the image if it doesn't already exist
    if (!defined($image_width) || !defined($image_height)) {
	print STDERR "Generating place image file: $image_file_name...\n";
	my $outhandle = $self->{'outhandle'};
	print $outhandle "$image_command\n" if ($self->{'verbosity'} > 2);
	my $image_result = `$image_command` || "";
	print $outhandle "RESULT = $image_result\n" if ($self->{'verbosity'} > 2);

	# Get image dimensions
	if ($image_command !~ /\-scale / && $image_result =~ m/([0-9]+)x([0-9]+)/) {
	    $image_width = $1;
	    $image_height = $2;
	}
	elsif ($image_result =~ m/[0-9]+x[0-9]+=>([0-9]+)x([0-9]+)/) {
	    $image_width = $1;
	    $image_height = $2;
	}
	elsif ($image_result =~ m/Image Width: (\d+) Image Length: (\d+)/) {
	    $image_width = $1;
	    $image_height = $2;
	}
        elsif ($image_result =~ m/JPEG (\d+)x(\d+)/) {
	    $image_width = $1;
	    $image_height = $2;
        }
	else {
	    print STDERR "Error: Could not parse image width and height for $original_image_file_path\n";
	    return;
	}
    }

    # Associate the image file
    $doc_obj->associate_file($image_file_path, $image_file_name, undef, $self->{'section'});

    # Add various bits of metadata for the image
    my $image_metadata_value = $image_file_name;
    $image_metadata_value =~ s/ /%20/g;
    $doc_obj->add_utf8_metadata($self->{'section'}, $image_type . "Image", $image_metadata_value);
    $doc_obj->add_metadata($self->{'section'}, $image_type . "ImageWidth", $image_width);
    $doc_obj->add_metadata($self->{'section'}, $image_type . "ImageHeight", $image_height);
    $doc_obj->add_metadata($self->{'section'}, $image_type . "ImagePath", "_httpcollection_/index/assoc/[parent(Top):assocfilepath]/[${image_type}Image]");

    # Write the image info file so we don't have to regenerate this exact image again in the future
    open(IMAGE_INFO_FILE, ">$image_info_file_path");
    print IMAGE_INFO_FILE "$original_image_file_date\n";
    print IMAGE_INFO_FILE "$image_command\n";
    print IMAGE_INFO_FILE "$image_width\n";
    print IMAGE_INFO_FILE "$image_height\n";
    close(IMAGE_INFO_FILE);
}


sub write_static_browser_macrofile
{
    my $static_browser_package_name = shift(@_);
    my $name_to_id_mapping = shift(@_);
    my $id_prefix = shift(@_);
    my $table_columns = 2;

    my $static_browser_macrofile_path = "$ENV{'GSDLHOME'}\\collect\\cic-hcap\\macros\\$static_browser_package_name.dm";
    print STDERR "Writing $static_browser_macrofile_path...\n";
    open(BROWSER_MACROFILE, ">$static_browser_macrofile_path") or die "Error: Could not write to $static_browser_macrofile_path.\n";
    print BROWSER_MACROFILE "package $static_browser_package_name\n\n";
    print BROWSER_MACROFILE "_cicstaticbrowser_ {\n";

    my %letter_to_name_mapping;
    foreach my $name (keys %$name_to_id_mapping) {
	my ($letter) = ($name =~ /^(.)/);
	push(@{$letter_to_name_mapping{$letter}}, $name);
    }

    print BROWSER_MACROFILE "<center><b>";
    foreach my $letter (split(//, "ABCDEFGHIJKLMNOPQRSTUVWXYZ")) {
	if (defined($letter_to_name_mapping{$letter})) {
	    print BROWSER_MACROFILE "<a href=\"#$letter\">$letter</a>&nbsp;";
	}
	else {
	    print BROWSER_MACROFILE "$letter&nbsp;";
	}
    }
    print BROWSER_MACROFILE "</b></center>\n";

    print BROWSER_MACROFILE "<table cellpadding=\"0\" cellspacing=\"0\" width=\"_pagewidth_\">\n";

    foreach my $letter (sort(keys %letter_to_name_mapping)) {
	print BROWSER_MACROFILE "<tr><td width=\"50%\"><br /><a name=\"$letter\"/><span style=\"color: black;\"><b>$letter</b></span></td><td width=\"50%\"></td></tr>\n";

	my @letter_names = sort(@{$letter_to_name_mapping{$letter}});
	my $half_point = ((scalar(@letter_names) % 2 == 0) ? scalar(@letter_names) / 2 : (scalar(@letter_names) + 1) / 2);
	for (my $i = 0; $i < $half_point; $i++) {
	    print BROWSER_MACROFILE "<tr>";

	    my $name = $letter_names[$i];
	    my $id = $id_prefix . $name_to_id_mapping->{$name};
	    print BROWSER_MACROFILE "<td valign=\"top\"><a href=\"_gwcgi_?a=d&d=$id\">$name</a></td>";

	    $name = $letter_names[$i+$half_point];
	    if (defined($name)) {
		$id = $id_prefix . $name_to_id_mapping->{$name};
		print BROWSER_MACROFILE "<td valign=\"top\"><a href=\"_gwcgi_?a=d&d=$id\">$name</a></td>";
	    }
	    else {
		print BROWSER_MACROFILE "<td></td>";
	    }

	    print BROWSER_MACROFILE "</tr>\n";
	}
    }

    print BROWSER_MACROFILE "}\n";
    close(BROWSER_MACROFILE);
}

sub write_bilevel_static_browser_macrofile
{
    my $static_browser_package_root = shift(@_);
    my $category_to_names_mapping = shift(@_);
    my $name_to_id_mapping = shift(@_);
    my $id_to_extra_mapping = shift(@_);
    my $id_prefix = shift(@_);
    my $table_columns = shift(@_);

    my $static_browser_macrofile_path = "$ENV{'GSDLHOME'}\\collect\\cic-hcap\\macros\\$static_browser_package_root.dm";
    print STDERR "Writing $static_browser_macrofile_path...\n";
    open(BROWSER_MACROFILE, ">$static_browser_macrofile_path") or die "Error: Could not write to $static_browser_macrofile_path.\n";

    foreach my $category (keys(%{$category_to_names_mapping})) {
	# print STDERR "Category: $category\n";

	my $static_browser_package_name = $static_browser_package_root . $category;
	$static_browser_package_name =~ s/\W//g;

	print BROWSER_MACROFILE "package $static_browser_package_name\n\n";
        print BROWSER_MACROFILE "_cicstaticbrowser_ {\n";

        print BROWSER_MACROFILE "<center><b>";
        foreach my $letter (split(//, "ABCDEFGHIJKLMNOPQRSTUVWXYZ")) {
	    print BROWSER_MACROFILE "<a href=\"#$letter\">$letter</a>&nbsp;";
        }
        print BROWSER_MACROFILE "</b></center>\n";

	print BROWSER_MACROFILE "<table cellpadding=\"0\" cellspacing=\"0\" width=\"_pagewidth_\">\n";

	my $last_name = "";
        my $current_letter = "";
        my $current_position = 0;
	foreach my $name (sort(@{$category_to_names_mapping->{$category}})) {
	    # Ignore duplicates
	    next if ($name eq $last_name);

	    $name =~ /^(.)/;
	    if ($1 ne $current_letter) {
		if ($current_position > 0) {
		    while ($current_position > 0) {
			print BROWSER_MACROFILE "<td></td>";
			$current_position--;
		    }
		    print BROWSER_MACROFILE "</tr>\n";
		}
		if ($table_columns == 2) {
		    print BROWSER_MACROFILE "<tr><td width=\"50%\"><br /><a name=\"$1\"/><span style=\"color: black;\"><b>$1</b></span></td><td width=\"50%\"></td></tr>\n";
		}
		else {
		    print BROWSER_MACROFILE "<tr><td width=\"33%\"><br /><a name=\"$1\"/><span style=\"color: black;\"><b>$1</b></span></td><td style=\"padding-left: 3px; padding-right: 3px;\" width=\"34%\"></td><td width=\"33%\"></td></tr>\n";
		}
		$current_letter = $1;
	    }

	    my $id = $name_to_id_mapping->{$name};
	    my $extra = "";
	    if (defined($id_to_extra_mapping)) {
		$extra = $id_to_extra_mapping->{$id};
	    }

	    if ($current_position == 0) {
		print BROWSER_MACROFILE "<tr>";
	    }
	    print BROWSER_MACROFILE "<td valign=\"top\"><a href=\"_gwcgi_?a=d&d=$id_prefix$id\">$name</a>$extra</td>";
	    $current_position++;
	    if ($current_position == $table_columns) {
		print BROWSER_MACROFILE "</tr>\n";
		$current_position = 0;
	    }

	    $last_name = $name;
	}

	print BROWSER_MACROFILE "}\n\n";
    }

    close(BROWSER_MACROFILE);
}


sub write_bilevel_static_browser_macrofile_new
{
    my $static_browser_package_root = shift(@_);
    my $category_to_names_mapping = shift(@_);
    my $name_to_id_mapping = shift(@_);
    my $id_to_extra_mapping = shift(@_);
    my $id_prefix = shift(@_);
    my $table_columns = shift(@_);

    my $static_browser_macrofile_path = "$ENV{'GSDLHOME'}\\collect\\cic-hcap\\macros\\$static_browser_package_root.dm";
    print STDERR "Writing $static_browser_macrofile_path...\n";
    open(BROWSER_MACROFILE, ">$static_browser_macrofile_path") or die "Error: Could not write to $static_browser_macrofile_path.\n";

    foreach my $category (keys(%{$category_to_names_mapping})) {
	# print STDERR "Category: $category\n";

	my $static_browser_package_name = $static_browser_package_root . $category;
	$static_browser_package_name =~ s/\W//g;

	print BROWSER_MACROFILE "package $static_browser_package_name\n\n";
        print BROWSER_MACROFILE "_cicstaticbrowser_ {\n";

	my %letter_to_name_mapping;
	foreach my $name (@{$category_to_names_mapping->{$category}}) {
	    my ($letter) = ($name =~ /^(.)/);
	    push(@{$letter_to_name_mapping{$letter}}, $name);
	}

        print BROWSER_MACROFILE "<center><b>";
        foreach my $letter (split(//, "ABCDEFGHIJKLMNOPQRSTUVWXYZ")) {
	    if (defined($letter_to_name_mapping{$letter})) {
		print BROWSER_MACROFILE "<a href=\"#$letter\">$letter</a>&nbsp;";
	    }
	    else {
		print BROWSER_MACROFILE "$letter&nbsp;";
	    }
	}
        print BROWSER_MACROFILE "</b></center>\n";

	print BROWSER_MACROFILE "<table cellpadding=\"0\" cellspacing=\"0\" width=\"_pagewidth_\">\n";

	foreach my $letter (sort(keys %letter_to_name_mapping)) {
	    print BROWSER_MACROFILE "<tr><td width=\"50%\"><br /><a name=\"$letter\"/><span style=\"color: black;\"><b>$letter</b></span></td><td width=\"50%\"></td></tr>\n";

	    my @letter_names = sort(@{$letter_to_name_mapping{$letter}});
	    my $half_point = ((scalar(@letter_names) % 2 == 0) ? scalar(@letter_names) / 2 : (scalar(@letter_names) + 1) / 2);
	    for (my $i = 0; $i < $half_point; $i++) {
		print BROWSER_MACROFILE "<tr>";

		my $name = $letter_names[$i];
		my $id = $name_to_id_mapping->{$name};
		my $extra = $id_to_extra_mapping->{$id};
		print BROWSER_MACROFILE "<td valign=\"top\"><a href=\"_gwcgi_?a=d&d=$id_prefix$id\">$name</a>$extra</td>";

		$name = $letter_names[$i+$half_point];
		if (defined($name)) {
		    $id = $name_to_id_mapping->{$name};
		    $extra = $id_to_extra_mapping->{$id};
		    print BROWSER_MACROFILE "<td valign=\"top\"><a href=\"_gwcgi_?a=d&d=$id_prefix$id\">$name</a>$extra</td>";
		}
		else {
		    print BROWSER_MACROFILE "<td></td>";
		}

		print BROWSER_MACROFILE "</tr>\n";
	    }
	}

#  	my $last_name = "";
#          my $current_letter = "";
#          my $current_position = 0;
#  	foreach my $name (sort(@{$category_to_names_mapping->{$category}})) {
#  	    # Ignore duplicates
#  	    next if ($name eq $last_name);

#  	    $name =~ /^(.)/;
#  	    if ($1 ne $current_letter) {
#  		if ($current_position > 0) {
#  		    while ($current_position > 0) {
#  			print BROWSER_MACROFILE "<td></td>";
#  			$current_position--;
#  		    }
#  		    print BROWSER_MACROFILE "</tr>\n";
#  		}
#  		if ($table_columns == 2) {
#  		    print BROWSER_MACROFILE "<tr><td width=\"50%\"><br /><a name=\"$1\"/><span style=\"color: black;\"><b>$1</b></span></td><td width=\"50%\"></td></tr>\n";
#  		}
#  		else {
#  		    print BROWSER_MACROFILE "<tr><td width=\"33%\"><br /><a name=\"$1\"/><span style=\"color: black;\"><b>$1</b></span></td><td style=\"padding-left: 3px; padding-right: 3px;\" width=\"34%\"></td><td width=\"33%\"></td></tr>\n";
#  		}
#  		$current_letter = $1;
#  	    }

#  	    my $id = $name_to_id_mapping->{$name};
#  	    my $extra = "";
#  	    if (defined($id_to_extra_mapping)) {
#  		$extra = $id_to_extra_mapping->{$id};
#  	    }

#  	    if ($current_position == 0) {
#  		print BROWSER_MACROFILE "<tr>";
#  	    }
#  	    if (!defined($name) || !defined($id_prefix) || !defined($id) || !defined($extra)) {
#  		print STDERR "Name: $name\n";
#  		print STDERR "ID prefix: $id_prefix\n";
#  		print STDERR "ID: $id\n";
#  		print STDERR "Extra: $extra\n";
#  	    }
#  	    print BROWSER_MACROFILE "<td valign=\"top\"><a href=\"_gwcgi_?a=d&d=$id_prefix$id\">$name</a>$extra</td>";
#  	    $current_position++;
#  	    if ($current_position == $table_columns) {
#  		print BROWSER_MACROFILE "</tr>\n";
#  		$current_position = 0;
#  	    }

#  	    $last_name = $name;
#  	}

	print BROWSER_MACROFILE "}\n\n";
    }

    close(BROWSER_MACROFILE);
}


sub write_state_browser_macrofile
{
    my $static_browser_package_name = shift(@_);
    my $state_to_name_mapping = shift(@_);
    my $name_to_id_mapping = shift(@_);

    my $static_browser_macrofile_path = "$ENV{'GSDLHOME'}\\collect\\cic-hcap\\macros\\$static_browser_package_name.dm";
    print STDERR "Writing $static_browser_macrofile_path...\n";
    open(BROWSER_MACROFILE, ">$static_browser_macrofile_path") or die "Error: Could not write to $static_browser_macrofile_path.\n";
    print BROWSER_MACROFILE "package $static_browser_package_name\n\n";
    print BROWSER_MACROFILE "_cicstaticbrowser_ {\n";

    print BROWSER_MACROFILE "<center><b>";
    foreach my $letter (split(//, "ABCDEFGHIJKLMNOPQRSTUVWXYZ")) {
	# if ($letter !~ /[BEJQXYZ]/) {
	print BROWSER_MACROFILE "<a href=\"#$letter\">$letter</a>&nbsp;";
	# }
	# else {
	# print BROWSER_MACROFILE "<span style=\"color: #999999\">$letter</span>&nbsp;";
	# }
    }
    print BROWSER_MACROFILE "</b></center>\n";

    print BROWSER_MACROFILE "<table cellpadding=\"0\" cellspacing=\"0\" width=\"_pagewidth_\">\n";

    my $current_letter = "";
    my $current_position = 0;
    foreach my $state (sort(keys %$state_to_name_mapping)) {
	if ($current_position > 0) {
	    while ($current_position > 0) {
		print BROWSER_MACROFILE "<td></td>";
		$current_position--;
	    }
	    print BROWSER_MACROFILE "</tr>\n";
	}

	print BROWSER_MACROFILE "<tr><td width=\"33%\"><br />";
	$state =~ /^(.)/;
	if ($1 ne $current_letter) {
	    print BROWSER_MACROFILE "<a name=\"$1\"/>";
	    $current_letter = $1;
	}
	print BROWSER_MACROFILE "<span style=\"color: black;\"><b>$state</b></span></td><td style=\"padding-left: 3px; padding-right: 3px;\" width=\"34%\"></td><td width=\"33%\"></td></tr>\n";

	foreach my $name (sort(@{$state_to_name_mapping->{$state}})) {
	    my $id = $name_to_id_mapping->{$name};

	    if ($current_position == 0) {
		print BROWSER_MACROFILE "<tr>";
	    }
	    print BROWSER_MACROFILE "<td valign=\"top\"><a href=\"_gwcgi_?a=d&d=i$id\">$name</a></td>";
	    $current_position++;
	    if ($current_position == 3) {
		print BROWSER_MACROFILE "</tr>\n";
		$current_position = 0;
	    }
	}
    }

    print BROWSER_MACROFILE "}\n";
    close(BROWSER_MACROFILE);
}


1;
