#!/bin/bash
#find_fanin
# Copyright (c) 2008 Graham Petley
# Released under the terms of the GNU Lesser General Public Licence

# Script which gives the fanin of the netlist in $arg_1

if [ "$#" -eq 0 ]
then
  echo "# Usage: find_fanin cell" 1>&2
  echo "#" 1>&2
  echo "# lists the fanin of each input to cell.vst" 1>&2
  exit 1
fi

if test -f $1.vst
then
  cell=$1.vst
else
  echo "# Usage: find_fanin cell" 1>&2
  echo "#" 1>&2
  echo "# The cell name supplied "$1".vst does not exist. Please check." 1>&2
  exit 1
fi

max_fanin=0
sed -nr '/^ *(E|e)(N|n)(T|t)(I|i)(T|t)(Y|y) /,/^ *(E|e)(N|n)(D|d)/ p' $cell |
  grep -i bit_vector | grep ': *in ' | sed 's/^  *//' | sed 's/;.*$//' | tr -s ' ' > $$_vectors

cat $$_vectors |
while read in_vector
do
  name=$(echo $in_vector | cut -f1 -d' ')
  dir_index=$(echo $in_vector | cut -f2 -d'(' | cut -f1 -d')' | cut -f2 -d' ' | tr 'A-Z' 'a-z')
  if [ "$dir_index" = downto ]
  then
    first_index=$(echo $in_vector | cut -f2 -d'(' | cut -f1 -d')' | cut -f3 -d' ')
    second_index=$(echo $in_vector | cut -f2 -d'(' | cut -f1 -d')' | cut -f1 -d' ')
  else
    first_index=$(echo $in_vector | cut -f2 -d'(' | cut -f1 -d')' | cut -f1 -d' ')
    second_index=$(echo $in_vector | cut -f2 -d'(' | cut -f1 -d')' | cut -f3 -d' ')
  fi

  index=$first_index
  while [ "$index" -le "$second_index" ]
  do
    echo -n ${name}"("${index}")= " >> $$_inputs
    fanin=$(sed -nr '/^ *(B|b)(E|e)(G|g)(I|i)(N|n) *$/,$ p' $cell | grep -c " ${name}(${index})")
    echo $fanin >> $$_inputs
    if [ "$fanin" -gt "$max_fanin" ]
    then
      max_fanin=$fanin
      worst_input=${name}"("${index}")"
      echo "Max fanin is "$worst_input"= "$max_fanin > $$_fanin
    fi
    let index=$index+1
  done
done

sed -nr '/^ *(E|e)(N|n)(T|t)(I|i)(T|t)(Y|y) /,/^ *(E|e)(N|n)(D|d)/ p' $cell |
  egrep -i ': *in  *bit( |;|$)' | egrep -v 'vdd *:|vss *:' | sed 's/^  *//' |
  sed 's/;.*$//' | tr -s ' ' > $$_bits

cat $$_bits |
while read in_bit
do
  name=$(echo $in_bit | cut -f1 -d' ')
  echo -n ${name}"= " >> $$_inputs
  fanin=$(sed -nr '/^ *(B|b)(E|e)(G|g)(I|i)(N|n) *$/,$ p' $cell | grep -c " ${name}")
  echo $fanin >> $$_inputs
  if [ "$fanin" -gt "$max_fanin" ]
  then
    max_fanin=$fanin
    worst_input=$name
    echo "Max fanin is "$worst_input"= "$max_fanin > $$_fanin
  fi
done
sort $$_inputs
cat $$_fanin
rm $$_vectors $$_inputs $$_bits $$_fanin

