var quoted_regexp = /"[\s,]*[^"]*?[\s,]*"/g;
function get_tag_separator(tag_string) {
  var no_quotes = tag_string.replace(quoted_regexp, '');
  return no_quotes.match(',') ? /\s*,\s*/ : /\s+/;
}
function get_last_tag(tag_string) {

  var separator = get_tag_separator(tag_string);

  if (tag_string.match(quoted_regexp)) {

    var quoted_strings     = tag_string.match(quoted_regexp);
    var non_quoted_strings = tag_string.split(quoted_regexp);

    if (quoted_strings[non_quoted_strings.length - 1]) {
      return '';
    } else {
      return get_last_tag(non_quoted_strings[non_quoted_strings.length - 1]);
    }

  } else {

    if (tag_string.match('"')) {
      var inc_quote_match = tag_string.match(/"[^"\s,][^"]*$/);
      if (inc_quote_match) {
        return inc_quote_match[0];
      } else {
        return '';
      }
    } else  {
      var tags = tag_string.split(separator);
      return tags[tags.length - 1];
    }

  }

}
function replace_last_tag(old_value, tag) {
  var last_tag = get_last_tag(old_value);
  var reg = new RegExp(last_tag + '$');
  if (last_tag.match(/^"/)) {
    tag = '"' + tag + '"';
  }
  return old_value.replace(reg, tag);
}
