Generate parts of the script in a better sequence

After generating the script, it is almost never possible to run the script, when functions or triggers are present. Functions sometimes depend on each other and triggers rely on functions.
It must be fairly simple to sort the different parts in a way that makes the script run at once.