Adding complete script functionality from Lai's repo