Fixed bugs off by one bugs in scripts