#
# Copyright (c) 2018 Tetsuya Isaki. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.

BEGIN {
       print "/* generated by mkdefs.awk */"
       print "#ifndef XPLX_DEFINE"
       print "#define XPLX_DEFINE"
}

# hex to decimal
function h2d(s,   i,c,n,rv)
{
       rv = 0
       for (i = 1; i <= length(s); i++) {
               c = toupper(substr(s, i, 1))
               n = index("0123456789ABCDEF", c)
               if (n == 0) {
                       error = 1
                       exit error
               }
               rv = rv * 16 + n - 1
       }
       return rv
}

# Global label
/::/ {
       print "/* " $0 " */"
       for (i = 1; i <= NF; i++) {
               f = $(i)
               if (f ~ /::/) {
                       break;
               }
       }
       sub(/::/, "", f)
       sub(/:/, "", $1)
       printf("#define %s 0x%s\n", f, $1);

       k = "GLOBAL_"
       keys[""] = k
       v = h2d($1)
       while (values["", v] != "") v++;
       values["", v] = f
       counts[""]++
}

$2 ~ /#define/ {
       printf("%s %s %s\n", $2, $3, $4);

       # multiple if statements
       # because match() returns index/length by global variables
       if (match($3, /^XPLX_R_/)) {
               k = substr($3, RSTART, RLENGTH)
       } else
       if (match($3, /^DEVID_/)) {
               k = substr($3, RSTART, RLENGTH)
       } else
       if (match($3, /^[^_]+_(CMD|ENC)_/)) {
               k = substr($3, RSTART, RLENGTH)
       } else {
               next
       }
       sub(k, "", $3)
       keys[k] = k
       values[k, $4] = $3
       counts[k]++
}

END {
       print "#endif /* !XPLX_DEFINE */"
}