#!/bin/sh

SRC_BCC='bcc.c'
SRC_CPP='main.c cpp.c hash.c token1.c token2.c'
SRC_UPR='unproto.c error.c hash.c strsave.c symbol.c tok_clas.c tok_io.c
	 tok_pool.c unproto.c vstring.c'
SRC_CC1='bcc-cc1.c assign.c codefrag.c debug.c declare.c express.c exptree.c
         floatop.c function.c gencode.c genloads.c glogcode.c hardop.c input.c
         label.c loadexp.c longop.c output.c preproc.c preserve.c scan.c
         softop.c state.c table.c type.c'
SRC_AS=' alloc.c as.c assemble.c errors.c express.c genbin.c genlist.c genobj.c
         gensym.c keywords.c macro.c mops.c pops.c readsrc.c scan.c table.c
	 typeconv.c'
SRC_LD=' ld.c dumps.c io.c linksyms.c readobj.c table.c typeconv.c
         writebin.c writex86.c'

SRC_UP=' unproto.c tok_io.c tok_class.c tok_pool.c vstring.c symbol.c error.c
         hash.c strsave.c'

main() {
   echo    '@echo off'

   CFLAGS='-nologo -O'
   LDFLAGS='%LIB%\setargv.obj -link /NOE'
   ARCH=-Ms
   build bcc bcc     bin $SRC_BCC

   CFLAGS='-nologo -O -DPOSIX_HEADERS_MISSING'
   LDFLAGS=
   ARCH=-Ml

   build cpp bcc-cpp lib $SRC_CPP
   build bcc bcc-cc1 lib $SRC_CC1
   build as  as86    bin $SRC_AS
   build ld  ld86    bin $SRC_LD

   build unproto unproto lib $SRC_UPR

   echo "echo Compile complete."
   echo ":exit_now"
}

build() {
   DIR="$1" ; shift
   PRG="$1" ; shift
   BIN="$1" ; shift
   OBJ=
   BOBJ=
   COBJ=
   LOBJ=
   SRC="$*"

   for i in $SRC
   do
      j=`basename $i .c`

      echo "cl $ARCH $CFLAGS -c -Fo%TMP%\\$j.obj $DIR\\$i"
      if [ "$BOBJ" = "" ]
      then BOBJ="%TMP%\\$j.obj"
      else LOBJ="$LOBJ +%TMP%\\$j.obj"
      fi
      COBJ="$COBJ %TMP%\\$j.obj"
      OBJ="$OBJ $j.obj"

      echo "if errorlevel 1 goto exit_now"
   done
   echo 

   if [ `echo $COBJ | wc -c` -lt 50 ]
   then
        echo "cl $ARCH -o $BIN\\$PRG.exe$COBJ $LDFLAGS"
        echo "if errorlevel 1 goto exit_now"
   else
        echo "if exist %TMP%\\doslib.lib del %TMP%\\doslib.lib"
        echo $LOBJ | fmt -62 | \
	sed "s/\(.*\)/lib %TMP%\\\\doslib.lib \1; /" |
	sed 's/$/@if errorlevel 1 goto exit_now/' |
	tr '@' '\012'
	echo
        echo "cl $ARCH -o $BIN\\$PRG.exe $BOBJ %TMP%\\doslib.lib $LDFLAGS"
        echo "if errorlevel 1 goto exit_now"
   fi
   echo
}

main "$@" | sed 's/$/
/' > compile.bat

