Refactor script

Probably some bugs in there but nothing major. I think the structure is messy
and should be simplified. I should also find a better way to handle img_observer
and remove the global variables