The main script, with a lot of improvement