# Steatotic liver disease from transient elastography (2017 on) and its cardiometabolic criteria.

# The five cardiometabolic risk factors of the 2023 multisociety MASLD definition, each 1 if met:
# (1) BMI 25 or more, or waist 94 cm or more (men) or 80 cm or more (women);
# (2) fasting glucose 100 mg/dL or more, HbA1c 5.7% or more, or diagnosed or treated diabetes;
# (3) blood pressure 130/85 mmHg or more, or treated hypertension;
# (4) triglycerides 150 mg/dL (1.70 mmol/L) or more, or lipid-lowering treatment;
# (5) HDL under 40 mg/dL (men) or 50 mg/dL (women), or lipid-lowering treatment.
# A criterion whose measurement is missing counts as not met (fasting glucose and triglycerides
# exist only for the fasting subsample). Returns the number met.
cardiometabolic_criteria <- function(cycle, demo) {
  s <- demo[, c("SEQN", "sex")]
  bm <- body_measures(cycle); g <- fasting_glucose(cycle); h <- hba1c(cycle); dq <- diabetes_questions(cycle)
  bp <- blood_pressure(cycle); bq <- bp_questions(cycle); tg <- triglycerides(cycle); hdl <- hdl_cholesterol(cycle)
  at <- function(frame, column) frame[[column]][match(s$SEQN, frame$SEQN)]
  bmi <- at(bm, "bmi"); waist <- at(bm, "waist")
  c1 <- bmi >= 25 | (s$sex == 1 & waist >= 94) | (s$sex == 2 & waist >= 80)
  c2 <- at(g, "glucose") >= 100 | at(h, "hba1c") >= 5.7 | at(dq, "told_diabetes") == 1 | at(dq, "insulin") == 1 | at(dq, "pills") == 1
  c3 <- at(bp, "sbp") >= 130 | at(bp, "dbp") >= 85 | at(bq, "bp_medication") == 1
  lipid_treatment <- at(bq, "cholesterol_medication") == 1
  c4 <- at(tg, "tg") >= 150 | lipid_treatment
  c5 <- (s$sex == 1 & at(hdl, "hdl") < 40) | (s$sex == 2 & at(hdl, "hdl") < 50) | lipid_treatment
  met <- cbind(c1, c2, c3, c4, c5)
  met[is.na(met)] <- FALSE
  data.frame(SEQN = s$SEQN, cardiometabolic = rowSums(met))
}

# Average alcohol in grams a day from the questionnaire: drinks on a drinking day times drinking
# days a year over 365, at 14 g a drink (a US standard drink).
alcohol_grams <- function(alq) {
  ifelse(alq$alcohol3 %in% 1:2, 0, alq$drinks_per_day * alq$drinking_days / 365 * 14)
}

# Self-reported liver cancer: any of the first three cancer types reported is liver (code 22).
liver_cancer <- function(cycle) {
  d <- component("MCQ", cycle)
  types <- d[, intersect(c("MCQ230A", "MCQ230B", "MCQ230C"), names(d)), drop = FALSE]
  data.frame(SEQN = d$SEQN, liver_cancer = as.integer(rowSums(types == 22, na.rm = TRUE) > 0))
}
