/* FamGedAwk (for version see "VERS" line below) */

BEGIN {
  print "0 HEAD"
  print "1 SOUR Conveted from Acorn Archimedes !Family format"
  print "2 VERS 1.00";                 /* Converter version number */
  print "2 CORP Denis Howe";           /* Author of source software */
  print "3 ADDR <dbh@doc.ic.ac.uk>"
  print "4 CONT 48 Anson Rd., London NW2 3UU, UK"
  print "4 PHON +44 (81) 450 9448"
  print "2 DATA " file
  print "1 DATE " date " " year
  print "1 SUBM @S1@"
  print "1 GEDC"
  print "2 VERS 5.3"
  print "0 @S1@ SUBM"
                                       /* Insert your details here: */
  print "1 NAME Denis Howe"
  print "1 ADDR <dbh@doc.ic.ac.uk>"
  print "2 CONT 48 Anson Rd., London NW2 3UU, UK"
  print "2 PHON +44 (81) 450 9448"  
}
/^$/ { blank = "2 CONT\n"; next }
/^Name:/ {
  Name[++IndiId] = IndiName = value()
  Id[IndiName] = IndiId
  blank = ""
  next
}
/^Sex:/ {
  Sex[IndiId] = IndiSex = $2
  next
}
/^Born:/ {
  Dates[IndiId] = Dates[IndiId] "1 BIRT\n2 DATE " value() "\n"
  next
}
/^Died:/ {
  Dates[IndiId] = Dates[IndiId] "1 DEAT\n2 DATE " value() "\n"
  next
}
/^Mother:/ {
  Mother[IndiId] = value()
  next
}
/^Father:/ {
  Father[IndiId] = value()
  next
}
/^Spouse:/ {
  s = value()
  if (IndiSex == "M")
    f = findfam(IndiName,s,0)
  else
    f = findfam(s,IndiName,0)
  addfam(IndiName,f)
  next
}
/^Child:/ {
  Kid[IndiId,++NKid[IndiId]] = value()
  next
}
/^Person:/ {
  person = value()
  next
}
{
  tag = Notes[IndiId] > "" ? blank "2 CONT" : "1 NOTE"
  blank = ""
  Notes[IndiId] = Notes[IndiId] tag " " $0 "\n"
}
END {
  for (i = 1; i <= IndiId; i++)
    findfam(Father[i],Mother[i],1)
  for (i = 1; i <= IndiId; i++)
  {
    name = Name[i]
    print "0 @I" i "@ INDI"
    print "1 NAME " name
    if (Sex[i] > "") print "1 SEX " Sex[i]
    printf Dates[i]
    for (f = 1; f <= NFams[name]; f++)
      print "1 FAMS @F" Fams[name,f] "@"
    f = findfam(Father[i],Mother[i],0)
    if (f) print "1 FAMC @F" f "@"
    printf Notes[i]
  }
  for (f = 1; f <= NFamily; f++)
  {
    print "0 @F" f "@ FAM"
    if (Husb[f] > "")
    {
      parent = Id[Husb[f]]
      print "1 HUSB @I" parent "@"
    }
    if (Wife[f] > "")
    {
      parent = Id[Wife[f]]
      print "1 WIFE @I" parent "@"
    }
    for (k = 1; k <= NKid[parent]; k++)
    {
      child = Id[Kid[parent,k]]
      if (Mother[child] == Wife[f] && Father[child] == Husb[f])
        print "1 CHIL @I" child "@"
    }
  }
  if (person > "") print "0 @N1@ NOTE Person " person
  print "0 TRLR"
}

function value()
{
  $1 = ""
  return substr($0,2)
}

function findfam(dad,mum,add,  f)
{
  if (dad == "" && mum == "")
    return 0
  for (f = 1; f <= NFamily; f++)
    if (Husb[f] == dad && Wife[f] == mum)
      return f
  f = ++NFamily;
  Husb[f] = dad; Wife[f] = mum
  if (add) { addfam(dad,f) ; addfam(mum,f) }
  return f
}

function addfam(name,fam)
{
  Fams[name,++NFams[name]] = fam
}
