Updated and optimized script. Still debugging.