#!/usr/bin/perl -w

# Felix Andrews 2003
# Output the ordered coordinates of a tour,
# given list of whitespace-separated indices (base 0!).

my $tour_file = $ARGV[0];
my $coord_file = $ARGV[1];

if (!$coord_file) {
  print "Usage: tourtrace.pl tour_file coord_file\n";
  exit 1;
}

my (@city_x, @city_y);

open COORD, "<$coord_file" or die "can't open coord file: $!\n";
my $header = 1;
while (my $line = <COORD>) {
  chomp $line;
  $line =~ s/^\s*//;
  $line =~ s/\s*$//;
  if ($line =~ /NODE_COORD_SECTION/) {
	$header = 0;
	next;
  }
  if ($header) {next;}
  if ($line =~ /EOF/) {last;}
  # read a city
  my ($s, $x, $y) = split(/\s+/, $line);
  my $i = int($s);
  $city_x[$i] = $x;
  $city_y[$i] = $y;
}
close COORD;

open TOUR, "<$tour_file" or die "can't open tour file: $!\n";
my $i0 = -1;
while (my $line = <TOUR>) {
  chomp $line;
  $line =~ s/^\s*//;
  $line =~ s/\s*$//;
  my @cities = split(/\s+/, $line);
  foreach my $s (@cities) {
	my $i = int($s) + 1; # move from base 0 to base 1
	if ($i0 == -1) {$i0 = $i;}
	print $i . "\t" . $city_x[$i] . "\t" . $city_y[$i] . "\n";
  }
}
close TOUR;

# back to starting point
print $i0 . "\t" . $city_x[$i0] . "\t" . $city_y[$i0] . "\n";

