Completed erlang version. There may still be some optimizations to do...