add more error checking and some cleverer simple masking