Attempting to fix strangely running script