documentation
and free some memory on errors