Reimplement beam search