Stranded in the dunes - please help

I ve got problem with this level. I reach the place where is skeleton king but i have too less
energy to win the game, this is my code:

while (true) {
var enemy = hero.findNearestEnemy();
var flag = hero.findFlag(“green”);
if (flag) {
if (hero.distanceTo(flag) < 40) {
hero.pickUpFlag(flag);
if (enemy) {
if (enemy.type != “sand-yak”) {
hero.attack(enemy);
var distance = hero.distanceTo(enemy);
if (distance < 5) {
if (hero.isReady(“cleave”)) {
hero.cleave(enemy);
} else {
hero.attack(enemy);
}
}
}
}
}
}
}

while (true) {
    var enemy = hero.findNearestEnemy();
    var flag = hero.findFlag("green");
    if (flag) {
        if (hero.distanceTo(flag) < 40) {
            hero.pickUpFlag(flag);
            if (enemy) {
                if (enemy.type != "sand-yak") {
                    hero.attack(enemy);
                    var distance = hero.distanceTo(enemy);
                    if (distance < 5) {
                        if (hero.isReady("cleave")) {
                            hero.cleave(enemy);
                            } else {
                            hero.attack(enemy);
                        }
                    }
                }
            }
        }
    }
}

I’m afraid there’s not much I can really help you with here, your code is pretty good, but that’s not really the point. This is an optional challenge level, if you can’t do it now why not come back to it later? You don’t need to do it to continue with the campaign. There’s not “right” code for this level.
Danny