added a few casts and some extra type safety.