' Emco 8 station turret index
' Version 1.0.2
' (c) G. Waterworth 11/12/2007

Sub Main()
If IsLoading() then
  ' do nowt
Else
  OldTurretPos=(GetOEMDRO(824))   'current tool position
  NextTool=GetSelectedTool()      'tool to be indexed
  
  If OldTurretPos<>NextTool Then
    ' new tool required
    If NextTool<1 Or NextTool>8 Then 'valid tool check
      Message("Next Tool out of range")
      Exit Sub
    End If

    ActivateSignal(OUTPUT4)   'rotate Turret 

    '=== Index Tool ===
    Select Case NextTool
	Case 1
		count=1
	Case 2
		count=3
	Case 3
		count=2
	Case 4
		count=6
	Case 5
		count=4
	Case 6
		count=12
	Case 7
		count=8
	Case 8
	  	count=9
    End Select

    thistool=OldTurretPos

    While thistool<>count
      sensors=0
      While sensors=0
        if IsActive(OEMTRIG1) then sensors=sensors+1
        if IsActive(OEMTRIG2) then sensors=sensors+2
        if IsActive(OEMTRIG3) then sensors=sensors+4
        if IsActive(OEMTRIG4) then sensors=sensors+8
      Wend
      thistool=sensors
    Wend

    Code"G04 P50"
    While Ismoving()
    Wend
  
    DeActivateSignal(OUTPUT4) 'stop turret rotation
    SetCurrentTool(thistool)
  End If
End If
End Sub            

'The actual timings are:-
'
'opto		1	2	3	4
'pin 		10	11	12	13
'value	1	2	4	8
'Tool 1	on	off	off	off
'Tool 2	on	on	off	off
'Tool 3	off	on	off	off
'Tool 4	off	on	on	off
'Tool 5	off	off	on	off
'Tool 6	off	off	on	on
'Tool 7	off	off	off   on
'Tool 8	on	off	off	on
