from kicad_sym import *

def make_pins(lines, half_width):
    pin_sort = lambda l: pin_sort_key(l[1])
    lines = sorted(lines, key=pin_sort)
    input_p = lambda lnt: lnt[2] in {"input", "power_in"}
    left = list(filter(input_p, lines))
    right = list(filterfalse(input_p, lines))
    pins = chain(
        make_pin_left(left, half_width),
        make_pin_right(right, half_width)
    )
    return pins, max(len(left), len(right))

def make_lib(lines):
    half_width = 12
    source, sink, other = split_power(lines)
    pins, max_len = list(make_pins(other, half_width))
    all_pins = chain(
        pins,
        make_pin_top(source),
        make_pin_bottom(sink, max_len),
    )
    return lib([
        symbol("ATF22V10C", "ATF22V10C",
               all_pins,
               u(-half_width), u(2),
               u(half_width),  u(-(max_len * 2)))
    ])

lines = read_txt("atf22v10c.txt")
print(make_lib(lines))
