Fixed some issues and made script more flexible