Factored out some ugly code