#!/bin/sh

#
# Replace English const names with Native names:
# (e.g., "Swan" -> "Cygnus")
# and replace non-ASCII chars in "Bootes".
#

FILE=$1

if [ "$FILE" = "" ]; then
  echo "[USAGE]"
  echo "$0 index.json.orig > index.json.new"
  echo "$0 --bootes-only index.json.orig > index.json.new"
  exit
fi

AWK_ARG=`sh get_awk-args.sh`

if [ "$2" == "--bootes-only" ]; then
  # Do not change English names, but replace non-ASCII chars in "Bootes".
  BOOTES_ONLY=1
else
  # Change English names and replace non-ASCII chars in "Bootes".
  BOOTES_ONLY=0
fi

# Do not change!
ID_NAME="modern"

cat $FILE | tr -d '\r' | awk $AWK_ARG '{ \
  p0 = match($0, /IAU constellation name/); \
  p1 = match($0, /["]common_name["]:/); \
  q0 = match($0, /["]id["]:/); \
  q1 = match($0, /["]modern["]/); \
  if ( NR == 1 ) { \
    str_bootes = sprintf("%c%s%c",34,"Bootes",34); \
  } \
  if ( 0 < q0 && 0 < q1 ) { \
    printf("  %cid%c: %c%s%c,\n",34,34,34,"'$ID_NAME'",34); \
  } \
  else if ( 0 < p0 && 0 < p1 ) { \
    count ++; \
    p_cmm = match($0, /[,][ ]*$/); \
    names0 = substr($0,p1+15); \
    gsub(/^[{]/, "", names0); \
    gsub(/[}][,]*[ ]*$/, "", names0); \
    split(names0, arr_names, ","); \
    native_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.*es["]/, 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.*es["]/, str_bootes, arr_names[i]); \
          if ( '$BOOTES_ONLY' == 0 ) { \
            arr_names[i] = native_str; \
          } \
          str_eng = sprintf("%c%s%c",34,"english",34); \
          gsub(/["]native["]/, str_eng, arr_names[i]); \
          break; \
        } \
      } \
    } \
    printf("      %ccommon_name%c: {",34,34); \
    j = 0; \
    for ( i=1 ; i <= length(arr_names) ; i++ ) { \
      if ( substr(arr_names[i],2,7) != "xxxx" ) { \
        if ( 0 < j ) { \
          printf(", "); \
        } \
        printf("%s",arr_names[i]); \
        j++; \
      } \
    } \
    if ( 0 < p_cmm ) { \
      printf("},\n"); \
    } \
    else { \
      printf("}\n"); \
    } \
  } \
  else { \
    print; \
  } \
}'

