# Used exclusively in gsub to replace var names with useful names.  We set
# the name to be of a pretty set format so it's very easy to muck with the
# vars later without worrying about accidentally grabbing a string that looks
# like a var, but isn't.
def replace_vars(global_def, prefix, funk, suffix, vars, var_usage)
  vartype = global_def.empty? ? 'v_' : 'g_'

  old_name = '%s%s%s' % [prefix, funk, suffix]
  new_name = vars[old_name]

  if !new_name
    # No existing item means we create one
    new_name = '$%s%06d_' % [vartype, $varnum]
    vars[old_name] = new_name
    var_usage[new_name] = 0
    var_usage[new_name] += 1 unless vartype == 'g_'
    $varnum += 1
  else
    # Otherwise we increment the use counter for the new name
    var_usage[new_name] += 1
  end

  return '%s%s' % [global_def, new_name]
end

# Given a variable name, what it's assigned to, and a hash telling us what all
# known globals have been assigned to, we store variables and their
# assignments as long as they're only assigned to a single value.  If they get
# reassigned to something different, we mark them invalid so we know we
# shouldn't name the variable anything too specific
def gather_assigns(varname, assign, var_assigns)
  current_value = var_assigns[varname]
  if (current_value)
    # Already assigned?  If assignment is different, we have a var that isn't
    # a constant
    if current_value != assign
      var_assigns[varname] = :invalid
    end
  else
    # Not assigned - we can just store it as-is
    var_assigns[varname] = assign
  end
end
