Added specific error messages for specific errors.
Internal cleanup and reordering. Also added function documentation and modified (debug) output format.