Process FOR loop for subform items in the order of the manual sorting

Process FOR loop for subform items in the order of the manual sorting

Hi Guys, 

I have searched everywhere and tried everything, but I still not able to resolve one particular challenge. 

I have a subform in my Invoice with rows for each item. I made it so that we can change the order of the items manually. I need to be able to run FOR loop to process all items in the exact order they were re-arranged manually, but whatever I do - it always picks up in the order the records were initially added. Surely there must be some kind of Order/Sorting ID or metadata that can be used to process items in the exact order they are on the subform list (simply because when form is loaded, somehow Creator already knows what exact manual sorting order records are in)

Would you please be able to give me some guidance on how to do this?

Ultimately, I need to be able to calculate correct balance for each row when sorting is changed manually:

For example:

Original sorting:

Item | Amount | Balance
Rec1 | $10 | $10
Rec2 | $20 | $30
Rec3 | $30 | $60

Manual sorting - note that Balance should be re-calculated correctly for each row. I am doing it on form-submit, so, I intend to run this calculation every time the form is submitted, even if no sorting was changed. This is to ensure we have correct amounts and balances every time invoice is submitted.

Item | Amount | Balance
Rec3 | $30 | $30
Rec2 | $20 | $50
Rec1 | $10 | $60

I am doing basic FOR loop:

running_balance = 0;
for each i in input.items_list
{
   running_balance = running_balance + i.Amount;
   i.Balance = running_balance;
}
input.Total_Balance = running_balance;

At the moment I am not displaying balance on the invoice, as it is always wrong if sorting is changed (FOR loop seems to be always processing records in the order of subform item IDs, not in the order they are sorted manually).

I do have overal total balance, which is correct, but having running balance on each row is super handy as we can easily see over time how it is changing and it is also so much easier to visually assess current state of the invoice and have it as a reference point.