make the casting magic standards compliant and avoid compiler warnings; add error check