#!/bin/bash

set -eo pipefail

if [ ! -z "$1" ]
then
    # Reading from a file. We have occasionally seen this error: http://www.gnu.org/software/coreutils/faq/coreutils-faq.html#Value-too-large-for-defined-data-type
    # Therefore, we now always cat the file into awk.
	if [ ! -z "$2" ]
	then
		cat $1 | awk '$0~"^#" { print $0; next } { print $0 | "sort -S 1G -k1,1V -k2,2n -k3,3n -k4,4V -k5,5n -k6,6n" }' > $2
	else
		cat $1 | awk '$0~"^#" { print $0; next } { print $0 | "sort -S 1G -k1,1V -k2,2n -k3,3n -k4,4V -k5,5n -k6,6n" }'
	fi
else
	awk '$0~"^#" { print $0; next } { print $0 | "sort -S 1G -k1,1V -k2,2n -k3,3n -k4,4V -k5,5n -k6,6n" }'
fi


