Erlang Token Ring Simulator, updated

ErlangThere’s a directory on my machine called ~/Archives. It’s not exactly… organised. 🙂 It contains bits and pieces from the last 20 or more years – and along with the usual documents, notes and datasheets on the 74 series TTL chipset (computer engineer and computer scientist had rather different flavours in TCD back then), there’s a fair amount of code. Some of that code I can remember, other bits I look at now and think “I wrote that? Eeek…” — but there’s a small amount of code that I look at and think “Hey, I wasn’t all bad back then”. Over the new year’s holiday, I was digging around in there and came across some bits and pieces from the latter category that I thought I’d put up here for kicks, seeing as how I’d put up stuff from the PhD work and other bits and bobs already. I’ll start with this one, it’s a token ring network simulator written in Erlang somewhere in the first half of my final year in college (so late 1996 to early 1997). Erlang back then was fairly new, it was the first functional language I ever worked in (but not the first I’d heard about, I mean, it’s an older concept than I am and Haskell was going strong even back then). I’d actually heard about Erlang two summers earlier while interning at Ericsson from some of the guys working on the MXE training courses (though they weren’t using it, just wishing they were, IIRC – that was 20 years ago and my memory’s only human).

It’s actually not horrible for a piece of final year labwork, but since my notes for that course are long since gone, I don’t have any of the original design notes to hand.

tr.original.erl

[cc lang="erlang" lines="50"]
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% 4D1 Project 1
%% Token Ring simulator
%%
%% Mark Dennehy
%% S.S. C.Eng. 93369425
%% mdennehy@tcd.ie
%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Known Bugs :
%%	Creating a network with too many nodes can cause timeout-related
%%		problems that prevent the network from ever starting up.
%%	Crashing the monitor node can lead to anomolous behaviour
%%		under apparently random sets of circumstances.
%%	Malicous attempts to crash the network will usually succeed. 
%%

-module(tr).
-export([start/1,ring/0,ring/1,stop/0,trnode/2,nodesearch/1,send/3,crash/1,add/1,del/1,recover/0]).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Starts up a simulated network with 3 nodes
%%	ring(N)
%%		N : Number of nodes, default = 3

ring() ->
	start(3).

ring(N) ->
	start(N).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Main startup function
%%	start(N)
%%		N = Number of nodes, must be positive integer

start(N) when integer(N),N>0 ->
	S = gs:start(),
	register(main,self()),
	register(firstnode,init(1,N,S)),
	io:format("Awaiting ready signals ~n",[]),
	readywait(N),
	recover(),
	firstnode!{"Token",self()},
	receive
		{"TokenReceived",RxPID} ->
			io:format("First Node acknowleging token receipt~n",[])
	end.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Spawns off the node processes

init(N,Total,S) when N
	spawn(tr,trnode,[N,S]),
	init(N+1,Total,S);

init(N,Total,S) when N==Total ->
	spawn(tr,trnode,[N,S]).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Delay function that does not return until all the nodes have 
%% completed initialisation and reported ready

readywait(N) when N>0 ->
	receive
		{"Ready",PID,N} ->
			io:format("Process ~w [Node ~w] reports ready~n",[PID,N]),
			readywait(N-1)
	end;

readywait(N) when N=
	true.
	
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Safely stops the network
%%	stop()

stop()->
    firstnode!{"Data",-1,1,"Stopping...",false,0},
    firstnode!{"Bye"},
		timer:sleep(3500),
    gs:stop(),
    exit(normal).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Find an arbitary node (requires firstnode to be defined)
%%	nodesearch(N)
%%		N = Node number (must be positive integer)

nodesearch(N) when N==1 ->
	io:format("nodesearch(~w)~n",[N]),
	firstnode;

nodesearch(N) when integer(N),N>1 ->
	io:format("nodesearch(~w)~n",[N]),
	nf(N,firstnode).

%% internal process called by nodesearch()
nf(N,PID) when integer(N),N>1 ->
	io:format("nf(~w,~w)~n",[N,PID]),
	PID!{"GetDnStream",self()},
	receive
		{"DownStreamNode",P,RetPID} ->
			io:format("nf-Rx(~w,~w)~n",[P,RetPID]),
			Tmp=0
	end,
	nf(N-1,RetPID);

nf(N,PID) when N==1 ->
	io:format("nf(~w,~w)~n",[N,PID]),
	PID.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Wrapper function to get an arbitarty node to send a message to an 
%% arbitary node
%%	send(Nto,Nfrom,Data)
%%		Nto = Node to send message to  (must be integer greater than -1)
%%		Nfrom = Node to send message from (must be positive integer)
%%		Data = Data to send in message

send(Nto,Nfrom,Data) when integer(Nto),integer(Nfrom),Nto>-1,Nfrom>0 ->
	nodesearch(Nfrom)!{"Message",Nto,Data}.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Function to cause an arbitary node to fail, simulating a transciever 
%% failure
crash(N) ->
	nodesearch(N)!{"Die"}.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Function to recover a network which has lost cohesion.
%%	recover()

recover() ->
	io:format("Checking for nodes ... ~n~w~n",[processes()]),
	KeyList = find_nodes(processes(),[]),
	case lists:member(firstnode, registered()) of
		true ->
			unregister(firstnode),
			register(firstnode,element(2,get(hd(KeyList))));
		false ->
			register(firstnode,element(2,get(hd(KeyList))))
	end,
	rebuild_ends(KeyList),
	rebuild_middle(KeyList),
	firstnode!{"ElectMonitor"}.

%% internal process called by recover
rebuild_ends(KeyList) when length(KeyList) >1 ->
	A = hd(KeyList),
	B = lists:last(KeyList),
	Anode = element(2,get(A)),
	Bnode = element(2,get(B)),
	Anode!{"SetUpStream",Bnode},
	Bnode!{"SetDownStream",Anode};

