Script refactored

Code was splitted into functions