Moved mainloop to OCaml

This makes the code simpler and easier to explain.