Modified and refined python script