optimized the script and fixed a little bug