%% internal process called by recover
rebuild_ends(KeyList) when length(KeyList)==1 ->
	A = get(element(1,list_to_tuple(KeyList))),
	element(2,A)!{"SetUpStream",element(2,A)},
	element(2,A)!{"SetDownStream",element(2,A)}.

%% internal process called by recover
rebuild_middle(KeyList) when length(KeyList) >1 ->
	A = hd(KeyList),
	NewKeyList = tl(KeyList),
	B = hd(NewKeyList),
	link(A,B),
	rebuild_middle(NewKeyList);

%% internal process called by recover
rebuild_middle(KeyList) when length(KeyList)==1 ->
	true.

%% internal process called by recover
link(A,B) ->
	Anode = element(2,get(A)),
	Bnode = element(2,get(B)),
	Anode!{"SetDownStream",Bnode},
	Bnode!{"SetUpStream",Anode}.

%% internal process called by recover
find_nodes([],KeyList) ->
	lists:sort(KeyList);

%% internal process called by recover
find_nodes(ProcList,KeyList) ->
	Test = hd(ProcList),
	Test!{"StatusReport",self()},
	receive
		{"NodeStatusReport",ThisPID,N,UpPID,DownPID}->
			put(N,{UpPID,ThisPID,DownPID}),
			NewKeyList = lists:append(KeyList,[N]),
			io:format("Process ~w : Node ~w : UpPID = ~w : DownPID = ~w~n",[ThisPID,N,UpPID,DownPID]),
			find_nodes(tl(ProcList),NewKeyList)

		%% The longest response time should be a little over 200 msec %%%%%%
		%% (the longest delay call in trnodeloop(...)%%%%%%%%%%%%%%%%%%%%%%%
		after 250 -> 
			io:format("~nProcess ~w : No node info response received~n",[Test]),
			find_nodes(tl(ProcList),KeyList)
	end.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Adds a new node after node N
%%	add(N)
%%		N = Node to insert new node after (must be positive integer)

add(N) when integer(N),N>0->
	UpPID = nodesearch(N),
	UpPID!{"GetDnStream",self()},
	receive
		{"DownStreamNode",P,DnPID} ->
			Tmp=0
	end,
	NewNode=spawn(tr,trnode,[N+1,gs:start()]),
    NewNode!{"SetUpStream",UpPID},
    NewNode!{"SetDownStream",DnPID},
	UpPID!{"SetDownStream",NewNode},
	DnPID!{"SetUpStream",NewNode},
	DnPID!{"IncrementN"}.
	
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Removes node N from the network
%%	del(N)
%%		N = Node to remove from network (must be positive integer)

del(N) when integer(N),N>0 ->
	ExPID = nodesearch(N),
	ExPID!{"GetDnStream",self()},
	receive
		{"DownStreamNode",P,DnPID} ->
			Tmp=0
	end,
	ExPID!{"GetUpStream",self()},
	receive
		{"UpStreamNode",Q,UpPID} ->
			Tmp2=0
	end,
	UpPID!{"SetDownStream",DnPID},
	DnPID!{"SetUpStream",UpPID},
	DnPID!{"DecrementN"},
	ExPID!{"Die"}.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Node initialisation function
%% called internally - Do Not Touch !
%%	trnode(N,S)
%%		N = Number to assign to new node
%%		S = return from gs:start()

trnode(N,S) ->
	io:format("Token Ring Node ~w Started : PID ~w ~n",[N,self()]),
	Info = io_lib:format("Process ~w~nNode ~w~n------------~n~n",[self(),N]),
	Title = io_lib:format("Token Ring Simulator : Process ~w [Node ~w]",[self(),N]),

	%% Create GUI components	
	W = gs:create(window,S,[{width,400},{height,200},{bg,black},{title,Title},{map,false}]),
	C = gs:create(canvas,W,[{width,400},{height,200},{bg,{70,70,85}}]),
	T = gs:create(oval,C,[{coords,[{350,20},{390,50}]},{bw,5},{fg,{128,128,128}},{fill,{0,0,0}}]),
	Text = gs:create(editor,W,[{vscroll,left},{bg,black},{fg,green},{insertpos,'end'},{wrap,word},{x,0},{y,0},{width,340},{height,200},{insert,{{0,0},Info}}]),
	Bclear = gs:create(button,W,[{click,true},{label,{text,"Cls"}},{height,25},{width,40},{x,350},{y,110}]),
	Bdie = gs:create(button,W,[{click,true},{label,{text,"Die"}},{height,25},{width,40},{x,350},{y,170}]),
	Bfail = gs:create(button,W,[{click,true},{label,{text,"Fail"}},{height,25},{width,40},{x,350},{y,140}]),

  %% Draw node's window and start message loop	
	gs:config(W,{map,true}),
	main!{"Ready",self(),N},
	trnodeloop(N,self(),self(),W,C,T,Bdie,Bfail,Bclear,Text,0,false,"Message",0,false,0,timer:send_after(30000,{"MonitorWatchdog"}),false,0,0,0,false,false,false).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Main node loop
%% called internally - Do Not Touch !
%%	trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,
%%							Bfail,Bclear,Text,MsgCount,MsgFlag,Msg,
%%							MsgTo,TokenFlag,TimeoutCounter,WatchdogRef,
%%							MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,
%%							MFdata,MFnet)
%%		N = Node number
%%		UpStreamPID = PID of process representing the node upstream of 
%%							this node in the network
%%		DownStreamPID = PID of process representing the node downstream of 
%%							this node in the network
%%		W = Window reference
%%		C = Canvas reference
%%		T = Token Indicator reference
%%		Bdie = 'Die' button reference
%%		Bfail = 'Fail' button reference
%%		Bclear = 'Clear' button reference
%%		Text = editor window reference
%%		MsgCount = internal node count of the number of messages received
%%		MsgFlag = boolean flag indicating the node has data to transmit
%%		Msg = data the node has ready to transmit
%%		MsgTo = the address the node wishes to send it's data to
%%		TokenFlag = boolead flag indicating possession of the token
%%		TimeoutCounter = counter indicating the number of timeouts since 
%%							the last message was recieved by the node
%%		WatchdogRef = the reference of the watchdog timer that a normal node
%%							uses to check for a monitor failure
%%		MonitorFlag = boolean flag indicating status of node as monitor
%%		RBtoken = 'Show Token' radiobutton reference
%%		RBdata = 'Show Data' radiobutton reference
%%		RBnetcheck = 'Show network messages' radiobutton reference
%%		MFtoken = MonitorFlag (boolean flag used only by monitor) to 
%%							show/hide token data
%%		MFdata = MonitorFlag (boolean flag used only by monitor) to 
%%							show/hide data packets
%%		MFnet = MonitorFlag (boolean flag used only by monitor) to 
%%							show/hide network messages

trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount,MsgFlag,Msg,MsgTo,TokenFlag,TimeoutCounter,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet) ->
	case TokenFlag of
		%% Have Token, Have Message to transmit%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
		true when MsgFlag==true ->
			tokenicon(W,C,T,"data"),
			DownStreamPID!{"Data",MsgTo,N,Msg,false,0},
			trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount,false,Msg,MsgTo,false,0,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);
			
		%% Have token, don't have Message to transmit%%%%%%%%%%%%%%%%%%%%%%%
		true when MsgFlag==false ->
			DownStreamPID!{"Token",self()},
			trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount,MsgFlag,Msg,MsgTo,false,0,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

		%% Don't have Token%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
		false ->
			receive
				%% Token processing
				{"Token",PID} ->
					case MFnet of
						true ->
							print(Text,io_lib:format("[~w] {Token,~w}",[MsgCount,PID]));
						false ->
							Tmp=0
					end,
					case MFtoken of
						true ->
							print(Text,"Token passing Monitor Node");
						false ->
							Tmp1 = 0
					end,
					tokenicon(W,C,T,"token"),
					if
						PID==UpStreamPID ->
							trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,true,0,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);
						PID/=UpStreamPID ->
							PID!{"TokenReceived",self()},
							print(Text,io_lib:format("Node ~w receiving token from process ~w",[N,PID])),
							trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,true,0,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet)
					end;
	
				%% Request to send message to arbitary node%%%%%%%%%%%%%%%%%%%%%
				{"Message",Nto,Data} ->
					case MFnet of
						true ->
							print(Text,io_lib:format("[~w] {Message,~w,~s}",[MsgCount,Nto,Data]));
						false ->
							Tmp = 0
					end,
					trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,true,Data,Nto,false,0,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

				%% Data Packet processing%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
				{"Data",Nto,Nfrom,Data,ReadFlag,MonCount} when Nfrom==N ->
					case MFnet of
						true ->
							print(Text,io_lib:format("[~w] {Data,~w,~w,~s,~w,~w}",[MsgCount,Nto,Nfrom,Data,ReadFlag,MonCount]));
						false ->
							Tmp2=0
					end,
					case MFdata of
						true ->
							print(Text,io_lib:format("~nNode ~w : Receipt of self-originated Message : Nto = ~w : ~s",[N,Nto,Data]));
						false ->
							Tmp3 = 0
					end,
					tokenicon(W,C,T,"data"),
					case ReadFlag of	
						true when Nto==-1 ->
							print(Text,io_lib:format("> ~s",[Data])),
							io:format("Node ~w : Eating Data, passing token~n",[N]),
							DownStreamPID!{"Token",self()},
							trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,0,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);
							
						true when Nto>0 ->
							io:format("Node ~w : Eating Data, passing token~n",[N]),
							DownStreamPID!{"Token",self()},
							trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,0,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

						false ->
							case MonitorFlag of
								true when MonCount
									NewMonCount=MonCount+1,
									DownStreamPID!{"Data",Nto,Nfrom,Data,ReadFlag,NewMonCount};
								true when MonCount>=5 ->
									print(Text,io_lib:format("Data Packet {Data,~w,~w,~s,~w,~w} ~nhas circulated 5 times, removing from Network",[Nto,Nfrom,Data,ReadFlag,MonCount])),
									self()!{"Token",self()};
								false ->	
									DownStreamPID!{"Data",Nto,Nfrom,Data,ReadFlag,MonCount}
							end,
							trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,0,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet)
					end;

				{"Data",Nto,Nfrom,Data,ReadFlag,MonCount} when Nto==-1 ->
					case MFnet of
						true ->
							print(Text,io_lib:format("[~w] {Data,~w,~w,~s,~w,~w}",[MsgCount,Nto,Nfrom,Data,ReadFlag,MonCount]));
						false ->
							Tmp4=0
					end,
					case MFdata of
						true ->
							print(Text, io_lib:format("~nNode ~w : Receipt of Message : Nto = ~w : ~s~n",[N,Nto,Data]));
						false ->
							Tmp5 = 0
					end,
					tokenicon(W,C,T,"data"),
					print(Text,io_lib:format("> ~s",[Data])),
					case MonitorFlag of
						true when MonCount
							NewMonCount=MonCount+1,
							DownStreamPID!{"Data",Nto,Nfrom,Data,true,NewMonCount};
						true when MonCount>=5 ->
							print(Text,io_lib:format("Data Packet {Data,~w,~w,~s,~w,~w} ~nhas circulated 5 times, removing from Network",[Nto,Nfrom,Data,ReadFlag,MonCount])),
							self()!{"Token",self()};
						false ->	
							DownStreamPID!{"Data",Nto,Nfrom,Data,true,MonCount}
					end,
					trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,0,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

				{"Data",Nto,Nfrom,Data,ReadFlag,MonCount} when Nto==N ->
					case MFnet of
						true ->
							print(Text,io_lib:format("[~w] {Data,~w,~w,~s,~w,~w}",[MsgCount,Nto,Nfrom,Data,ReadFlag,MonCount]));
						false ->
							Tmp=0
					end,
					case MFdata of
						true ->
							print(Text, io_lib:format("~nNode ~w : Receipt of Message : Nto = ~w : ~s",[N,Nto,Data]));
						false ->
							Tmp1 = 0
					end,
					tokenicon(W,C,T,"data"),
					print(Text,io_lib:format("> ~s",[Data])),
					case MonitorFlag of
						true when MonCount
							NewMonCount=MonCount+1,
							DownStreamPID!{"Data",Nto,Nfrom,Data,true,NewMonCount};
						true when MonCount>=5 ->
							print(Text,io_lib:format("Data Packet {Data,~w,~w,~s,~w,~w} ~nhas circulated 5 times, removing from Network",[Nto,Nfrom,Data,ReadFlag,MonCount])),
							self()!{"Token",self()};
						false ->	
							DownStreamPID!{"Data",Nto,Nfrom,Data,true,MonCount}
					end,
					trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,0,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

				{"Data",Nto,Nfrom,Data,ReadFlag,MonCount}  ->
					case MFnet of
						true ->
							print(Text,io_lib:format("[~w] {Data,~w,~w,~s,~w,~w}",[MsgCount,Nto,Nfrom,Data,ReadFlag,MonCount]));
						false ->
							Tmp=0
					end,
					case MFdata of
						true ->
							print(Text, io_lib:format("~nNode ~w : Receipt of Message : Nto = ~w : ~s",[N,Nto,Data]));
						false ->
							Tmp1 = 0
					end,
					tokenicon(W,C,T,"data"),
					case MonitorFlag of
						true when MonCount
							NewMonCount=MonCount+1,
							DownStreamPID!{"Data",Nto,Nfrom,Data,ReadFlag,NewMonCount};
						true when MonCount>=5 ->
							print(Text,io_lib:format("Data Packet {Data,~w,~w,~s,~w,~w} ~nhas circulated 5 times, removing from Network",[Nto,Nfrom,Data,ReadFlag,MonCount])),
							self()!{"Token",self()};
						false ->	
							DownStreamPID!{"Data",Nto,Nfrom,Data,ReadFlag,MonCount}
					end,
					trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,0,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

				%% To safely shut down a ring %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
				{"Bye"} ->
					case MFnet of
						true ->
							print(Text,io_lib:format("[~w] {Bye}",[MsgCount]));
						false ->
							Tmp=0
					end,
					DownStreamPID!{"Bye"},
					print(Text,"Received Termination Instruction, Quitting ..."),
					timer:sleep(2000),
					true;

				%% Up- and Down- stream node value functions%%%%%%%%%%%%%%%%%%%%
				{"SetUpStream",UpPID} ->
					case MFnet of
						true ->
							print(Text,io_lib:format("[~w] {SetUpStream,~w}",[MsgCount,UpPID]));
						false ->
							Tmp=0
					end,
					io:format("TRNode ~w : Setting Upstream node : ~w ~n",[N,UpPID]),
					print(Text,io_lib:format("Setting Upstream Node : ~w",[UpPID])),
					trnodeloop(N,UpPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,TimeoutCounter,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

				{"SetDownStream",DnPID} ->
					case MFnet of
						true ->
							print(Text,io_lib:format("[~w] {SetDownStream,~w}",[MsgCount,DnPID]));
						false ->
							Tmp=0
					end,
					io:format("TRNode ~w : Setting Downstream node : ~w ~n",[N,DnPID]),
					print(Text,io_lib:format("Setting Downstream Node : ~w",[DnPID])),
					trnodeloop(N,UpStreamPID,DnPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,TimeoutCounter,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

				{"GetUpStream",RetPID} ->
					case MFnet of
						true ->
							print(Text,io_lib:format("[~w] {GetUpStream,~w}",[MsgCount,RetPID]));
						false ->
							Tmp=0
					end,
					RetPID!{"UpStreamNode",N,UpStreamPID},
					trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,TimeoutCounter,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);
					
				{"GetDnStream",RetPID} ->
					case MFnet of
						true ->
							print(Text,io_lib:format("[~w] {GetDnStream,~w}",[MsgCount,RetPID]));
						false ->
							Tmp=0
					end,
					RetPID!{"DownStreamNode",N,DownStreamPID},
					trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,TimeoutCounter,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

				%% To crash a node from the GUI %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
				{gs,Bdie,click,_,_} ->
					print(Text,"Dying!"),
					tokenicon(W,C,T,"failure"),
					true;

				%% To crash a node from the shell %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
				{"Die"} ->
					print(Text,"Dying!"),
					tokenicon(W,C,T,"failure"),
					true;

				%% To fail a node from the GUI %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
				{gs,Bfail,click,_,_} ->
					print(Text,"Node Failure!"),
					tokenicon(W,C,T,"failure"),
					failednodeloop(DownStreamPID,Bdie);

				%% To fail a node from the shell %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
				{"Fail"} ->
					print(Text,"Node Failure!"),
					tokenicon(W,C,T,"failure"),
					failednodeloop(DownStreamPID,Bdie);

				%% For finding lost nodes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
				{"StatusReport",RepPID} ->
					case MFnet of
						true ->
							print(Text,io_lib:format("[~w] {StatusReport,~w}",[MsgCount,RepPID]));
						false ->
							Tmp=0
					end,
					RepPID!{"NodeStatusReport",self(),N,UpStreamPID,DownStreamPID},
					trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,TimeoutCounter,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

				%% For Re-Numbering the nodes after network re-configuration %%%
				{"DecrementN"} when N==1 ->
					case MFnet of
						true ->
							print(Text,io_lib:format("[~w] {DecrementN}",[MsgCount]));
						false ->
							Tmp=0
					end,
					trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,TimeoutCounter,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

				{"DecrementN"} ->
					case MFnet of
						true ->
							print(Text,io_lib:format("[~w] {DecrementN}",[MsgCount]));
						false ->
							Tmp=0
					end,
					DownStreamPID!{"DecrementN"},
					Info = io_lib:format("Process ~w~nNode ~w~n------------~n~n",[self(),N-1]),
					Title = io_lib:format("Token Ring Simulator : Process ~w [Node ~w]",[self(),N-1]),
					gs:config(Text,[clear]),
					print(Text,Info),
					gs:config(W,{title,Title}),
					trnodeloop(N-1,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,TimeoutCounter,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

				{"IncrementN"} when MonitorFlag==true ->
					case MFnet of
						true ->
							print(Text,io_lib:format("[~w] {IncrementN}",[MsgCount]));
						false ->
							Tmp=0
					end,
					trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,TimeoutCounter,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

				{"IncrementN"} ->
					case MFnet of
						true ->
							print(Text,io_lib:format("[~w] {IncrementN}",[MsgCount]));
						false ->
							Tmp=0
					end,
					DownStreamPID!{"IncrementN"},
					Info = io_lib:format("Process ~w~nNode ~w~n------------~n~n",[self(),N+1]),
					Title = io_lib:format("Token Ring Simulator : Process ~w [Node ~w]",[self(),N+1]),
					gs:config(Text,[clear]),
					print(Text,Info),
					gs:config(W,{title,Title}),
					trnodeloop(N+1,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,TimeoutCounter,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

				%% Monitor Election Functions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
				{"BecomeMonitor"} ->
					case MFnet of
						true ->
							print(Text,io_lib:format("[~w] {BecomeMonitor}",[MsgCount]));
						false ->
							Tmp=0
					end,
					case MonitorFlag of
						true ->
							trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,0,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);
						false ->
							print(Text,"Becoming Monitor ..."),
							DownStreamPID!{"NewMonitor",N},
							tr2mon(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,0,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet)
					end;

				{"NewMonitor",Nrx} ->
					case MFnet of
						true ->
							print(Text,io_lib:format("[~w] {NewMonitor,~w}",[MsgCount,N]));
						false -> 
							Tmp=0
					end,
					case MonitorFlag of 
						true when Nrx > N ->
							DownStreamPID!{"NewMonitor",N};
						true when Nrx 
							self()!{"ResignMonitor"};
						true when Nrx==N ->
							Tmp1=0;
						false ->
							DownStreamPID!{"NewMonitor",Nrx}
					end,
					trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,0,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

				{"ResignMonitor"} when MonitorFlag==true ->
					print(Text,"Resigning from monitorhood"),
					mon2tr(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,TimeoutCounter,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

				{"ElectMonitor"} ->
					case MFnet of
						true ->
							print(Text,io_lib:format("[~w] {ElectMonitor}",[MsgCount]));
						false ->
							Tmp=0
					end,
					DownStreamPID!{"MonitorClaim",N},
					trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,0,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

				{"MonitorClaim",Nrx} when MonitorFlag==true ->
					case MFnet of
						true ->
							print(Text,io_lib:format("[~w] {MonitorClaim,~w}",[MsgCount,Nrx]));
						false ->
							Tmp=0
					end,
					trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,0,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);
					
				{"MonitorClaim",Nrx} when Nrx == N ->
					case MFnet of
						true ->
							print(Text,io_lib:format("[~w] {MonitorClaim,~w}",[MsgCount,Nrx]));
						false ->
							Tmp=0
					end,
					self()!{"BecomeMonitor"},
					trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,0,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

				{"MonitorClaim",Nrx} when Nrx > N ->
					case MFnet of
						true ->
							print(Text,io_lib:format("[~w] {MonitorClaim,~w}",[MsgCount,Nrx]));
						false ->
							Tmp=0
					end,
					DownStreamPID!{"MonitorClaim",N},
					trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,0,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);
					
				{"MonitorClaim",Nrx} when Nrx 
					case MFnet of
						true ->
							print(Text,io_lib:format("[~w] {MonitorClaim,~w}",[MsgCount,Nrx]));
						false ->
							Tmp=0
					end,
					DownStreamPID!{"MonitorClaim",Nrx},
					trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,0,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

				%% Monitor Failure Detection %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
				{"MonitorWatchdog"} when MonitorFlag==false ->
					spawn(tr,recover,[]),
					trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount,MsgFlag,Msg,MsgTo,false,TimeoutCounter,timer:send_after(14500,{"MonitorWatchdog"}),MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

				{"MonitorPet"} when MonitorFlag==true ->
					case MFnet of
						true ->
							print(Text,io_lib:format("[~w] {MonitorPet}",[MsgCount]));
						false ->
							Tmp=0
					end,
					trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount,MsgFlag,Msg,MsgTo,false,TimeoutCounter,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

				{"MonitorPet"} when MonitorFlag==false ->
					timer:cancel(element(2,WatchdogRef)),
					DownStreamPID!{"MonitorPet"},
					trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,TimeoutCounter,timer:send_after(30000,{"MonitorWatchdog"}),MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

				{"WatchdogPet"} when MonitorFlag==true ->
					case MFnet of
						true ->
							print(Text,io_lib:format("[~w] {WatchdogPet}",[MsgCount]));
						false ->
							Tmp=0
					end,
					timer:send_after(10000,{"WatchdogPet"}),
					DownStreamPID!{"MonitorPet"},
					trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount,MsgFlag,Msg,MsgTo,false,TimeoutCounter,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);
					
				%% Clear Screen %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
				{gs,Bclear,click,_,_} ->
					case MonitorFlag of
						true ->
							Info = io_lib:format("Process ~w~nMonitor Node ~w~n------------~n~n",[self(),N]);
						false ->
							Info = io_lib:format("Process ~w~nNode ~w~n------------~n~n",[self(),N])
					end,
					gs:config(Text,[clear]),
					print(Text,Info),
					trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,TimeoutCounter,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);
				
				%% Toggle token monitoring %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
				{gs,RBtoken,click,_,_} ->
					case MFtoken of
						true ->
							trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,TimeoutCounter,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,false,MFdata,MFnet);
						false ->
							trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,TimeoutCounter,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,true,MFdata,MFnet)
					end;
					
				%% Toggle data packet monitoring %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
				{gs,RBdata,click,_,_} ->
					case MFdata of
						true ->
							trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,TimeoutCounter,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,false,MFnet);
						false ->
							trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,TimeoutCounter,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,true,MFnet)
					end;

				%% Toggle network message monitoring %%%%%%%%%%%%%%%%%%%%%%%%%%%
				{gs,RBnetcheck,click,_,_} ->
					case MFnet of
						true ->
							trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,TimeoutCounter,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,false);
						false ->
							trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount+1,MsgFlag,Msg,MsgTo,false,TimeoutCounter,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,true)
					end

				%% Non-receipt Timeout %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
				after 5000 ->
					case MonitorFlag of 
						%% First Timeout on Monitor %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
						true when TimeoutCounter==0 ->
							gs:config(Text,[{insert,{{5,0},io_lib:format("~nTimeout",[])}}]),
							trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount,MsgFlag,Msg,MsgTo,false,1,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

						%% First 4 Monitor Timeouts %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
						true when TimeoutCounter 
							gs:config(Text,[{insert,{insert,"."}}]),
							trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount,MsgFlag,Msg,MsgTo,false,TimeoutCounter+1,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

						%% Re-inject token to counter Lost Token Problem %%%%%%%%%%%
						true when TimeoutCounter == 4 ->
							gs:config(Text,[{insert,{insert,"Injecting Token"}}]),
							DownStreamPID!{"Token",self()},
							trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount,MsgFlag,Msg,MsgTo,false,TimeoutCounter+1,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

						%% Token hasn't re-appeared, attempt to recover network %%%%
						true when TimeoutCounter == 5 ->
							gs:config(Text,[{insert,{insert,"Net Down, Attempting to Recover"}}]),
							spawn(tr,recover,[]),
							trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount,MsgFlag,Msg,MsgTo,false,TimeoutCounter+1,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

						%% Wait for network re-configuration to succeed %%%%%%%%%%%%
						true when TimeoutCounter>5, TimeoutCounter=
							gs:config(Text,[{insert,{insert,"."}}]),
							trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount,MsgFlag,Msg,MsgTo,false,TimeoutCounter+1,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);

						%% Network Re-configuration has failed, enter failed loop %%
						true when TimeoutCounter > 10 ->
							print(Text,"Unrecoverable Network Failure"),
							failednodeloop(DownStreamPID,Bdie);

						%% First non-Monitor Timeout %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
						false when TimeoutCounter==0 ->
							gs:config(Text,[{insert,{insert,io_lib:format("~nTimeout",[])}}]),
							trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount,MsgFlag,Msg,MsgTo,false,1,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet);
							
						%% Non-first, non-monitor timeouts %%%%%%%%%%%%%%%%%%%%%%%%%	
						false when TimeoutCounter>0 ->
							gs:config(Text,[{insert,{insert,"."}}]),
							trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount,MsgFlag,Msg,MsgTo,false,TimeoutCounter+1,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet)
					end
			end
	end.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Loop to simulate a hardware failure that does not prevent echo mode 
