#! /bin/sh

# Utility to change the number of registers in the virtual machine.
#
# Usage:  misc/set-regs [ <NB_GVM_REGS> [ <NB_ARG_REGS> ]]

NB_GVM_REGS=$1
NB_ARG_REGS=$2

if [ "$NB_GVM_REGS" = "" ] ; then
  NB_GVM_REGS=5
fi

if [ "$NB_ARG_REGS" = "" ] ; then
  NB_ARG_REGS=3
fi

if [ "$NB_GVM_REGS" -lt 3 ] ; then
  echo "NB_GVM_REGS=$NB_ARG_REGS but it must be >= 3"
  exit 1
fi

if [ "$NB_GVM_REGS" -gt 25 ] ; then
  echo "NB_GVM_REGS=$NB_ARG_REGS but it must be <= 25"
  exit 1
fi

if [ "$NB_ARG_REGS" -lt 1 ] ; then
  echo "NB_ARG_REGS=$NB_ARG_REGS but it must be >= 1"
  exit 1
fi

if [ "$NB_ARG_REGS" -gt 12 ] ; then
  echo "NB_ARG_REGS=$NB_ARG_REGS but it must be <= 12"
  exit 1
fi

if [ "$NB_ARG_REGS" -gt `expr $NB_GVM_REGS - 2` ] ; then
  echo "NB_ARG_REGS=$NB_ARG_REGS but it must be <= `expr $NB_GVM_REGS - 2`"
  exit 1
fi

# Make sure the bootstrap compiler is built.

make -j 2

# Save the current bootstrap compiler just in case something goes wrong.

cp gsc-boot gsc-boot-old

# Set the number of registers in the gsc/_t-c-1.scm file.

sed -e "s/(set! targ-nb-gvm-regs [0-9]*)/(set! targ-nb-gvm-regs $NB_GVM_REGS)/" -e "s/(set! targ-nb-arg-regs [0-9]*)/(set! targ-nb-arg-regs $NB_ARG_REGS)/" gsc/_t-c-1.scm > gsc/_t-c-1.scm-new

mv gsc/_t-c-1.scm-new gsc/_t-c-1.scm

# Build the new bootstrap compiler.

make -j 2

make bootstrap

# Set the number of registers in the include/gambit.h file.

sed -e "s/#define ___NB_GVM_REGS [0-9]*/#define ___NB_GVM_REGS $NB_GVM_REGS/" -e "s/#define ___NB_ARG_REGS [0-9]*/#define ___NB_ARG_REGS $NB_ARG_REGS/" include/gambit.h.in > include/gambit.h.in-new

mv include/gambit.h.in-new include/gambit.h.in

# All the .c files previously generated by gsc are now invalid.

make bootclean

# Build the system using the new compiler.

make -j 2
