Guard against an empty material map.
Added some slightly useful output when the write fails.