%% on the transciever
%% called internally - Do Not Touch !

failednodeloop(DownStreamPID,Bdie) ->
	receive
		%% To crash a node from the GUI %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
		{gs,Bdie,click,_,_} ->
			true;

		%% To crash a node from the shell %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
		{"Die"} ->
			true;

		%% Watchdog timer %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
		{"MonitorWatchdog"} ->
			failednodeloop(DownStreamPID,Bdie);

		%% Echo anything else straight away %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
		Any ->
			DownStreamPID!Any,
			failednodeloop(DownStreamPID,Bdie)
	end.
	
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Prints text on the node's window
%% called internally - Do Not Touch !
%%	print(Text,Data)
%%		Text = reference to editor window to print in
%%		Data = text to print in window

print(Text,Data) ->
	gs:config(Text,[{insert,{{5,0},io_lib:format("~s~n",[Data])}}]),
	Text.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Manages the Token/Data indicator
%% called internally - Do Not Touch !
%%	tokenicon(W,C,T,Type)
%%		W = window reference
%%		C = canvas reference
%%		T = token indicator reference
%%		Type = what to indicate

tokenicon(W,C,T,Type) ->
	case Type of
		"token" ->
			gs:config(T,{fill,{0,128,0}}),
			timer:sleep(200),
			gs:config(T,{fill,{0,0,0}});
		"failure" -> 
			gs:config(T,{fill,{255,0,0}});
		"data" ->
			gs:config(T,{fill,{255,255,0}}),
			timer:sleep(200),
			gs:config(T,{fill,{0,0,0}})
	end.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Handles reconfiguration of a node's window and sundry from Normal 
