
BEGIN {
  type_name = "";	# GtkEnumType
  type_macro = "";	# GTK_TYPE_ENUM_TYPE
  type_ident = "";	# _gtk_enum_type
  type_flags = 0;
  type_counter = 0;
  delete value_names;	# GTK_ENUM_VALUE
  delete value_nicks;	# enum-value
  VI = 0;
  gen_arrays = 0;
  gen_defs = 0;
  comment_file = "";
  
  for (i = 1; i < ARGC; i++)
    {
      if (ARGV[i] == "arrays")
	gen_arrays = 1;
      else if (ARGV[i] == "defs")
	gen_defs = 1;
      ARGV[i] = "";
    }
  
  if (gen_arrays)
    printf ("/* generated by makeenums.awk */\n\n");
  else if (gen_defs)
    printf (";; generated by makeenums.awk  ; -*- scheme -*-\n\n");
  else
    {
      printf ("hm? what do you want me to do?\n") > "/dev/stderr";
      exit 1;
    }
}

function set_type (set_type_1)
{
  type_name = set_type_1;
  type_macro = "GTK_TYPE";
  type_ident = "";
  for (i = 0; i < length (type_name); i++)
    {
      ch = substr (type_name, i + 1, 1);
      Ch = toupper (ch);
      if (Ch == ch)
	{
	  type_macro = type_macro "_" Ch;
	  type_ident = type_ident "_" tolower (ch);
	}
      else
	{
	  type_macro = type_macro Ch;
	  type_ident = type_ident ch;
	}
    }
}

function set_value (set_value_1, set_value_2)
{
  value_names[VI] = set_value_1;
  value_nicks[VI] = tolower (set_value_2);
  while (match (value_nicks[VI], "_"))
    sub ("_", "-", value_nicks[VI]);
}

function generate_arrays ()
{
  if (gen_arrays)
    {
      printf ("static GtkEnumValue %s_values[] = {\n", type_ident);
      for (i = 0; i < VI; i++)
	{
	  printf ("  { %s, \"%s\", \"%s\" },\n",
		  value_names[i], value_names[i], value_nicks[i]);
	}
      printf ("  { 0, NULL, NULL }\n");
      printf ("};\n");
    }
}

function generate_defs ()
{
  if (gen_defs)
    {
      if (comment_file != "")
	{
	  printf ("\n; enumerations from \"%s\"\n", comment_file);
	  comment_file = "";
	}
      
      printf ("\n(define-%s %s",
	      type_flags ? "flags" : "enum",
	      type_name);
      for (i = 0; i < VI; i++)
	{
	  printf ("\n  (%s %s)",
		  value_nicks[i], value_names[i]);
	}
      printf (")\n");
    }
}

function basename (basename_1)
{
  sub ("\"", "", basename_1);
  while (match (basename_1, "/"))
    sub (".*/", "", basename_1);
  sub ("\"", "", basename_1);
  return basename_1;
}

# parse keywords

/G_ENUM_E/ {
  if ($3 != "+" || $5 != "+")
    printf ("huh? G_ENUM_E keyword without arg?\n") > "/dev/stderr";
  else
    set_type($4);
  type_flags = 0;

  generate_defs();
  generate_arrays();
  VI = 0;
}

/G_ENUM_F/ {
  if ($3 != "+" || $5 != "+")
    printf ("huh? G_ENUM_F keyword without arg?\n") > "/dev/stderr";
  else
    set_type($4);
  type_flags = 1;

  generate_defs();
  generate_arrays();
  VI = 0;
}

/G_ENUM_V/ {
  if ($2 != "+" || $4 != "+" || $6 != "+")
    printf ("huh? G_ENUM_V keyword without arg?\n") > "/dev/stderr";
  else
    set_value($3, $5);
  VI += 1;
}

# feature per file comments
/# / {
  comment_file = basename($3);
}

END {
  printf("\n");
}
