###############################################################################
##  BKMutate - full demonstration
##  Runs every analysis and saves each figure as a 300 dpi PNG.
###############################################################################

library(BKMutate)
library(ggplot2)

out <- file.path(tempdir(), "BKMutate_figures")
dir.create(out, showWarnings = FALSE)
sav <- function(p, f, w = 8, h = 5.2)
  ggsave(file.path(out, f), p, width = w, height = h, dpi = 300)

## ---- 1. Dose-response: LD50 with Fieller intervals ------------------------
ld <- bm_dose(bm_data("dose"), dose = "dose", n_total = "n_treated",
              n_affected = "n_survived", mutagen = "mutagen")
print(ld)
sav(bm_plot(ld), "01_dose_response.png")

## ---- 2. Effectiveness and efficiency with confidence intervals ------------
ef <- bm_effect(bm_data("m2"), mutagen = "mutagen", dose = "dose",
                m2_total = "M2_plants", m2_mutants = "M2_mutants",
                lethality_n = "lethality_n", lethality_x = "lethality_x",
                sterility_n = "sterility_n", sterility_x = "sterility_x",
                injury = "injury_pct", boot = 2000)
print(ef)
sav(bm_plot(ef), "02_effectiveness.png", w = 9)
sav(bm_plot(ef, type = "efficiency"), "03_efficiency.png", w = 9)

## ---- 3. Chlorophyll mutation spectrum -------------------------------------
sp <- bm_spectrum(bm_data("spectrum"), mutagen = "mutagen",
                  classes = c("albina", "xantha", "chlorina", "viridis"),
                  dose = "dose")
print(sp)
sav(bm_plot(sp), "04_spectrum.png", w = 7)
sav(bm_plot(sp, type = "diversity"), "05_spectrum_diversity.png", w = 7)

## ---- 4. M2 counts, overdispersion handled ---------------------------------
m2 <- bm_m2(bm_data("counts"), counts = "mutants", mutagen = "mutagen",
            dose = "dose", plants = "plants")
print(m2)
sav(bm_plot(m2), "06_m2_rates.png")

## ---- 5. Comparison of mutagens --------------------------------------------
cmp <- bm_compare(ef, dose_fit = ld, reference = "Gamma")
print(cmp)
sav(bm_plot(cmp), "07_mutagen_comparison.png", w = 7)

cat("\nAll analyses complete. Figures in:", out, "\n")
###############################################################################
