Updated version, adding some logging, removed a faulty cast.