#!/usr/bin/perl

use XBase;

$scratch = '/tmp/';

$shpstore = '/net/lobo/lobo04/samba_ac/shapelib/';
$web_shpstore = '/usr/local/www/data/shapefiles/';

$sortshp = '/export/stlime/mapserv/bin/sortshp';
$shptree = '/export/stlime/mapserv/bin/shptree';

@extensions = ('.dbf', '.idx', '.qix', '.shp', '.shx');

sub build_spatial_index() {
  my($file, $depth) = @_;

  die 'No source file supplied.' unless $file;
  die 'Quadtree depth must be greater than zero.' unless $depth > 0;

  system("$shptree $file $depth");
}

sub clean() {
  my($base) = @_;

  foreach (@extensions) {
    system("rm $base".$_);
  }
}

sub copy() {
  my($from_base, $to_base) = @_;

  die 'No source file supplied.' unless $from_base;
  die 'No destination file supplied.' unless $to_base;

  foreach (@extensions) {
    system("cp $from_base".$_." $to_base".$_);
  }
}

sub additem() {
  my($table_name, $field_name, $field_type, $field_length, $field_decimals, $initial_value) = @_;

  my $temp_table_name = $scratch.'temporary.dbf';
  system("mv $table_name $temp_table_name");

  my $oldtable = new XBase $temp_table_name or die XBase->errstr;

  my $newtable = XBase->create("name" => $table_name,
			       "field_names" => [$oldtable->field_names, $field_name],
			       "field_types" => [$oldtable->field_types, $field_type],
			       "field_lengths" => [$oldtable->field_lengths, $field_length],
			       "field_decimals" => [$oldtable->field_decimals, $field_decimal],
			       );

  foreach (0 .. $oldtable->last_record) {
    ($deleted, @data) = $oldtable->get_record($_);
    push @data, $initial_value;
    $newtable->set_record($_, @data);
  }

  $newtable->close();
  $oldtable->close();

  unlink($temp_table_name);
}
