Fixed a possible NULL pointer dereference
Fixed some warnings
Added some checks on reading