#!/usr/bin/awk -f

#
# (c) K. Anton Feenstra 2001
#
# subindex v. 0.1 - 12 feb 2001
#
# reads tex index entries as generated by makeindex and 
# combines identical words into sub-entries
#

BEGIN {
  n=0;
}

/[{ ]Symbols[ }]/ {
  if ( substr(1,1,$0)!="%" )
    $0 = "% " $0;
}

/^[ \t]*\\see/ {
  sub("^[ \t]*","");
  pp = pp $0;
  next;
}

{
  sub(", \\\\see.*","",pp);
}

function dump() {
  printf("%% %d %d %d %d |", mc, nc, mp, np);
  for(i=1;i<=nc;i++) printf(" %s",c[i]);
  printf(" |");
  for(i=1;i<=np;i++) printf(" %s",p[i]);
  printf(" |\n");
}


{
  mc=0;
  if ($1=="\\item") {
    for(i=1; $(i)!="\\hfill" && i<=NF; i++) {
      c[i]=$(i+1);
      sub(",$","",c[i]);
      if (i<=np && c[i]==p[i]) mc=i;
    }
    nc=i-2;
  } else {
    nc=0;
    mc=0;
  }
#  if (mc) dump();
  if (mc && mc<=nc) {
    if (mc) {
      key=c[1];
      for(i=2; i<=mc; i++)
	key=key" "c[i];
    } else 
      key="";
    if (key != pkey && mc<np)
      printf("  \\item %s \\hfill \\nopagebreak\n", key);
    pkey=key;
  }
  if (mp) m=mp; else m=mc;
  skey=p[m+1];
  for(i=m+2; i<=np; i++)
    skey=skey" "p[i];
  if (mc<np)
    for(i=1; i<=mp || i<=mc; i++) {
      sub("item "key" ", "subitem ", pp);
      sub("item "key", "skey, "subitem "skey" $\\sim$", pp);
      pp="  "pp;
    }
  
  np=nc;
  mp=mc;
  for(i=1;i<=np;i++)
    p[i]=c[i];
}

{
  if (NR>1) print pp;
  pp=$0;
}

END {
  print pp;
}

#last line
