added free_mem routine + graceful exit even on error(hopefully)