-module(strangeCommunication).

-export([start/0,foo/0,run/0,bar/0,communicator/1]).

-define(N1,'n1@jezabel').
-define(N2,'n2@jezabel').
-define(N3,'n3@jezabel').


start() ->
    spawn(?N1,?MODULE,run,[]).

run() ->
    erlang:process_flag(trap_exit,true),
    spawn(?N2,erlang,halt,[]),
    timer:sleep(2000),
    Pids = lists:map(fun(N) ->
		      Pid1 = spawn_link(?N2,?MODULE,foo,[]),
		      io:format("Killing and restarting node ~p\n",[?N2]),
		      spawn(?N2,erlang,halt,[]),
		      timer:sleep(2000),
		      Pid1
	      end, lists:seq(1,3)),
    receive ErrMsg1 ->            % receive a 'DOWN' from spawned process
	    io:format("Got: ~w\n", [ErrMsg1])
    end,
    receive ErrMsg2 ->            % receive a 'DOWN' from spawned process
	    io:format("Got: ~w\n", [ErrMsg2])
    end,
    receive ErrMsg3 ->            % receive a 'DOWN' from spawned process
	    io:format("Got: ~w\n", [ErrMsg3])
    end,
    spawn(?N2,?MODULE,bar,[]),
    spawn(?N3,?MODULE,communicator,[Pids]).

foo() ->
    ok.

bar() ->
    receive {From,N} ->
	    From ! {self(),(N+1)}
    end.

communicator(Pids) ->
    lists:foreach(fun(Pid) ->
			  io:format("Trying to communicate with: ~w\n(~w)\n",
				    [Pid,term_to_binary(Pid)]),
			  Pid ! {self(),5},
			  receive {Pid2,N} ->
				  io:format("Recieved ~w from ~w\n(~w)\n",
					    [N,Pid2,term_to_binary(Pid2)])
			  after 2000 ->
				  io:format("No reply!\n")
			  end
		  end, Pids).
