.FindTagValue <- function(path_with_globs_and_tag, actual_path, tag) {
  
  if (!all(sapply(c(path_with_globs_and_tag, actual_path, tag), is.character))) {
    stop("All 'path_with_globs_and_tag', 'actual_path' and 'tag' must be character strings.")
  }
  
  if (grepl('$', tag, fixed = TRUE)) {
    stop("The provided 'tag' must not contain '$' symbols.")
  }
  full_tag <- paste0('$', tag, '$')
  
  if (!grepl(full_tag, path_with_globs_and_tag, fixed = TRUE)) {
    stop("The provided 'path_with_globs_and_tag' must contain the tag in 'tag' surrounded by '$' symbols.")
  }
  
  parts <- strsplit(path_with_globs_and_tag, full_tag, fixed = TRUE)[[1]]
  if (length(parts) == 1) {
    parts <- c(parts, '')
  }
  parts[1] <- paste0('^', parts[1])
  parts[length(parts)] <- paste0(parts[length(parts)], '$')
  
  # Group the parts in 2 groups, in a way that both groups have a number
  # of characters as similar as possible.
  part_lengths <- sapply(parts, nchar)
  group_len_diffs <- sapply(1:(length(part_lengths) - 1), 
                            function(x) {
                              sum(part_lengths[(x + 1):length(part_lengths)]) - sum(part_lengths[1:x])
                            }
  )
  clp <- chosen_left_part <- which.min(group_len_diffs)[1]
  
  left_expr <- paste(parts[1:clp], collapse = full_tag)
  left_expr <- gsub('?', '.', left_expr, fixed = TRUE)
  # The .*? will force lazy evaluation (find the shortest match from the 
  # beginning of the actual_path).
  left_expr <- gsub('*', '.*?', left_expr, fixed = TRUE)
  left_expr <- gsub(full_tag, '.*?', left_expr, fixed = TRUE)
  left_match <- regexec(left_expr, actual_path)[[1]]

  if (left_match < 0) {
    stop("Unexpected error in .FindTagValue.")
  }
  
  right_expr <- paste(parts[(clp + 1):(length(parts))], collapse = full_tag)
  right_expr <- gsub('?', '.', right_expr, fixed = TRUE)
  # For lazy evaulation to work, pattern and string have to be reversed.
  right_expr <- gsub('*', '.*?', right_expr, fixed = TRUE)
  right_expr <- gsub(full_tag, '.*?', right_expr, fixed = TRUE)
  right_expr <- gsub('$', '^', right_expr, fixed = TRUE)
  rev_str <- function(s) {
    paste(rev(strsplit(s, NULL)[[1]]), collapse = '')
  }
  right_expr <- rev_str(right_expr)
  right_expr <- gsub('?*.', '.*?', right_expr, fixed = TRUE)
  right_match <- regexec(right_expr, rev_str(actual_path))[[1]]
  if (right_match < 0) {
    stop("Unexpected error in .FindTagValue.")
  }
  right_match[] <- nchar(actual_path) - 
    (right_match[] + attr(right_match, 'match.length') - 1) + 1
  
  if ((left_match + attr(left_match, 'match.length')) > 
      (right_match - 1)) {
    NULL
  } else {
    substr(actual_path, left_match + attr(left_match, 'match.length'),
           right_match - 1)
  }
}