// (c) Rebecca Dell, University of Cambridge, December 2020
// Function to Mask Rock Outcrops following Moussavi et al. (2020), with an additional 1km buffer (Halberstadt et al., 2020). 

exports.rock_mask = function(image) {
  var BLUE = image.select('B2');
  var TIRS = image.select('B10'); 
  var TIRSBLUE = (TIRS).divide(BLUE);//.rename("TIRSBLUE");
  // produces an array of 1's where both criteria below fufilled
  var threshold_1 = TIRSBLUE.gt(650).and(BLUE.lt(0.35));
  
   // produces a mask of 1s where 1s already were - basically pointless but if you wanted a mask where 0's were would be useful
  var threshold_1_mask = threshold_1.eq(1);
  
  // Apply a rock buffer
  // Calculates distance to nearest non 0 pixel
  var RockDistance = threshold_1_mask.fastDistanceTransform(40).sqrt()
                           .multiply(ee.Image.pixelArea().sqrt());
  // Make rock buffer if rock distance is 1000m or less AND pixel isn't already masked as rock 
  var RockBuffer = RockDistance.lte(1000);//.and(threshold_1_mask.not());
  
 // var rock_mask = threshold_1_mask.eq(1).or(RockBuffer.eq(1));
  return image.updateMask(RockBuffer.not());
};

// REFERENCES

//Halberstadt, A. R. W., Gleason, C. J., Moussavi, M. S., Pope, A., Trusel, L. D., & DeConto, R. M. (2020). 
//Antarctic supraglacial lake identification using landsat-8 image classification. Remote Sensing, 12(8), 
//1–29. https://doi.org/10.3390/RS12081327

//Moussavi, M., Pope, A., Halberstadt, A. R. W., Trusel, L. D., Cioffi, L., & Abdalati, W. (2020). 
//Antarctic Supraglacial Lake Detection Using Landsat 8 and Sentinel-2 Imagery: Towards Continental 
//Generation of Lake Volumes. Remote Sensing, 12(1), 134. https://doi.org/10.3390/rs12010134