Fix bad_alloc error and add some extra diagnostic tools