#!/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    12 Mar 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
      N1a=`grep '^1' temp3 | wc -l `
      N2=`grep '^2' temp3 | wc -l `
      N4=`grep '^4' temp3 | wc -l `
      N8=`grep '^8' temp3 | wc -l `
      N16=`grep '^16' temp3 | wc -l `
      N1=`expr $N1a - $N16`      ## Because N1a contains both 1 and 16 lines.
      N32=`grep '^32' temp3 | wc -l `

      NAll=`expr $N1 + $N2 + $N4 + $N8 + $N16 + $N32`
      NC=`cat temp3 | wc -l `
      N9=`expr $NC - $NAll`

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

    rm temp3 temp8 new$clary

   exit 0

