added some type annotations, removed asInstanceOf[..]