import java.io.*;
import java.util.*;
public class TotalChat  {
    public static void main(String[] args) throws Exception {
        int myId = Integer.parseInt(args[1]);
        int numProc = Integer.parseInt(args[2]);
        Linker comm = new Linker(args[0], myId, numProc);
        Chat chat = new Chat(comm);
        TotalOrder t = new TotalOrder(comm, chat);
        for (int i = 0; i < numProc; i++)
            if (i != myId)
                (new ListenerThread(i, t)).start();
        BufferedReader din = new BufferedReader(new InputStreamReader(System.in));
        while (true) {
            String chatMsg = chat.getUserInput(din);
            if (chatMsg.equals("quit")) break;
            IntLinkedList destIds =  chat.getDest(din);
            t.multicast(destIds, "chat", chatMsg);
        }
    }
}