Begin A1_DAT_SRT_Teleport

Short state  ; 0 = first run, 1 = wait for fade, 2 = teleport, 3 = done teleport (fade in), -1 = stop

Short Cell   ; 0 = exterior, 1 = plaza brindisi, 2 = mournhold temple

Short CellY  ; current Y cell location
Float Pos    ; scratch variable
Float Angle  ; scratch variable
Float Timer  ; times fadeout

; initialize
If ( State == 0 )
	FadeOut 0.2
	Set State to 1

; wait for fade out
ElseIf ( state == 1 )   
	Set Timer to ( timer + GetSecondsPassed )
	If ( timer > 0.25 )  ; it is dark now
    		Set Timer to 0
    		Set State to 2    
Endif

; teleport
ElseIf ( State == 2 )
	; get global teleport position
	Set Cell  to "A1_DAT_SRT_TeleCell"
	; check indoor cells
	If ( Cell > 0 )
		StartScript, "A1_DAT_SRT_SetCell"		; position in indoor cell
		Set State to -1
		Return
	Endif

	; activate any "A1_DAT_SRT_CoE_*" scripts by setting the "A1_DAT_SRT_tele_state" to 1
	Set "A1_DAT_SRT_TeleState" to 1         

	; handle known scripts extra efficient (so they don't have to be global)
	Set Pos to ( "A1_DAT_SRT_RecPosY" )
	Set CellY to ( Pos / 8192 )

If ( cellY <= 0 )
		StartScript "A1_DAT_SRT_CoE_V_Lo"  
	Elseif ( cellY <= 14 )
		StartScript "A1_DAT_SRT_CoE_V_Mid"
	Elseif ( cellY <= 28 )
		StartScript "A1_DAT_SRT_CoE_V_Hi"  
	Endif

ToggleGodMode      ; ensure a player survives being centered in lava or something :)
Set State to 3     ; and wait for *any* script to do "coe" (for 1 frame)

; wait for other teleport scripts
Elseif ( state == 3 )
	; disable teleportation (this assumes global scripts are run in a fixed order)
	Set "A1_DAT_SRT_TeleState" to 0       
 
If ( CellChanged == 1 )
	; we have teleported, fix the position
	Set Pos to "A1_DAT_SRT_RecPosX"
		Player->SetPos, X, pos
	Set Pos to "A1_DAT_SRT_RecPosY"
		Player->SetPos, Y, pos
	Set Pos to "A1_DAT_SRT_RecPosZ"
		Player->SetPos, Z, pos
	Set Angle to "A1_DAT_SRT_TeleAngle"
		Player->SetAngle, Z, Angle

	; become mortal again
	ToggleGodMode      

	; and fade in again
	FadeIn 0.25
  
Else
	; no teleport: we use the generic coe script
	ToggleGodMode   ; restore mortality
	StartScript "A1_DAT_SRT_CoE_Gen"  
Endif 

; and we are done
Set State to -1

; stop running
Else  ; if ( state == -1 )
	; MessageBox "Stop teleport script"
	Set state to 0      ; reset state for the next run
	StopScript "A1_DAT_SRT_Teleport"
 
Endif

End