Improve mapping for more functions.

I moved the module definition to its own file because I think it's more convenient.
Also, a lot of this code can go into separate files for clarity ... there's a lot of stuff here and no clear structure. Using separate files would help a lot.