check_order (version 2.0)

You can also look at:
#! /usr/bin/perl

##############################################################################
#
# SYNTAX: check_order file column
#
# DESCRIPTION: This utility checks if a column of a FITS file bintable
# DESCRIPTION: is in increasing order. If it isn't, issue an exception and
# DESCRIPTION: sort the file.
#
# VERSION: 2.0
#
# HISTORY: 0.0 -> 1.0 4/9/98
# HISTORY: Changed "column" to "columns" for fmemsort parameter to
# HISTORY: accomodate FTOOLS 4.1
# HISTORY: 
# HISTORY: 1.0 -> 2.0 1999-05-07
# HISTORY: Converted from ksh to perl
#
# CALLS: $UTIL/log_entry
# CALLS: $UTIL/ftool_test
# CALLS: $UTIL/exception
# CALLS: $FTOOL/cktime
# CALLS: $FTOOL/fmemsort
#
##############################################################################

($file, $column) = @ARGV;

$UTIL = $ENV{"UTIL"};
$FTOOL = $ENV{"FTOOL"};

`$UTIL/log_entry "Checking if column $column in $file is in order"`;

`$FTOOL/cktime infile=$file    \\
               colname=$column \\
               ckequal=yes >stdout${$}.log 2>stderr${$}.log`;
$code = $?;
chomp($ordered = `grep ORDERED stdout${$}.log`);
`$UTIL/ftool_test cktime $code $0 2 stdout${$}.log stderr${$}.log`;

if ( !$ordered ) {
    ###################################
    # File is out of order, so sort it
    ###################################
    `$UTIL/exception $0 1 "Sorting column $column in $file"`;

    unlink 'out.tmp';

    `$FTOOL/fmemsort infile=$file      \\
                     outfile='out.tmp' \\
                     column=$column    \\
                     method=insert     \\
                     ascend=yes        \\
                     copyall=yes       \\
                     history=yes       >stdout${$}.log 2>stdout${$}.log`;

    `$UTIL/ftool_test fmemsort $? $0 2 stdout${$}.log stderr${$}.log`;

    if ( -s 'out.tmp' ) {
        rename 'out.tmp', $file;
    }
    unlink 'out.tmp';
}

exit 0;