Buffalo overcomes costly mistakes, survives Miami's bid at historic upset