Fixed some bugs and made script more tolerant.