added python3 compatibility by catching the errors with xrange