still a mess of python, but at least it runs
ported much of the logic from javascript into python