factor out code and add sane defaults