procedure PrintPath( var home : sector; sec : sector );
begin
  if home = sec then
    write( sec )
  else
    begin
      PrintPath( home, distances[ sec ].s );
      write( ' - ', sec );
    end; {induction}
end;

function FixPath( start, finish : sector ) : integer;
{ Adjusts Distances from start up to point were finish is entered;
returns length of path. }
var
  s : sector;
  breadth : queue;
  daddy, sonny : sector;
  i : warpindex;
  done : boolean;
begin
  for s := 1 to maxSector do
    Distances[s].d := -1;
  breadth.front := 0;
  enqueue( breadth, start, start );
  repeat
      serve( breadth, daddy, sonny );
      if Distances[ sonny ].d = -1 then {haven't hit him before:}
        begin
          distances[ sonny ].d := distances[ daddy ].d + 1;
          distances[ sonny ].s := daddy;
          with space.sectors[ sonny ] do if number > 0 then
            for i := 1 to number do
              enqueue( breadth, sonny, data[ i ] );
          done := sonny = finish;
        end; {if}
  until done or (breadth.front = 0);
  FixPath := distances[ finish ].d;
  for s := 1 to maxSector do
    if distances[s].d = -1 then distances[s].d := maxint;
end; {FixPath}

procedure PathLength;
var
  s1, s2 : sector;
begin
  write('Distance between which two sectors? ');
  readln( s1, s2 );
  if space.sectors[ s1 ].number <> Unexplored then
    begin
      if FixPath( s1, s2) = Error then
        writeln('You don''t know how to get to ', s2, ' from ', s1, '!' )
      else
        begin
          writeln('Known shortest path from ', s1, ' to ', s2, ' is ');
          PrintPath( s1, s2 );
          writeln;
        end; {if finite distance}
    end {visited}
  else
    writeln('Never visited ', s1, ' so can''t tell distances leaving it.');
  if space.sectors[ s1 ].number <> UnExplored then
    begin
      if FixPath( s2, s1 ) = Error then
        writeln('You don''t know how to get to ', s1, ' from ', s2, '!' )
      else
        begin
          writeln('Known shortest path from ', s2, ' to ', s1, ' is ');
          PrintPath( s2, s1 );
          writeln;
        end; {if finite distance}
    end
  else
    writeln('Never visited ', s2, ' so can''t tell distances leaving it.');
end;

procedure NearestFighters;
var
  s, s1, Closest : sector;
begin
  write('What is your current sector?  ');
  readln( s );
  TwoWayDistances( s, distances, false, true );
  Closest := 1;
  for s1 := 1 to maxSector do
    if space.sectors[ s1 ].portType = Class0 then
      if distances[ s1 ].d = maxint then
        writeln('You don''t know how to get to ', s1 )
      else
        begin
          writeln('Path to ', s1, ' is of length ', distances[ s1 ].d );
          PrintPath( s, s1 );
          writeln;
          if distances[ s1 ].d < distances[ Closest ].d then
            Closest := s1;
        end; {for if else}
end; {Nearest Fighters}

