Corrected invalid casting, also fixed invalid type handling