Fixed illegal casting
Refactored