% Sorted list handling
-module(sl).
-compile(export_all).

%% Returns a list where the new key and value are inserted.

insert({Key, Value}, [{HK, HV}|T]) when Key =< HK ->
	[{Key, Value}, {HK, HV}|T];
insert({Key, Value}, [{HK, HV}|T]) ->
	[{HK, HV}|insert({Key, Value}, T)];
insert({Key, Value}, []) -> [{Key, Value}].

start() ->
	register(listStore, spawn(sl, listLoop, [[]])).

%% Maintain a list in the server loop:
listLoop(L) ->
	receive {insert, {Key,Value}} ->
		io:format("insert of ~w, ~w~n", [Key,Value]),
		listLoop(insert({Key,Value}, L));
		{P, getList} ->
		io:format("getList from ~w~n", [P]),
		P ! L, listLoop(L);
		shutdown ->
		io:format("Castle of arrrrgggh...~n", []),
		unregister(listStore), exit(normal)
	end.

%% Client side one-shot access funcs:
addElem(E) ->
	listStore ! {insert, E}.

getList() ->
	listStore ! {self(), getList},
	receive L ->
		L
	end.

shutdown() ->
	listStore ! shutdown,
	complete.

%% Caveat: it seems that module reloading with c:c kills the server loop
%% if the file is reloaded unchanged (?).

