Tested/rewritten version of python code