better threshold algorithm