Changed magic handling to be more general and hopefully robust