It isn't very clear what the conditions for raising errors vs returning are. The function needs tidying up