#!/bin/sh 
#
#  Date: Fri May 10 10:15:56 CDT 2019
#  Name: pop
#
#  This will output a sorted list of
#  countries by population.
#
#  The default population cutoff is 3 million
#  the option -c <number> can be used to override
#  this default value.
#
#  The output is sorted by Ranking by default
#  the option -s caned be used to requested 
#  the output sorted by Country Code
#

USAGE="pop [-s] [-c number] population_file"

CUTOFF=3
SORT='no'

while getopts ":c:s" INPUT
do
	case $INPUT in
		s) SORT='yes' ;;
		c) CUTOFF=${OPTARG} ;;
		*) echo "$USAGE"
		   echo "error bad option ${OPTARG}"
	       exit 1;;
	esac
done

# remove the command line options
shift $(( OPTIND - 1 ))

if [[ $# -ne 1 ]]
then
  echo "$USAGE"
  exit 2
fi

if [[ ! -r $1 ]]
then
  echo "$USAGE"
  exit 3
fi

IFS=','
CUTOFF=$(( CUTOFF * 1000 ))
TEMP="/tmp/pop.$$"

exec 3< $1

while read CODE RANK NAME POP <&3
do
   if [[ $POP -ge $CUTOFF ]]
   then
	 printf "\t%3s %3d %10d\t%s\n" $CODE $RANK $POP $NAME >> $TEMP
   fi
done

exec 3<&-

if [[ $SORT == 'yes' ]]
then
  /bin/sort  -o $TEMP  $TEMP
fi

cat $TEMP
rm $TEMP
exit 0     
