It's really late, but the basic formula is going to be something like
for x > 360, take the remainder of x/360.
400, for example. 400/360 is 1 (throw that away) with a remainder of 40, or think of it as 40 degrees past one full circle.
For x < 0 ....
take x + (360+360*INT(x/360))
meaning -20 gives
-20 + 360 + 0, or 340.
-400 gives us
-400 + 360 + (360*1) or 720 - 400 = 320.
Double check that, but it looks close.