I have following dataset, recording whether individual unemployment and want to normalized my "wave" variable so that have a new variable will be 0 when the unemployment happend and other date will be normalized base on the event date. And for people never unemploy will be null. Note that I have drop all individual who experienced more than once unemploy in the dataset.

Wanted
Code:
   +------------------------------+
   | prim_key wv unemploy timeline|
   |------------------------------|
1. |        1   3      0       -2 |
2. |        1   4      0       -1 |
3. |        1   5      1        0 |
4. |        1   6      0        1 |
   |------------------------------|
6. |        2   1      1        0 |
7. |        2   2      0        1 |
8. |        2   3      0        2 |
9. |        2   4      0        3 |
10.|        2   5      0        4 |
   |------------------------------|
11.|        3   7      0        . |
12.|        3   8      0        . |
13.|        3   9      0        . |
14.|        3   10     0        . |
15.|        3   11     0        . |
   +------------------------------+
what I did seems like too complicated and I want to have a simplied version
Code:
*gen forward date
gen prev = wv if unemploy==1
bysort prim_key wv (prev) : replace prev =prev[1] if prev [1] ==1
bysort prim_key (wv): replace prev =prev[_n-1] if mi(prev)
gen forward = wv - prev

*gen backward
gen negwv = -wv
gen next = wv if unemploy ==1
bysort prim_key negwv (next): replace next =next[1] if next[1] ==1
bysort prim_key (wv) : replace next = [_n-1] if mi(next)
gen backward = wv - next

*gen timeline
gen timeline =cond(abs(forward) < abs (backward) , forward, backward)