Fix signedness and handle optional variable better (#4085)

Closes #4085.