I got a raw dataset in a wide format that includes hundreds of variables defining drug prescriptions. The problem is that the dates of prescriptions are not sequential and may not start with a variable 1. See the example below:

Raw dataset:
1 date . date . .
2 . date date . .
3 . . date . date
4 date . date . .
5 date . . . date
...
1000 date date . . .
I would like to restructure the dataset in the following way (that the dates are sequential in each row and the first prescription date is in the variable1(Rx1_dte):
ID Rx1_dte Rx2_dte Rx3_dte ... Rx500_dte
1 date date . . .
2 date date . . .
3 date date date . .
4 date . date . .
5 date date . . .
...
1000 date date . . .

What I have in mind:

*Generate 500 empty variables
forval i = 0/500 {
gen Rx`i'_dte_new = .
}
replace Rx0_dte_new = td(1jan1900)

* replace those by variables from the raw dataset
forval i = 1/500 {
forval j = 1/500 {
replace Rx`i'_dte_new = Rx`j'_dte if Rx`j'_dte != . & Rx`j'_dte > Rx`=`j'-1'_dte
}
}

The problem with this code is that prescriptions made on the same data are ingored. Could you please help me to fix this code?