import sys

argv = sys.argv
if len(argv) <= 3:
    print("")
    print("Usage: python", argv[0], "val base_source base_target")
    print("")
    exit()

val = argv[1]
base_source = int(argv[2])
base_target = int(argv[3])

base_chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
max_base = len(base_chars)

if base_source < 2 or base_source > max_base:
    print("\nError: base_source [", base_source, "] is invalid.\n")
    exit()
if base_target < 2 or base_target > max_base:
    print("\nError: base_target [", base_target, "] is invalid.\n")
    exit()

def value_base(char):
    return base_chars.index(char.upper())

print("")
print("Convert", val, "in base", base_source, "to base 10")

nstr = len(val)
v10 = 0
i = 0
while i < nstr:
    idx = nstr - 1 - i
    v = value_base(val[idx])
    if v >= base_source:
        print("Error: The value at the", i, "-th digit", v, "is not compatible with base", base_source)
        exit()
    dv = v * (base_source ** i)
    v10 = v10 + dv
    print(i, "-th digit =", str(v) + "_" + str(base_source) + ":", "+", str(v) + "*" + str(base_source) + "^" + str(i), "=> +", dv, "_10 =>", v10, "_10")
    i = i + 1

b10 = str(v10)
print()
print("Convert", b10, "in base 10 to base", base_target)

vnext = v10
starget = ''

while True:
    n = vnext // base_target
    residue = vnext % base_target
    starget = base_chars[residue] + starget
    print(vnext, "=", n, "*", base_target, "+", residue, ":", "base_" + str(base_target), "=>", starget)
    if n == 0:
        break
    vnext = n

print()
