#!/usr/bin/ksh

##  Count selected cell numbers after sorting by size.
##  Usage:  countcells  inputfile
##  Output is saved as new_inputfile
##
##  First created:   Jian-Guo Li    26 Feb 2010
##  Last modified:   Jian-Guo Li     2 Sep 2020
##

##  Use given input files.
#
if [ $# -lt 1 ]
  then echo "$0: Usage is $0 cell_array "
  exit 1
fi
#
clary=$1
if test ! -f "$clary"                    # Check if input file exists
  then
  echo "$clary does not exist"
  exit 1
fi

##  sort according to y-size then j and i count
      sort -s -k 4,4n -k 2,2n -k 1,1n  $clary > new$clary 

##  cut out y-size field for counting
#     cut -c18-22 new$clary > temp3
##  awk selects y-size column 4 for counting
      awk '{print $4}' new$clary > temp3

##  count the different sizes
      N1=`grep '^1' temp3 | wc -l `
      N2=`grep '^2' temp3 | wc -l `
      N4=`grep '^4' temp3 | wc -l `
      N8=`grep '^8' temp3 | wc -l `
      N12=`expr $N1 + $N2`
      N48=`expr $N4 + $N8`
      N9R=`expr $N48 + $N12`
#     NCp1=`cat temp3 | wc -l `
#     NC=`expr $NCp1 - 1`
      NC=`cat temp3 | wc -l `
      N9=`expr $NC - $N9R`
      NE=`echo ${N1}*8 + ${N2}*4 + ${N4}*2 + ${N8}*1 | bc`
#   echo "Equivalent number NE/NC = ${NE}/$NC"

    echo "  NE   NC   N1  N2  N4  N8  N9"
    echo " "$NE  $NC  $N1 $N2 $N4 $N8 $N9 
    echo " "$NC  $N1 $N2 $N4 $N8 $N9 > temp8
    cat temp8 new$clary > New_$clary 

    rm temp3 temp8 new$clary

   exit 0

