Fix signedness and handle optional variable better

Closes #4085.