Some cleanup of growable arrays

NOTE: I haven't coded C for 15 years, so this probably requires some review. The documentation is not following doxygen rules - will fix this once we have doxygen documentation generation in the makefiles.

What has been done:
* moved declarations closer to where they are used
* assertions
* documentation
* added const where possible
* some early returns to avoid doing unecessary work