Hi! I was wondering if you could help me with the following question:

I have the following (abbreviated) data set, where I have two type of variables. The first one, total_mi, adds up a_m1 through a_m12, it is essentially the row total. The second type of variable is the a_m* variables, which to keep the explanation simple, is equal to 1 when something else occurs in the data set, as you can see, they do not always turn 1, which means that there may be missing values in between the different a_m* columns (see the bold row below for the example that is easy to follow).

Code:
* Example generated by -dataex-. To install: ssc install dataex
clear
input float(total_mi a_m1 a_m2 a_m3 a_m4 a_m5 a_m6 a_m7 a_m8 a_m9)
2 1 . . . . 1 . . .
8 1 1 1 1 1 . 1 1 1
7 1 1 1 1 1 1 . 1 .
8 1 1 1 1 1 1 1 1 .
6 1 1 1 1 1 1 . . .
8 1 1 1 1 1 . 1 1 1
7 1 1 1 1 1 1 1 . .
8 1 1 1 1 1 1 1 1 .
2 1 1 . . . . . . .
5 1 1 . 1 . . 1 1 .
4 1 . . 1 1 . 1 . .
9 1 1 1 1 1 1 1 1 1
7 1 1 1 1 1 . 1 1 .
8 1 1 1 1 1 1 1 1 .
8 1 1 1 1 1 1 . 1 1
end
I want to "automatically" (through some code which I can't seem to program correctly) replace the previous data set into the following:

Code:
clear
input float total_mi byte(key1 key2 key3 key4 key5 key6 key7 key8 key9)
2 1 . . . . .2 . . .
8 1 2 3 4 5 . 6 7 .
7 1 2 3 4 5 6 . 7 .
8 1 2 3 4 5 6 7 . .
6 1 2 3 4 5 6 . . .
8 1 2 3 4 5 . 6 7 .
7 1 2 3 4 5 6 7 . .
8 1 2 3 4 5 6 7 8 .
2 1 . . . . . . . .
5 1 2 . 3 . . 4 5 .
4 1 . . 2 3 . 4 . .
9 1 2 3 4 5 6 7 8 9
7 1 2 3 4 5 . 6 7 .
8 1 2 3 4 5 6 7 8 .
8 1 2 3 4 5 6 . 7 8
end

As you can see, all that I want to do is turn the 1s into a consecutive sequence from 1 to n, where n is the row total (total_mi). How can I achieve this? Any help/suggestions are welcome.

Thanks!