#!/bin/bash
#
#                      ReROUTE LOOP
#
if [ "$#" -eq 0 ]
then
  echo "# Usage: nero_loop layout V|H [netlist]" 1>&2
  echo "#" 1>&2
  echo "#   loop nero until there are no more DRC errors or until the" 1>&2
  echo "#   loop limit of 50 is reached. Argument_2 is the routing" 1>&2
  echo "#   direction of metal-2. If netlist is not supplied, the" 1>&2
  echo "#   value of layout will be used." 1>&2
  exit 1
fi

layout=$1

if [ "$#" -eq 1 ]
then
  echo "# Usage: nero_loop layout V|H [netlist]" 1>&2
  echo "#" 1>&2
  echo "#   No metal-2 direction has been given. Please check." 1>&2
  exit 1
else
  route_dir=$2
fi

if [ "$#" -eq 2 ]
then
  netlist=$1
else
  netlist=$3
fi

if ! test -d $MBK_TARGET_LIB
then
  echo "#?! No MBK_TARGET_LIB found. Please check." 1>&2
  break
fi

rm -f emergency.ap
block_count=0; strip=0
err_count=$(grep 'ERROR Code' ${layout}.drc | egrep -c '921|1521|2221|2621')
loop_count=1
loop_limit=50
echo "# Loop $loop_count with $err_count errors and $block_count blockages"

while [ "$err_count" -gt 0 ]
do
  $VIA_DRC_BLOCK ${layout}
  if [ "$strip" -eq 1 ]
  then
    $STRIP_BLOCKAGES ${layout} ${layout}_bg $route_dir
    strip=0
  fi
  block_count=$(grep -c mosl ${layout}_bg.ap)
  nice -10 $NERO -2 -L -p ${layout}_p ${netlist} ${layout} > /dev/null
  if test -e emergency.ap
  then
    rm -f emergency.ap
    strip=1;
    echo "# Loop $loop_count failed to complete"
    let loop_count=$loop_count+1
    if [ "$loop_count" -ge "$loop_limit" ]
    then
      break
    fi
  fi
  if [ "$strip" -eq 1 ]
  then
    continue
  fi
  sed -i '/zzzblock/ d' ${layout}.ap
  $VIA_OVERLAP ${layout} $route_dir > /dev/null
  $SIMPLE_BLOCK ${layout} TALU1 big > /dev/null
  $SIMPLE_BLOCK ${layout} TALU2 small > /dev/null
  $SIMPLE_BLOCK ${layout} TALU3 small > /dev/null
  $SIMPLE_BLOCK ${layout} TALU8 big > /dev/null
  $DRUC ${layout} > /dev/null
  err_count=$(grep 'ERROR Code' ${layout}.drc | egrep -c '921|1521|2221|2621')
  let loop_count=$loop_count+1
  echo "# Loop $loop_count with $err_count errors and $block_count blockages"
  if [ "$loop_count" -ge "$loop_limit" ]
  then
    break
  fi
done
