Some improvements

Localizing variables and functions
Removed unnecessary looping