#!/usr/bin/perl
# USGS computer program source code: qwmixsort.pl
# 
# Use of this program is described in USGS Scientific Investigations Report:
# Software for Analysis of Chemical Mixture Occurrence, Distribution, and
# Potential Toxicity by Jonathon Scott, Kenneth Skach, and Patricia Toccalino
# 
# The program is written in the Perl programming language (version 5.10.1)
# and was developed and tested on a Sun V440 with 8-GB of memory running
# SunOS 5.10.  The program has also been successfully using a Lenovo with
# 64-bit Intel G630 processors and 6-GB of memory running Microsoft Windows 7.
#
# Use of trade names is for identification purposes and does not imply
# endorsement by the U.S. Geological Survey.  Perl and applicable Perl
# packages are free software, made available under an Artistic License.
# http://perldoc.perl.org/perlartistic.html
#
# Although this program has been used by the USGS, no warranty, expressed or
# implied, is made by the USGS or the United States Government as to the
# accuracy and functioning of the program and related program material nor
# shall the fact of distribution constitute any such warranty, and no
# responsibility is assumed by the USGS in connection therewith.
#
# Program to sort files: a program invoked by the mixture-analysis
# software and not intended for stand-alone usage.  Performance
# improvement might be achieved via threading? 
#
# Jon Scott, Oct 2008 : Initial coding
#            Sep 2012 : Improved internal documentation

# ==================================================================
# -- Perl packages used.  See:  http://cpan.org
# ==================================================================
use File::Sort qw(sort_file);
use File::Spec;
use IO::Pipe;     # used by the calling program, output -> STDOUT

# ==================================================================
# -- Command-line parsing
# ==================================================================
($Directory,$InFile,$sortkey) = @ARGV;

# ==================================================================
# -- Construct input-file pathname 
#    volume, if needed, is assumed to be embedded within directory
# ==================================================================
my ($vol,$dir) = File::Spec->splitpath($Directory,1);
my $path = File::Spec->catpath($vol, $dir, $InFile );

# ==================================================================
# -- Sort
# ==================================================================
sort_file({
         t => "\t",
	 I => $path,
	 k => $sortkey,
#	 y => 1000 # MAX_SORT_RECORDS caused very slow performance
	 y => 1000000 # MAX_SORT_RECORDS 
       });