%% to Monitor node
%% called internally - Do Not Touch !
%%	tr2mon(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,
%%							Bfail,Bclear,Text,MsgCount,MsgFlag,Msg,
%%							MsgTo,TokenFlag,TimeoutCounter,WatchdogRef,
%%							MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,
%%							MFdata,MFnet)
%%		N = Node number
%%		UpStreamPID = PID of process representing the node upstream of 
%%							this node in the network
%%		DownStreamPID = PID of process representing the node downstream of 
%%							this node in the network
%%		W = Window reference
%%		C = Canvas reference
%%		T = Token Indicator reference
%%		Bdie = 'Die' button reference
%%		Bfail = 'Fail' button reference
%%		Bclear = 'Clear' button reference
%%		Text = editor window reference
%%		MsgCount = internal node count of the number of messages received
%%		MsgFlag = boolean flag indicating the node has data to transmit
%%		Msg = data the node has ready to transmit
%%		MsgTo = the address the node wishes to send it's data to
%%		TokenFlag = boolead flag indicating possession of the token
%%		TimeoutCounter = counter indicating the number of timeouts since 
%%							the last message was recieved by the node
%%		WatchdogRef = the reference of the watchdog timer that a normal node
%%							uses to check for a monitor failure
%%		MonitorFlag = boolean flag indicating status of node as monitor
%%		RBtoken = 'Show Token' radiobutton reference
%%		RBdata = 'Show Data' radiobutton reference
%%		RBnetcheck = 'Show network messages' radiobutton reference
%%		MFtoken = MonitorFlag (boolean flag used only by monitor) to 
%%							show/hide token data
%%		MFdata = MonitorFlag (boolean flag used only by monitor) to 
%%							show/hide data packets
%%		MFnet = MonitorFlag (boolean flag used only by monitor) to 
%%							show/hide network messages

