This may be the problem...you're looping the entire saving operation twice, once for each order, but you should only be looping the setting of the element orders, not the whole save process.  That may be the challenge, it works once, and then the second time overwrites something, or something like that