# ==============================================================================
# Replace NLS string definitions in source file
#
# Copyright (c) 2012-2013 by the developers. See the LICENSE file for details.
#
# Every NLS string definition 'NLS_STRING()' is replaced with the corresponding
# 'nls_getstring()' function call (which will retrieve the string from the NLS
# catalog of the current locale)
#
# Note:
# If a 'NLS_STRING()' definition is commented out or disabled by a preprocessor
# directive this program use a dummy string as a replacement (for debugging
# only).


# ==============================================================================
# Init

BEGIN \
{
   # File where to search NLS string
   fn = "nls/string_table"
}


# ==============================================================================
# Replace NLS strings in source code with function calls to NLS module

{
   pos = 1
   do
   {
      # Search for 'NLS_STRING()'
      matched_exp = substr($0, pos)
      rv = match(matched_exp, /NLS_STRING\("[^)]*"\)/)
      if(rv)
      {
         # Found
         matched_exp = substr(matched_exp, RSTART, RLENGTH)

         # Print part before
         spart = substr($0, pos, RSTART - pos)
         printf("%s", spart)

         # Set position to rest of line
         pos = pos - 1 + RSTART + RLENGTH

         # Extrakt parameter of 'NLS_STRING()'
         if(match(matched_exp, /".*"/))
         {
            nls_str = substr(matched_exp, RSTART, RLENGTH)
            nls_no = search_nls_string(nls_str)
            if(!nls_no)
            {
               # String not found
               # This dummy replacement should never become compiled!
               # It is only allowed to occur in strings that are commented
               # out or removed by a preprocessor directive)
               printf("\"No TL found\"")
            }
            else
            {
               printf("nls_getstring(%d, %s)", nls_no, nls_str)
            }
         }
      }
   }
   while(rv != 0)

   # Print rest of line
   spart = substr($0, pos)
   printf("%s", spart)

   # Terminate line
   printf("\n")

   next
}


# ==============================================================================
# Search string in string table and return its number
# Zero is returned if the string was not found

function search_nls_string(s) \
{
   # Open file
   if(-1 == getline cur <fn)  exit(1)

   # Search string
   do
   {
      if(match(cur, /^".*"/))
      {
         if(substr(cur, RSTART, RLENGTH) == s)
         {
            # String found
            # Extract number
            sno = substr(cur, RSTART + RLENGTH)
            if(match(sno, /[ ]*[0123456789]*/))
            {
               no = substr(sno, RSTART, RLENGTH)
               if(close(fn))  exit(1)
               return(no + 0)
            }
         }
      }
   }
   while(1 == getline cur <fn)

   # String not found
   # Close file
   if(close(fn))  exit(1)
   return 0
}


# EOF