tr2mon(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount,MsgFlag,Msg,MsgTo,TokenFlag,TimeoutCounter,WatchdogRef,MonitorFlag,0,0,0,MFtoken,MFdata,MFnet) ->
	X = gs:read(W,x),
	Y = gs:read(W,y),
	gs:config(W,{map,false}),
	gs:config(W,{height,600}),
	gs:config(C,{height,600}),
	gs:config(W,{width,610}),
	gs:config(C,{width,610}),
	gs:config(Text,[{height,600},{width,400}]),
	gs:config(T,{coords,[{550,20},{590,50}]}),
	gs:config(Bdie,[{y,565},{x,560}]),
	gs:config(Bclear,[{y,505},{x,560}]),
	gs:config(Bfail,[{y,535},{x,560}]),
	gs:config(W,[{x,X},{y,Y}]),
	RBtoken = gs:create(checkbutton,W,[{label,{text,"Tokens"}},{align,w},{width,200},{x,400},{y,100}]),
	RBdata = gs:create(checkbutton,W,[{label,{text,"Data Packets"}},{align,w},{width,200},{x,400},{y,130}]),
	RBnetcheck =gs:create(checkbutton,W,[{label,{text,"Net Msgs"}},{align,w},{width,200},{x,400},{y,160}]),
	timer:send_after(10000,{"WatchdogPet"}),
	gs:config(W,raise),
	gs:config(W,{map,true}),
	print(Text,io_lib:format("Node ~w becoming Monitor Node~n",[N])),
	trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount,MsgFlag,Msg,MsgTo,TokenFlag,TimeoutCounter,WatchdogRef,true,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet).

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Handles reconfiguration of a node's window and sundry from Monitor 
%% to Normal node
%% called internally - Do Not Touch !
%%	tr2mon(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,
%%							Bfail,Bclear,Text,MsgCount,MsgFlag,Msg,
%%							MsgTo,TokenFlag,TimeoutCounter,WatchdogRef,
%%							MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,
%%							MFdata,MFnet)
%%		N = Node number
%%		UpStreamPID = PID of process representing the node upstream of 
%%							this node in the network
%%		DownStreamPID = PID of process representing the node downstream of 
%%							this node in the network
%%		W = Window reference
%%		C = Canvas reference
%%		T = Token Indicator reference
%%		Bdie = 'Die' button reference
%%		Bfail = 'Fail' button reference
%%		Bclear = 'Clear' button reference
%%		Text = editor window reference
%%		MsgCount = internal node count of the number of messages received
%%		MsgFlag = boolean flag indicating the node has data to transmit
%%		Msg = data the node has ready to transmit
%%		MsgTo = the address the node wishes to send it's data to
%%		TokenFlag = boolead flag indicating possession of the token
%%		TimeoutCounter = counter indicating the number of timeouts since 
%%							the last message was recieved by the node
%%		WatchdogRef = the reference of the watchdog timer that a normal node
%%							uses to check for a monitor failure
%%		MonitorFlag = boolean flag indicating status of node as monitor
%%		RBtoken = 'Show Token' radiobutton reference
%%		RBdata = 'Show Data' radiobutton reference
%%		RBnetcheck = 'Show network messages' radiobutton reference
%%		MFtoken = MonitorFlag (boolean flag used only by monitor) to 
%%							show/hide token data
%%		MFdata = MonitorFlag (boolean flag used only by monitor) to 
%%							show/hide data packets
%%		MFnet = MonitorFlag (boolean flag used only by monitor) to 
%%							show/hide network messages

