-module(mymodule).

-export([
  main/0,
  firsthandler/0,
  secondhandler/0
]).



main() ->

  FirstPID  = spawn(mymodule, firsthandler, []),                    % create two processes
  SecondPID = spawn(mymodule, secondhandler, []),

  register(first_process,  FirstPID),                               % name the processes
  register(second_process, SecondPID),                              % this is fairly gratuitous

  first_process ! get_started,                                      % send a message "get_started" to the first process

  { ok, this_process_terminating, other_two_are_going, have_fun }.  % return a value and terminate this process.  the other two will continue on happily.






firsthandler() ->

  receive                                                           % will block here for free until a message comes in, from the original process; receive is an operator

    get_started  ->
      second_process ! { self(), i_r_teh_awakes },                  % send a tuple as a message to second_process; self() gets the local process ID; think of it like a this pointer in c++
      first_handler();                                              % tail recursion to start the handler anew; this is the typical infinite erlang handler loop

    die_damn_you ->
      io:format("zomg firstproc is dying~n"),                       % print to console
      ok                                                            % return a value, which effectively terminates the process, since there's nothing left to do
 end.





secondhandler() ->

  receive                                                           % again, blocking

    { PID, i_r_teh_awakes } ->                                      % get the message from firsthandler when available. where it said self() before, the value is going to be assigned to PID - that's pattern matching
      io:format("secondproc tells firstproc to die~n"),             % print to console
      PID ! die_damn_you,                                           % so, send a message back to the PID that messaged us, advocating murder
      io:format("secondproc dies~n"),                               % print to console
      ok                                                            % and terminate

end.