#!/usr/bin/env julia
if length(ARGS) != 2
        println("Usage: strip_simfiles.jl <dir> <prefix>")
        exit(1)
end

basedir = ARGS[1]
prefix = ARGS[2]

using RCall

R"""
ReadAndRemoveT <- function(simdir) {
        tmp <- PoetUtils::ReadPOETSims(simdir)
        stripped <- lapply(tmp, function(x) {x$T <- NULL; return(x)})
        for (i in seq_along(stripped)) {
                stopifnot(all.equal(tmp[[i]]$C, stripped[[i]]$C))
                PoetUtils::SaveRObj(stripped[[i]], path=paste0(simdir,"/",names(stripped)[i],"_str.qs2"))
          }
      }
"""

function ReadAndRemoveT(simdir)
        @rput simdir

        R"ReadAndRemoveT(simdir)"
end

for sim_dir in readdir(basedir)
        if !occursin(prefix, sim_dir)
                continue
        end

        current_dir = joinpath(basedir, sim_dir)

        ReadAndRemoveT(current_dir)

        new_files = readdir(current_dir; join=true)
        for file in new_files
                if !occursin("_str.qs2", file)
                        continue
                end
                mv(file, replace(file, "_str.qs2" => ".qs2"); force=true)
        end
end
