#!/bin/sh

#
# Output Native-English const name table
# (Both Cygwin and w64devkit are OK!)
#

FILE=$1

if [ "$FILE" = "" ]; then
  echo "[USAGE]"
  echo "$0 index.json.orig > native-english-table.utf-8.txt"
  exit
fi

AWK_ARG=`sh get_awk-args.sh`

cat $FILE | tr -d '\r' | awk $AWK_ARG '{ \
  p0 = match($0, /IAU constellation name/); \
  p1 = match($0, /["]common_name["]:/); \
  if ( NR == 1 ) { \
    count = 0; \
    idx_bootes = 0; \
    str_bootes = sprintf("%c%s%c",34,"Bootes",34); \
  } \
  if ( 0 < p0 && 0 < p1 ) { \
    p_cmm = match($0, /[,][ ]*$/); \
    names0 = substr($0,p1+15); \
    gsub(/^[{]/, "", names0); \
    gsub(/[}][,]*[ ]*$/, "", names0); \
    split(names0, arr_names, ","); \
    native_str = ""; \
    english_str = ""; \
    for ( i=1 ; i <= length(arr_names) ; i++ ) { \
      gsub(/^[ ]*/, "", arr_names[i]); \
      gsub(/[ ]*$/, "", arr_names[i]); \
    } \
    for ( i=1 ; i <= length(arr_names) ; i++ ) { \
      if ( substr(arr_names[i],2,6) == "native" ) { \
        gsub(/["]Bo.*tes["]/, str_bootes, arr_names[i]); \
        native_str = arr_names[i]; \
        break; \
      } \
    } \
    if ( native_str != "" ) { \
      for ( i=1 ; i <= length(arr_names) ; i++ ) { \
        if ( substr(arr_names[i],2,7) == "english" ) { \
          gsub(/["]Bo.*tes["]/, str_bootes, arr_names[i]); \
          english_str = arr_names[i]; \
          break; \
        } \
      } \
      if ( english_str != "" ) { \
        count ++; \
        if ( count == 1 ) { \
          printf("array set asarr_native_to_english {\n"); \
        } \
        gsub(/^["][a-z][a-z]*["]:[ ]/, "", native_str); \
        gsub(/^["][a-z][a-z]*["]:[ ]/, "", english_str); \
        if ( native_str == str_bootes ) { \
          idx_bootes = count; \
          printf("  %s %s\n",native_str,english_str); \
        } \
        else { \
          printf("  %s %s\n",native_str,english_str); \
        } \
        arr_english_names[count] = english_str; \
      } \
    } \
  } \
  if ( count == 88 ) { \
    printf("}\n"); \
#    len = length(arr_english_names[idx_bootes]); \
#    for ( i=1+2 ; i <= len ; i++ ) { \
#      for ( j=32 ; j <= 255 ; j++ ) { \
#        c0 = sprintf("%c",j) ; \
#        c1 = substr(arr_english_names[idx_bootes],i-1,1); \
#        if ( c0 == c1 ) { \
#          break; \
#        } \
#      } \
#      if ( i == 1+2 ) { \
#        printf("set asarr_native_to_english(%s) [format ",substr(str_bootes,2,length(str_bootes)-2)); \
#        for ( k=1+2 ; k <= len ; k++ ) { \
#          printf("%cc",37); \
#        } \
#        printf(" "); \
#      } \
#      else { \
#        printf(" "); \
#      } \
#      printf("%d",j); \
#    } \
#    printf("]\n");
    printf("\n");
    printf("var constellation_dac = new Array("); \
    for ( i=1 ; i <= count ; i++ ) { \
      if ( 1 < i ) { \
        printf(","); \
      } \
      printf("%s",arr_english_names[i]); \
    } \
    printf(");\n"); \
    count = 0; \
  } \
}'

