Made script a bit more intelligent
But also more ugly