Significantly fix and clean up mask code