```{asis, echo = {{penvs_drawBgExtent_knit}}, eval = {{penvs_drawBgExtent_knit}}, include = {{penvs_drawBgExtent_knit}}}
### Process environmental data
Sampling of {{bgPtsNum_rmd}} background points and corresponding environmental data using a user drawn background extent with a {{drawBgBuf_rmd}} degree buffer.
```

```{r, echo = {{penvs_drawBgExtent_knit}}, include = {{penvs_drawBgExtent_knit}}}
# Create a background extent based on user drawn polygon
bgExt_{{spAbr}} <- penvs_drawBgExtent(
  polyExtXY = matrix({{polyExtXY_rmd}},ncol=2,byrow=FALSE), 
  polyExtID = {{polyExtID_rmd}}, 
  drawBgBuf = {{drawBgBuf_rmd}}, 
  occs = occs_{{spAbr}})
# Mask environmental data to provided extent
bgMask_{{spAbr}} <- penvs_bgMask(
  occs = occs_{{spAbr}},
  envs = envs_{{spAbr}},
  bgExt = bgExt_{{spAbr}})
# Sample background points from the provided area
bgSample_{{spAbr}} <- penvs_bgSample(
  occs = occs_{{spAbr}},
  bgMask =  raster::stack(bgMask_{{spAbr}}),
  bgPtsNum = {{bgPtsNum_rmd}})
# Extract values of environmental layers for each background point
bgEnvsVals_{{spAbr}} <- as.data.frame(terra::extract(bgMask_{{spAbr}},  bgSample_{{spAbr}}))
##Add extracted values to background points table
bgEnvsVals_{{spAbr}} <- cbind(scientific_name = paste0("bg_", "{{spName}}"), bgSample_{{spAbr}},
                            occID = NA, year = NA, institution_code = NA, country = NA,
                            state_province = NA, locality = NA, elevation = NA,
                            record_type = NA, bgEnvsVals_{{spAbr}})
```