mon2tr(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount,MsgFlag,Msg,MsgTo,TokenFlag,TimeoutCounter,WatchdogRef,MonitorFlag,RBtoken,RBdata,RBnetcheck,MFtoken,MFdata,MFnet) ->
	X = gs:read(W,x),
	Y = gs:read(W,y),
	gs:config(W,{map,false}),
	gs:config(W,[{width,400},{height,200},{bg,black}]),
	gs:config(C,[{width,400},{height,200},{bg,{70,70,85}}]),
	gs:config(T,[{coords,[{350,20},{390,50}]},{bw,5},{fg,{128,128,128}},{fill,{0,0,0}}]),
	gs:config(Text,[{vscroll,left},{bg,black},{fg,green},{insertpos,{5,0}},{wrap,word},{x,0},{y,0},{width,340},{height,200}]),
	gs:config(Bdie,[{click,true},{label,{text,"Cls"}},{height,25},{width,40},{x,350},{y,110}]),
	gs:config(Bfail,[{click,true},{label,{text,"Die"}},{height,25},{width,40},{x,350},{y,170}]),
	gs:config(Bclear,[{click,true},{label,{text,"Fail"}},{height,25},{width,40},{x,350},{y,140}]),
	gs:config(W,[{x,X},{y,Y}]),
	gs:config(W,raise),
	gs:config(W,{map,true}),
	trnodeloop(N,UpStreamPID,DownStreamPID,W,C,T,Bdie,Bfail,Bclear,Text,MsgCount,MsgFlag,Msg,MsgTo,TokenFlag,TimeoutCounter,WatchdogRef,false,0,0,0,false,false,false).
