factor out 'generic' functions into util.c