import java.io.*;

public class Person {
	// max # of people in database.
	private final static int maxN = 100;

	// folks[0..n] are people in database.
	private static Person[] folks = new Person[maxN];
	private static int n = 0;

	private String name;	// person's name.
    private boolean male;	// person's sex: true = male, false = female.
	private Person friend1; // person's first friend
	private Person friend2; // person's second friend
	
	// Construct person named s of maleness m.  
	public Person(String s, boolean m) {
		name = s;
		male = m;

		// check if there are too many people in the database
		if ( n >= maxN )
			System.out.println("Person: too many.");
		else {
			folks[n] = this;
			n++;
		}
	}

	// # of people in database.   
	public static int numberOfPeople() {
		return n;
	}
        
	// i-th person in database.
	public static Person intToPerson(int i) {
		if (i < 0 || i >= n)
			return null;
		else return folks[i];
	}
        
	// string representation of a person.
	public String toString() {
		String result;
		result = "name:"+ name + ";";

		if (male)
			result = result + " sex:male;";
		else 
			result = result + " sex:female;";
		if (friend1 == null && friend2 == null)
			result = result + " no friends";
		else if (friend1 != null && friend2 != null)
			result = result + 
				" friends: " + friend1.name + " and " + friend2.name;
		else if (friend1 != null ) 
			result = result + " friend: " + friend1.name;
		else if (friend2 != null ) 
			result = result + " friend: " + friend2.name;
		
		return result; 
	}
  
	// Return error code if argument not valid:
	//	1: Can't be your own friend.
	//	2: p is already this's friend.
	//	3: this already has 2 friends.
	// Otherwise, make p self's friend, and return 0.
	public  int  newFriend(Person p)
	{
		if (name.equals(p.name)) 
			// Can't be your own friend.
			return 1;
		if (friend1 != null && friend1.name.equals(p.name) ||
			friend2 != null && friend2.name.equals(p.name) ) 
			// p1 is already this's friend.
			return 2;
		if (friend1 != null && friend2 != null)
			// this already has 2 friends
			return 3;
			
		if (friend1 == null) friend1 = p;
		else friend2 = p;
			
		return 0;
		}

	// Return false if p is not the Person's friend;
	// otherwise make p no longer the Person's friend,
	// and return true.
	public boolean removeFriend(Person p) { 
		if (friend1 != null) 
		{
			if (friend1.name.equals(p.name))
			{
				friend1 = null;
				return true;
			} 
		}
		
		if (friend2 != null) 
		{
			if (friend2.name.equals(p.name))
			{
				friend2 = null;
				return true;
			}
		}
		
		return false;
	}
        
	// field accessors.
	public String name()  { return name; }
    public boolean male() { return male; }

}