[/cc]

Nice formatting, lots of comments… yeah, I didn’t party much in college 😀

You can tell how old it is though – some easily fixed things like the integer() call which is one of a set of calls to test datatype which were replaced years ago by the is_integer() call and its ilk. And of course some things which are a bit more work – like gs, which isn’t the preferred graphics library anymore (wx has since replaced it). And there’s some sort of difference between the linux erlang implementation of gs and the solaris one (this code was all developed on a SPARCstation 4, which is why my wrists needed icing and I had to switch to an ergonomic keyboard by year’s end – I don’t know who designed those things’ keyboards, but I swear he hated the human hand and loved to cause carpal tunnel syndrome); because while this ran perfectly well on the solaris version in ’97, it doesn’t even fire up properly now; the nodesearch() call pings every erlang process running and the linux gs implementation responds to that ping with a failure exit 😀

[cc]=ERROR REPORT==== 17-Jan-2014::02:41:34 ===
Supervisor received unexpected message: {“StatusReport”,}

Process : No node info response received

Process : No node info response received
GS frontend. Last mgs in was:{“StatusReport”,}
exit:{“StatusReport”,}
Reason: {‘EXIT’,
{function_clause,
[{gs_frontend,doit,
[{“StatusReport”,},
{state,16400,,43,undefined,undefined,}],
[{file,”gs_frontend.erl”},{line,145}]},
{gs_frontend,loop,1,[{file,”gs_frontend.erl”},{line,127}]}]}}
** exception exit: {‘EXIT’,{function_clause,[{gs_frontend,doit,
[{“StatusReport”,},
{state,16400,,43,undefined,undefined,}],
[{file,”gs_frontend.erl”},{line,145}]},
{gs_frontend,loop,1,
[{file,”gs_frontend.erl”},{line,127}]}]}}
[/cc]

Okay, so quick fix is to filter that list of processes and only ping processes that are running the token ring simulator code (they’ll all be running trnode/2 as the initial call). This isn’t the most idiomatic chunk of erlang but I’m knocking off 20 years of rust here!

[cc lang="erlang"]
%% internal process called by recover
find_nodes(ProcList,KeyList) ->
	Test = hd(ProcList),
   Info = erlang:process_info(Test, initial_call),
   Call = element(2,element(2,Info)),
   if 
      Call == trnode -> Test!{"StatusReport",self()},
      receive
         {"NodeStatusReport",ThisPID,N,UpPID,DownPID}->
            put(N,{UpPID,ThisPID,DownPID}),
            NewKeyList = lists:append(KeyList,[N]),
            io:format("Process ~w : Node ~w : UpPID = ~w : DownPID = ~w~n",[ThisPID,N,UpPID,DownPID]),
            find_nodes(tl(ProcList),NewKeyList)

         %% The longest response time should be a little over 200 msec %%%%%%
         %% (the longest delay call in trnodeloop(...)%%%%%%%%%%%%%%%%%%%%%%%
         after 250 -> 
            io:format("~nProcess ~w : No node info response received~n",[Test]),
            find_nodes(tl(ProcList),KeyList)
      end;

      true -> find_nodes(tl(ProcList),KeyList)
   end.
[/cc]

And success!

Screenshot

And it runs properly too!

ScreenshotWell, that was a bit of fun 🙂 I’d forgotten how different the mindset was in practice when programming in Erlang, and it’s interesting to break your rut if you’ve been programming in one language for any length of time (and I’ve been writing C/C++/Java/Python code for the last six years or so straight, and compared to Erlang, that stuff might as well all be the same). Definitely a cobweb-clearing kind of activity, and I’d recommend it for anyone with a few cycles to burn. I’m not done with this yet either – the next job is to port it over to wx from gs. That’ll take a bit more grepping through docs, looking at the difference between the two graphics engines. I’m guessing it won’t be rocket science, but it’s competing for keyboard time with some tweaking I’m doing to SCID so I don’t have a timeline for it. But there’s a certain kind of satisfaction in seeing this kind of thing brought back from almost 20 years of bitrot so it’s not getting dropped 🙂

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.