#!/usr/bin/env Rscript
# filter_counts_10ug.R
# 从 raw_bulk_counts.csv 中只保留 control + BPA10ug 样本列,去掉 BPA10mg。
# 样本名形如: BA_RNA_<Dose>_<MouseID>_Bl_<Sex>_adt_<Lane>
# 用法:
#   Rscript filter_counts_10ug.R [input.csv] [output.csv]
# 不带参数时默认读 raw_bulk_counts.csv,写出 raw_bulk_counts_ctrl_10ug.csv

args    <- commandArgs(trailingOnly = TRUE)
infile  <- if (length(args) >= 1) args[1] else "raw_bulk_counts.csv"
outfile <- if (length(args) >= 2) args[2] else "raw_bulk_counts_ctrl_10ug.csv"

if (!file.exists(infile)) stop("找不到输入文件: ", infile)

# 第一列是基因 ID(设为行名);check.names=FALSE 保留原始样本名里的空格/特殊字符
counts <- read.csv(infile, row.names = 1, check.names = FALSE)

# 保留含 Ctrl 或 BPA10ug 的样本列,显式排除 BPA10mg
keep <- grepl("Ctrl|BPA10ug", colnames(counts)) & !grepl("BPA10mg", colnames(counts))

cat("总样本数  :", ncol(counts), "\n")
cat("保留样本数:", sum(keep), "\n")
cat("保留的样本:\n")
print(colnames(counts)[keep])

if (sum(keep) == 0) stop("没有匹配到任何 Ctrl / BPA10ug 样本,请检查列名格式")

counts_sub <- counts[, keep, drop = FALSE]

# 行名(基因 ID)会写到输出文件第一列
write.csv(counts_sub, outfile)
cat("已写出:", outfile, " (", nrow(counts_sub), "基因 x ", ncol(counts_sub), "样本)\n", sep = "")
