year <- sub("-.*", "", meta$Date)

if (!length(year)) {
  i <- regexpr("(?<=\\s{1})\\d{4}(?=-{1})", meta$Built, perl = TRUE)
  year <- substring(meta$Built, i, i + 3)
}

if (!length(year)) {
  year <- substr(Sys.Date(), 1, 4)
}

pkg <- meta$Package
vers <- meta$Version
title <- meta$Title

if (is.null(vers)) {
  vers <- packageVersion("SLOPE")
}

vers <- paste("R package version", vers)

author <- meta$`Authors@R`
if (length(author)) {
  aar <- .read_authors_at_R_field(author)
  author <- Filter(function(e) {
    !(is.null(e$given) && is.null(e$family)) && !is.na(match(
      "aut",
      e$role
    ))
  }, aar)
  if (!length(author)) {
    author <- Filter(function(e) {
      !(is.null(e$given) && is.null(e$family)) && !is.na(match(
        "cre",
        e$role
      ))
    }, aar)
  }
}
if (length(author)) {
  has_authors_at_R_field <- TRUE
} else {
  has_authors_at_R_field <- FALSE
  author <- as.person(meta$Author)
}

author <- format(author, include = c("given", "family"))
if (length(author) > 1L) {
  author <- paste(paste(head(author, -1L), collapse = ", "),
    tail(author, 1L),
    sep = " and "
  )
}

bibentry(
  bibtype = "Manual",
  title   = paste0("{", pkg, "}: ", title),
  author  = author,
  year    = year,
  note    = vers,
  url     = "https://CRAN.R-project.org/package=SLOPE",
  header  = "To cite the SLOPE package in publications, please use:"
)

bibentry(
  bibtype = "Article",
  title = "{{SLOPE}} -- Adaptive Variable Selection via Convex Optimization",
  author = c(
    person("Małgorzata", "Bogdan"),
    person("Ewout", "van den Berg"),
    person("Chiara", "Sabatti"),
    person("Weijie", "Su"),
    person("Emmanuel J.", "Candès")
  ),
  journal = "The annals of applied statistics",
  volume = 9,
  number = 3,
  pages = "1103--1140",
  year = 2015,
  doi = "10.1214/15-AOAS842",
  issn = "1932-6157",
  header = "To cite the SLOPE method in publications, please use:"
)
