Fix wrong buffer size and factorize state changes.