#!/usr/bin/perl -w
#
# GPSy Extended Format -> TrkDB-GPil.pdb
# Nowral
# 01/10/4
#
# initialize
use Time::Local;
$t0 = timelocal(0,0,0,31,11,89); # 31-12-89 0:00
$t0 += 9 * 3600; # Japanese Standard Time
$ds = 180 / 2147483648; # degree / semicircle = 180 / 2^31
$h0 = unpack("f", pack("H8", "69045951")); # unknown altitude = 1.0e25
undef @trds;
$trd = \x00 x (288+4500*18); # dummy process for memory allocation
print "-"x70, "\n";
# file loop begin
foreach $oldargv (sort @ARGV) {
open(IN, $oldargv) || next;
$oldargv =~ /(.+:)(.+)/;
$name = $2;
print "\"$name\"";
# read file
$trd = "";
$nr = 0;
$trn = 0;
($bmin, $bmax, $lmin, $lmax) = (90/$ds, -90/$ds, 180/$ds, -180/$ds);
while (<IN>) {
next unless(/^T\t/);
@ed = split("\t");
# date
$t = ($ed[4] =~ /(\d+)\/(\d+)\/(\d+) (\d+):(\d+):(\d+)/) ?
timelocal($6,$5,$4,$2,$1-1,$3-1900)-$t0 : 0;
# latitude
$ed[5] =~ /(-?)(\d+)。(\d+)'(\d+\.?\d*)"/;
$b = ($1 ? -1 : 1) * ($2 + $3/60 + $4/3600);
$b = int($b/$ds + 0.5);
$bmin = $b if($bmin>$b);
$bmax = $b if($bmax<$b);
# longitude
$ed[6] =~ /(-?)(\d+)。(\d+)'(\d+\.?\d*)"/;
$l = ($1 ? -1 : 1) * ($2 + $3/60 + $4/3600);
$l = int($l/$ds + 0.5);
$lmin = $l if($lmin>$l);
$lmax = $l if($lmax<$l);
# altitude
$h = ($ed[8] eq "-") ? $h0 : $ed[8]+0;
# encode position, time, altitude, new_track # Custom_Trk_Point_Type
$trd .= pack("NNNfCC", $b, $l, $t, $h, ($trn==$ed[1]) ? 0 : 1, 0);
$trn = $ed[1];
++$nr;
# last if $nr>4500;
}
close(IN);
print " ($nr)\n";
# internal track header # Custom_Trk_Hdr_Type
if($nr) {
$hd = pack ("H16a256ccH4nNNNNH4", (
"6500011600000002", $name, 1, -1, "6600",
$nr, $bmin, $bmax, $lmin, $lmax, "0000" ) );
push(@trds, $hd.$trd);
}
# file loop end
}
$ntr = $#trds + 1;
print "\n# Tracks: $ntr\n";
die unless $ntr;
# pdb_header
$t = time;
$hd = pack("a32nnNNNNNNa4a4NNn",
("TrkDB-GPil", 8, 0, $t, $t, $t, 0, 0, 0, "Trks", "GPil", 0, 0, $ntr) );
# pdb_rec_header
$ofs = 78 + $ntr*8; # offset to first record
foreach $i (0 .. $ntr-1) {
$hd .= pack("NN", $ofs, 0x406F8000+$i);
$name = unpack("a256", substr($trds[$i], 8, 256));
$name =~ s/\x00.*$//;
printf "%d) [%04X] ---> \"%s\" (%d)\n",
$i+1, $ofs, $name, (length($trds[$i])-288)/18;
$ofs += length($trds[$i]);
}
# output file
$0 =~ /(.+:)/;
$newargv = "$1TrkDB-GPil.pdb";
open(OUT, ">$newargv") || die;
MacPerl::SetFileInfo('Gld1', 'Gld0', $newargv);
print OUT $hd, @trds;
close(OUT);
print "-"x70, "\n";
#MacPerl::Quit(2);
die "The Unhappy End";