write_rocrate <- function(recipes, out_dir, expid) {
  
  # Load necessary libraries
  library(yaml)
  library(jsonlite)
  

  # Loop through all recipes
  for (recipe_name in recipes) {
    
    # Read the existing rocrate YAML file
    rocrate <- read_yaml(paste0(out_dir, "/outputs/provenance/rocrate.yml"))

    # Construct JSON name and path dynamically
    recipe <- paste0("atomic_recipe_", recipe_name, ".yml")
    recipe_dir <- paste0("/tmp/", basename(out_dir), "/logs/recipes/", recipe)
    json_name <- paste0("main_provenance_", recipe_name, ".json")
    json_dir <- paste0("/tmp/", basename(out_dir), "/outputs/provenance/", json_name)
    
    # New entry to add to @graph
    #new_entry <- list(
    #  "@id" = json_dir,
    #  "@type" = "File",
    #  "dateModified" = Sys.time(),
    #  "name" = json_name,
    #  "sdDatePublished" = Sys.time()
    #)

    # Add the new entry to the @graph section
    #rocrate$ROCRATE$PATCH$`@graph` <- append(rocrate$ROCRATE$PATCH$`@graph`, list(new_entry))
    
    # Add object and result to create action entity
    results <- list(list("@id" = json_dir))
    objects <- list(list("@id" = recipe_dir))
    rocrate$ROCRATE$PATCH$'@graph'[[3]]$object <- append(rocrate$ROCRATE$PATCH$'@graph'[[3]]$object, objects)
    rocrate$ROCRATE$PATCH$'@graph'[[3]]$result <- append(rocrate$ROCRATE$PATCH$'@graph'[[3]]$result, results)

    # Define the outputs path within the rocrate
    
    rocrate$ROCRATE$OUTPUTS <- append(rocrate$ROCRATE$OUTPUTS, paste0("file://", json_dir))
    rocrate$ROCRATE$OUTPUTS <- append(rocrate$ROCRATE$OUTPUTS, paste0("file://", recipe_dir))
    
    write_yaml(rocrate, paste0(out_dir, "/outputs/provenance/rocrate.yml"))
  }

  rocrate$ROCRATE$PATCH <- toJSON(rocrate$ROCRATE$PATCH, pretty = TRUE, auto_unbox = TRUE)

  # Write the updated rocrate YAML to both specified locations
  write_yaml(rocrate, paste0(out_dir, "/outputs/provenance/rocrate.yml"))
  write_yaml(rocrate, paste0("/esarchive/autosubmit/", expid, "/conf/rocrate.yml"))

}
