Fix warnings caused by -Wsign-conversion and -Wshadow-ivar.

The casts look a bit ugly. Please, let me know if you want to change the code to avoid any of those.