#!/usr/bin/perl

# Routine to sort a file full of REFERENCE objects, based on the 
# REFERENCE_KEY_ID fields.
#
#  Format:  % sortref [ reference_file  [ output_file ] ]
#
# 15 May 2000, acr: creation
#
#==============================================================================
# Begin by opening the provided files:

if (@ARGV > 2)
  { die "Usage: sortref [ reference_file [ output_file ]].\n"; }

$infile  = (@ARGV > 0)? $ARGV[0] : "-";
$outfile = (@ARGV > 1)? $ARGV[1] : "-";

open (IN,$infile)      || die "Could not open '$infile' for reading.";
open (OUT,">$outfile") || die "Could not open '$outfile' for writing.";

# Read the first line and check for 80-byte CR/LF lines:

$line = <IN>;
$padding = (length($line) == 80  &&  $line[78] == '\r');

# Skip through lines in the input file until the first OBJECT=REFERENCE line:

while ($line !~ /^\s*OBJECT\s*=\s*REFERENCE/)
  { printf OUT $line;
    $line=<IN>;
  }

# Set up the loop:

$END_found = 0;
$not_done  = 1;
while ($not_done)
  { undef $tmpref;

    # Save the entire reference in a single element of the %ref hash:

    while ($line !~ /^\s*END_OBJECT/)
      { $tmpref .= $line;
        if ($line =~ /REFERENCE_KEY_ID/)
          { $id = $line;
            chop $id;
            $id =~ s/^.*=\s*//;
            $id =~ s/\/\*.*$//;
            $id =~ s/\s*$//;
            $id =~ s/"//g;
          }
        $line = <IN>;
      }
    $tmpref .= $line;
    $ref{$id} = $tmpref;

    # Look for either the end of file or the next REFERENCE object:

    $still_looking = 1;
    while ($still_looking)
      { if ($line = <IN>)
          { if ($line =~ /^\s*END\s*$/)
              { $END_found = 1;
                $not_done  = 0;
                $still_looking = 0;
              }
            elsif ($line =~ /^\s*OBJECT\s*=\s*REFERENCE/)
              { $still_looking = 0; }
          }
        else
          { $still_looking = 0;
            $not_done      = 0;
          }
      }

    # Next reference.
  }

# OK, we've read through all the references and we've got them stored in the
# %ref hash. Now we retrieve them and output them in sorted order:

foreach $id (sort (keys %ref))
  { printf OUT $ref{$id};
    if ($padding)
      { printf OUT "%78.78s\r\n"," "; }
    else
      { printf OUT "\n"; }
  }

# If there was an END statement, we write one:

if ($END_found)
  { if ($padding)
      { printf OUT "%-78.78s\r\n","END"; }
    else
      { printf OUT "END\n"; }
  }

# Close the files, and we're done:

close(IN);
close(OUT);

          
