more general solution to IllegalStateException problem