
initialiseStructure = function(stud_ids, correct_file) {
  dd = vector("list", length(stud_ids))
  names(dd) = stud_ids

  initial_list = list(
    stud_id = NULL,
    stud_name = NULL,
    
    filename_dir = NULL,
    has_correct_filename = TRUE,
    correct_filename = correct_file,
    your_filename = correct_file, 
    is_binary = FALSE,

    can_source = TRUE,
    source_error = vector(),

    env = NULL,
    has_add_variables = FALSE,
    add_variables = vector(),
    
    code_tests = NULL
    )
  for(id in stud_ids) {
    dd[[id]] = initial_list
    dd[[id]]$stud_id = id
  }
  return(dd)
}


addFunction = function(struct, fun_name, no_of_tests) {

  test_list = list(
    fun_name=fun_name,
    fun_call = NULL,
    args=NULL,
    
    can_run = TRUE,
    run_error = NULL,

    max_marks = 1,
    mark = 1,

    is_correct = TRUE,
    correct_answer = NULL,
    your_answer = NULL,

    compare=NULL)

  for(st in 1:length(struct)) {
    fun_test = vector("list", no_of_tests)
    for(i in 1:no_of_tests) 
      fun_test[[i]] = test_list
    
    struct[[st]][["tests"]][[fun_name]] = fun_test
  }
  return(struct)
}

addStudentName = function(dd, stud_names) {
  stud_ids = names(dd)
  for(id in stud_ids) 
    dd[[id]]$stud_name = as.character(stud_names[stud_names[,1] == id,][,2])
  return(dd)
}

addFilePath = function(dd, stud_paths) {
  stud_ids = names(dd)
  for(id in stud_ids) 
    dd[[id]]$filename_dir = as.character(stud_paths[stud_paths[,1] == id,][,2])
  return(dd)
}


checkFilename = function(d) {
  filename = list.files()
  if(filename != d$correct_filename) {
    #mv_com = paste("mv", filename, d$correct_filename)
    #system(mv_com)
    d$your_filename = filename
    d$has_correct_filename = FALSE
  }
  return(d)
}

checkFileSource = function(d) {
  ringed_env = new.env()
  y = try(sys.source(d$your_filename, ringed_env), TRUE)
  if(class(y) == "try-error") {
    d$can_source = FALSE
    d$source_error = y[1]
    if(y[1] == "Error in parse(n = -1, file = file) : 3:1: unexpected $end\n")
      d$is_binary=TRUE
  }
  d$env = ringed_env
  return(d)
}

checkAddVariables = function(d) {
  if(d$can_source) {
    ringed_env = d$env
    for(variable in ls(ringed_env)) {
      if(!is.function(get(variable, envir=ringed_env))) {
        d$has_add_variables = TRUE
        d$add_variables = c(d$add_variables, variable)
      }
    }
  }
  return(d)
}
