ported more of the code from bash to python