#!/usr/bin/perl

use XBase;

opendir(DIR, '.');
foreach $file (readdir(DIR)) {
    next if !($file =~ /\.dbf$/);

    print "Working on $file...\n";

    $tfile = 'temporary.dbf';
    system("mv $file $tfile");

    $oldtable = new XBase $tfile or die XBase->errstr;

    print join("\t", $oldtable->field_names) ."\n";
    print join("\t", $oldtable->field_types) ."\n";
    print join("\t", $oldtable->field_lengths) ."\n";
    print join("\t", $oldtable->field_decimals) ."\n";

    $newtable = XBase->create("name" => $file, 
			      "field_names" => [$oldtable->field_names, "IMGDATE"], 
			      "field_types" => [$oldtable->field_types, "C"], 
			      "field_lengths" => [$oldtable->field_lengths, 8], 
			      "field_decimals" => [$oldtable->field_decimals, undef]) or die "Error creating new table.";

    foreach (0 .. $oldtable->last_record) {
	($deleted, @data) = $oldtable->get_record($_);
  
	print "  ...record $data[0]\n";

        # extract the date
        $year = substr $data[0], 7, 4;
	$day = substr $data[0], 11, 3;

	push @data, "$year-$day";
	$newtable->set_record($_, @data);
    }

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

    unlink($tfile);
}
