Various bug fixes, props @jrfnl