#!/bin/sh -
#@ Generate gen-cmd-tab.h.  See [.]src/mx/{cmd.c,cmd-tab.h}.
#
# Public Domain

: ${IN:=src/mx/cmd-tab.h}
: ${OUT:=src/mx/gen-cmd-tab.h}
: ${awk:=awk}

# Generate a more verbose output.  Not for shipout versions.
VERB=1
DEBUG=0

##

LC_ALL=C

if [ ${#} -ne 0 ]; then
   if [ "${1}" = noverbose ]; then
      shift
      VERB=0
      export VERB
   else
      echo >&2 'Invalid usage'
      exit 1
   fi
fi

< "${IN}" > "${OUT}" exec ${awk} -v O=${OUT} -v V=${VERB} -v D=${DEBUG} '
   BEGIN{
      hot = cnt = 0
      defidx = -1
      lc = ""
   }

   /^[ 	]*\/\* --MKTAB-START-- \*\/[ 	]*$/{hot = 1}
   /^[ 	]*\/\* --MKTAB-END-- \*\/[ 	]*$/{hot = 0}
   /^[ 	]*\{[ 	]*"/{
      i = index($0, "\"")
      x = substr($0, i + 1)
      i = index(x, "\"")
      if(i == 0){
         print "FAULTY COMMAND, I: <" $0 ">" >> "/dev/stderr"
         next
      }
      x = substr(x, 1, i - 1)
      if(length(x) == 0){
         print "FAULTY COMMAND, II: <" $0 ">" >> "/dev/stderr"
         next
      }

      c = substr(x, 1, 1)
      if(lc != c && abc[c] == ""){
         if(D)
            print "SWITCH TO LETTER " c " AT " cnt >> "/dev/stderr"
         abc[lc = c] = cnt
      }

      if($0 ~ /\/\*[ 	]*--MKTAB-DFL--[ 	]*\*\//){
         if(V)
            print "DEFAULT COMMAND IS <" x "> at " cnt >> "/dev/stderr"
         defidx = cnt
      }
      ++cnt
   }

   END{
      if(defidx == -1){
         print "FAULT: NO DEFAULT COMMAND" >> "/dev/stderr"
         defidx = 0
      }
      t = (cnt < 256) ? "u8" : "u16"


      print "/*@ " O ", generated by mk/make-cmd-tab.sh."
      print " *@ See cmd.c and cmd-tab.h for more */"
      print ""
      print "#define a_CMD_DEFAULT_IDX " defidx
      print "#define a_CMD_COUNT " cnt

      printf("static %s const %s[128] = {\n#undef a_X\n#define a_X %s",
         t, "a_cmd__cidx", "a_CMD_COUNT")
      for(i = 1; i <= 128; ++i){
         if(i == 1 || i % (V ? 5 : 10) == 0){
            printf("\n   ")
            if(V)
               printf("/* 0x%X */", i - 1)
         }
         c = sprintf("%c", i - 1)
         x = (abc[c] != "") ? abc[c] : "a_X"
         printf("%s%s,", (V ? " " : ""), x)
      }
      printf("\n#undef a_X\n};\n")

      printf("%s %s %s\n",
         "#define", "a_CMD_CIDX(C)",
         "(S(u8,C) <= 127 ? a_cmd__cidx[S(u8,C)] : a_CMD_COUNT)")
      print("CTAV(a_CMD_COUNT == NELEM(a_cmd_ctable));")
   }
'

# s-sh-mode
