Add prototypes. Add more utility functions.

An attempt to optimize a bit, and make the code cleaner and easier to read.