Fixed compiler errors (mainly invalid type conversions).
Fixed invalid read (reported by valgrind).