port from raw mtgapi.com code