/* familycheck:  Consistency checks between indi records and family records
	(making sure links between kids and spouses go both ways.)
	make sure each family that a person says he is a spouse of
	has him as a spouse, and, vice-versa,
	 make sure each person that a family says is a spouse thinks he
	 is a spouse of that family
	It also checks when a person says he is a child in a family that
	the family has that person as a child. 
	And vice-versa, that every child in a family thinks he
	is a child of that family.

	Written by Dennis Nicklaus nicklaus@facstaff.wisc.edu, 1997.
*/
proc main ()
{
	print("processing each person and family in the database\n")
    forindi(person, number) {
    	
        families(person, fam, spouse, nfam) {
		set(okboss,0)
		if (husband(fam)){
			if (eq(husband(fam),person)){
			set(okboss, 1)}
		}
		if (wife(fam)){
			if (eq(wife(fam),person)){
			set(okboss,1)}
		}
		if (eq(0,okboss)){
		   print("\nbad family for ")print(key(person)) 
		   "bad family for " key(person) nl()
		}
	
	}
	/* now check that this person is a child in the family
	   he thinks he is */
	if (parents(person)){
		set(okboss,0)
		children(parents(person),child,num){
			if (eq(person,child)) {set(okboss,1)}
		}
		if (eq(0,okboss)){
		   print("\nbad parents for ")print(key(person)) 
		   "bad parents for " key(person) nl()
		}
	}

    }

  /* now check families so that for every spouse the family says is in the 
     family, that spouse also thinks he/she is in the family. */
  /* the family keys aren't terribly useful in LL (or out since LL
     will change the key numbers on import), so print out the key
     of the indi involved, also */

    forfam(fam, number) {
	set(okboss,0)
	set(okwife,0)
	if (husband(fam)){
           families(husband(fam), fam2, spouse, nfam) {
		if (eq(fam,fam2)){  set(okboss,1)}
	   }
	}
	else{  set(okboss,1)}
	if (wife(fam)){
           families(wife(fam), fam2, spouse, nfam) {
		if (eq(fam,fam2)){  set(okwife,1)}
	   }
	}
	else{  set(okwife,1)}
	if (and(not(husband(fam)),not(wife(fam)))){
	   print("\nno parents in family") print(key(fam)) 
	}
	if (or(eq(0,okboss),eq(0,okwife))){
	   print("\nbad spouse for ")print(key(fam)) 
	   if (husband(fam)){print(key(husband(fam)))}
	   if (wife(fam)){print(key(wife(fam)))}
	   "bad spouse for " key(fam) nl()
	}
	children(fam,child,num){
		if (ne(parents(child),fam)){
		   print("\nbad child in family,") print(key(child)) print(key(fam))
		   "bad child in family," key(child) key(fam) nl()
		}
	}

    }
}
