! script name: tsm.d/globalexecute
! Version_270423.a

!A
!A NAME:
!A
!A      GENERIC EXECUTE
!A
!A DESCRIPTION:
!A
!A      This is a CUSTOM script that will create Automated Manufacturing
!A      Output (AMO) for a specific post processor.  The script is specific
!A      to one post processor.  A command_file is automatically created for
!A      this post and then executed.  The command_file can be
!A      edited and, rerun using TurboPost. NOTE: DO NOT rerun the command_file
!A      using AMO.  The changes that were made will be overwritten.
!A
!B INSTRUCTIONS:
!B
!B      The areas in here are broken into SUBroutines.  There are three
!B      main areas that are the most customizable.
!B
!B              1) SUB Toolch - This is where the output for a tool change is created. The startup is also output in this section.
!B              2) SUB Drilling - This area is designed to output a certain canned_cycle for a certain tool type (i.e. REAMER)
!B              3) SUB Milling - This area outputs milling data. It will split associated data into: Round Milling, Plunging, Surfaces, Path Groups and, Contours.
!B              4) SUB Threading - This area is designed to output a call to helical_mill_cut, the threading cycle in Tpost.
!B
!B      There are comments throughout the script to better explain
!B      specific areas.
!B
!# see also - amo.d/execute.hlp

stat=ChangeLabelStr("ScriptNameStatus","Function: execute amo ")

DIM Dir$[1024]
DIM Data_name$[1024],Post_name$[1024]
DIM Event_name$[256],Event_type$[256],Event_data$[1024],Event_ques$[256]
DIM Data_type$[256],Last_tool$[256]
DIM Tasks_file$[256],Endmill_order$[256],Date_form$[256]

DeActivateUndo

PlotOff
! POST NAME: DO NOT change /weber to be /usr/weber. Change only the name
! AMO to be <post processor>.

Dir$=NamedVariableStr("post dir",WsSystemVars,"/usr/weber/post_formats/")
IF ARGC<2 THEN
        CALL GetPostName(Dir$,"",Post_name$)
ELSE
        CALL GetPostName(Dir$,ARGV(1),Post_name$)
END IF

! SWITCHES: These are convenience switches. This will aide in the customization

Amo_vdata= ReadUserData(WsMiscData,"AMO_VARS",FileNameString(Post_name$,"amofiles/amo_variables"))
Opt_vdata= ReadUserData(WsMiscData,"AMO_OPT_VARS",FileNameString(Post_name$,"amofiles/optimize_vars"))
G1= FindNamedGrp("TEMP AMO VARS")
IF ValidGeometry(G1) THEN Stat= DeleteGroup(G1,2,WsTrue)

IF ValidGeometry(Amo_vdata) THEN
        Use_tdata= GetUserValue(Amo_vdata,"Use tdata:")
        Do_nxt= GetUserValue(Amo_vdata,"Use next tool:")
        One_zone= GetUserValue(Amo_vdata,"One zone:")
        Get_first= GetUserValue(Amo_vdata,"Get first:")
        Last_num= GetUserValue(Amo_vdata,"Last number:")
        Exec_amo= GetUserValue(Amo_vdata,"Execute amo:")
        Debug_amo= GetUserValue(Amo_vdata,"Debug amo:")
        Out_zones= GetUserValue(Amo_vdata,"Output zones:")
        Tasks_file$= UserDataStr(Amo_vdata,"Tasks sort file:")
        IF NOT LEN(Tasks_file$) THEN Tasks_file$="autotasks"
        Endmill_order$= UserDataStr(Amo_vdata,"Endmill ordering:")
        IF NOT LEN(Endmill_order$) THEN Endmill_order$="PLUNGE;SURFACE;PATHS;ROUND"
        Date_form$= UserDataStr(Amo_vdata,"Date string:")
        IF NOT LEN(Date_form$) THEN Date_form$="MM/dd/yyyy"
        Stat= DeleteEntity(Amo_vdata)
ELSE
        Use_tdata= 1
        Do_nxt= 0
        One_zone= 1
        Get_first= 1
        Last_num= 0
        Exec_amo= 1
        Debug_amo= 0
        Out_zone= 0
        Tasks_file$="autotasks"
        Endmill_order$= "PLUNGE;SURFACE;PATHS;ROUND"
        Date_form$="MM/dd/yyyy"
END IF

IF ValidGeometry(Opt_vdata) THEN
        Opt_type= GetUserValue(Opt_vdata,"Optimize type:")
        Lp_type= GetUserValue(Opt_vdata,"Last point type:")
        Opt_tol= GetUserValue(Opt_vdata,"Tolerance:")
        Opt_zigzag= GetUserValue(Opt_vdata,"Zigzag:")
        Opt_x= GetUserValue(Opt_vdata,"Optimize x:")
        Opt_y= GetUserValue(Opt_vdata,"Optimize y:")
        Opt_z= GetUserValue(Opt_vdata,"Optimize z:")
        Opt_ang= GetUserValue(Opt_vdata,"Angle:")
        Opt_row_dir= GetUserValue(Opt_vdata,"Row direction:")
        Opt_hole_dir= GetUserValue(Opt_vdata,"Hole direction:")
        Stat= DeleteEntity(Opt_vdata)
ELSE
        Opt_type= 1
        Lp_type= 1
        Opt_tol= .0001
        Opt_zigzag= 1
        Opt_x= 0.0
        Opt_y= 0.0
        Opt_z= 0.0
        Opt_ang= 90
        Opt_row_dir= WsForward
        Opt_hole_dir= WsReverse
END IF

! DEFAULT SECTION: Defaults.

! Initialize variables to be used in subroutines (Do NOT Touch)
CALL Set_tmp_var("amo startup",1,"")
CALL Set_tmp_var("use tool data",Use_tdata,"")
CALL Set_tmp_var("output next tool",Do_nxt,"")
CALL Set_tmp_var("one work zone",One_zone,"")
CALL Set_tmp_var("get first tool",Get_first,"")
CALL Set_tmp_var("last next tool",Last_num,"")
CALL Set_tmp_var("debug amo",Debug_amo,"")
CALL Set_tmp_var("output zone data",Out_zones,"")
CALL Set_tmp_var("current tool",0,"")
CALL Set_tmp_var("tasks file",0,Tasks_file$)
CALL Set_tmp_var("endmill order",0,Endmill_order$)
CALL Set_tmp_var("date format",0,Date_form$)

Global_opt_type= NamedVarVal("Optimize amo",WsSystemVars,WsTrue)
IF NOT Global_opt_type THEN
        CALL Set_tmp_var("amo opt type",0,"")
ELSE
        CALL Set_tmp_var("amo opt type",Opt_type,"")
END IF
CALL Set_tmp_var("last point type",Lp_type,"")
CALL Set_tmp_var("amo opt tol",Opt_tol,"")
CALL Set_tmp_var("zigzag optimize",Opt_zigzag,"")
CALL Set_tmp_var("optimize x",Opt_x,"")
CALL Set_tmp_var("optimize y",Opt_y,"")
CALL Set_tmp_var("optimize z",Opt_z,"")
CALL Set_tmp_var("amo opt angle",Opt_ang,"")
CALL Set_tmp_var("amo opt rdir",Opt_row_dir,"")
CALL Set_tmp_var("amo opt hdir",Opt_hole_dir,"")

CALL Set_tmp_var("current loop work zone",0,"")

Dtable= FindNamedEntity("Amo process table")
IF NOT ValidGeometry(Dtable) THEN
        CALL Check_zone_table
        Dtable= FindNamedEntity("Amo process table")
END IF

! RECORD POST NAME: This is where the name of the post_processor is 
! recorded. Nothing in this section is to be changed.

Found= RecordPostName(Post_name$,CurrentUnits)
IF NOT Found THEN Leave
Stat= RemoveDirFiles("./","*","command_file")
Stat= RemoveDirFiles("./","*","notepad")
Stat= RemoveFile("command_buffer")
First= InitCmdMenu(1,0)

AmoGroups= AmoTasksTableGrps(Dtable)
IF NOT ValidGeometry(AmoGroups) THEN Leave
Num_rows= NumberTableRows(Dtable)
CALL FindTDataCols(Dtable,Tcol,Fcol,Scol)

Stat=RemoveDupTools
Next_grp= 0
Wzoner= -9999
Last_tool= -9999
FOR K= 2 TO Num_rows
        CALL Set_tmp_var("current tool",K,"")
        EntData= AmoTaskTableTool(Dtable,K)
        IF ValidGeometry(EntData) THEN
                Stat= GetUserDataName(EntData,Data_name$)
                Data_type$= UserDataStr(EntData,"Tool type:")
                Next_grp= Next_grp+1
                Group= GroupElement(AmoGroups,Next_grp)
                IF NOT ValidGeometry(Group) THEN Next_k

                S_up= NamedVarVal("amo startup",WsAmoVars,(Next_grp=1))
                Tool_num= GetTableValue(Dtable,K,Tcol)
                Wzone= AmoTaskTableZone(Dtable,K)

                CALL Set_tmp_var("current loop work zone",Wzone,"")
Stat=OutputCmdBuff("START OPERATION: #"&VAL$(K-1),0)

                IF Last_tool<>Tool_num OR S_up THEN
Tool_ch:                CALL Toolch(EntData)
                        Last_tool= Tool_num
                        Tl_ch= 1
                ELSE
                        M= POS(Data_name$,"--")
                        IF M THEN
                                IF Last_tool$= Data_name$[1,M-1] THEN
                                        CALL Output_feed_speed(EntData,Dtable,K)
                                        Tl_ch= 0
                                ELSE
                                        GOTO Tool_ch
                                END IF
                        ELSE
                                IF Last_tool$= Data_name$ THEN
                                        CALL Output_feed_speed(EntData,Dtable,K)
                                        Tl_ch= 0
                                ELSE
                                        GOTO Tool_ch
                                END IF
                        END IF
                END IF

                IF Wzone THEN
                        IF (Wzoner<>Wzone) OR NOT One_zone OR (One_zone AND Tl_ch) THEN
                                CALL Do_newzero(Wzone,0)
                        END IF
                        Wzoner= Wzone
                END IF
                CALL Do_cycle(EntData,Group)
                IF POS(Data_name$,"--") THEN
                        Last_tool$= Data_name$[1,POS(Data_name$,"--")-1]
                ELSE
                        Last_tool$= Data_name$
                END IF
        ELSE
                S_up= NamedVarVal("amo startup",WsAmoVars,1)
                EntData= AmoTaskTableEvent(Dtable,K)
                IF NOT ValidGeometry(EntData) THEN Next_k
                Event_name$= UserDataStr(EntData,"Event name:")
                Event_ques$= UserDataStr(EntData,"Event ques:")
                IF LEN(Event_ques$) THEN
                        CALL AskQuestion(Event_ques$,Event_name$,Event_name$,Event_name$)
                END IF
                Event_type$= UserDataStr(EntData,"Event type:")
                Event_data$= UserDataStr(EntData,"Event data:")
                IF LEN(Event_type$) AND LEN(Event_data$) THEN
                        Stat= OutputCmdBuff(Event_type$&": "&Event_data$,S_up)
                END IF
                IF S_up THEN UpdateCmdFile
        END IF
Next_k:NEXT K

End_codes:!
CALL AskQuestion("end_ques","End of file ques","NONE","NONE")
Stat=OutputCmdBuff("MACRO: end_codes",0)
CALL AskQuestion("anlze_ques","Cost ques","NONE","NONE")
Stat=OutputCmdBuff("MACRO: anlze_cost",0)
UpdateCmdFile
Did_table= NamedVarVal("did table",WsAmoVars,0)
IF Did_table THEN
        IF ValidGeometry(Dtable) THEN Stat= DeleteEntity(Dtable)
ELSE
        Basecol=StringSearchRow(Dtable,"AMO Basename",1,0,0,1)
        Stat= DeleteTableColumn(Dtable,Basecol)
END IF
Tasks= FindNamedGrp("AMO OPERATIONS")
Did_sort= NamedVarVal("did sort",WsAmoVars,0)
IF ValidGeometry(Tasks) AND Did_sort THEN Stat= DeleteEntity(Tasks,WsFalse,2)

PlotOn
Start_work= CurrentWorkplane
StdWorkplane

Exec_amo= NamedVarVal("Execute amo",WsAmoVars,Exec_amo)
IF Exec_amo THEN
        Command_type=InterpretCmd("EXEC: ")   ! EXECUTE Command File
END IF
Stat=ListTapeFile("tapefile","tapelist",1) ! Make tapelist file

Command_type=InterpretCmd("EXIT: ")        ! EXIT Post
Stat=RemoveDupTools
IF ValidGeometry(Start_work) THEN Stat=SetWorkplane(Start_work)

Leave:!
PlotOn
CALL CheckExit(1)
END

SUB CheckExit(Do_leave)
DIM Dest$[256]

IF NOT (Do_leave OR ExitScript(Dest$)) THEN SUBEXIT

Did_sort= NamedVarVal("did sort",WsAmoVars,0)
Did_table= NamedVarVal("did table",WsAmoVars,0)
IF Did_table THEN
        Dtable= FindNamedEntity("Amo process table")
        Stat= DeleteEntity(Dtable)
END IF
IF Did_sort THEN
        Tasks= FindNamedGrp("AMO OPERATIONS")
        Stat= DeleteEntity(Tasks,0,2)
END IF
Stat= DeleteGroup("TEMP AMO VARS",2)
Stat= DeleteEntity("LAST AMO POINT")

IF LEN(Dest$) THEN LOAD Dest$
LOAD "typecontrol"
SUBEND

SUB Do_newzero(Wzone,On_tool)
! This calculates the rotary movement and new workplane position
! The line rotary_zero can be change to reflect a differnet work zone
! change MACRO.

DIM Fixture$[256],Hnum$[32]

        Hle= FindZoneOrigin(WsWorkZoneOrigin,Wzone)
        Zent= GetAssocEnt(Hle,WsWorkZoneOrigin)

        IF NOT On_tool THEN
! IF Fixture is a string
           IF CheckUserField(Zent,"Fixture number:",1) THEN
                Fixture= GetUserValue(Zent,"Fixture number:")
                Stat=OutputCmdBuff("ASSIGN: Fixture= "&VAL$(Fixture)&";",0)
           ELSE
                Fixture$= UserDataStr(Zent,"Fixture number:")
                Stat=OutputCmdBuff("ASSIGN: Fixstr= """&Fixture$&""";",0)
           END IF
        END IF

        IF On_tool=2 THEN
                Pt= ParameterPt(Hle,0)
                X= XPointValue(Pt)
                Y= YPointValue(Pt)
                Z= ZPointValue(Pt)
                Stat= DeleteEntity(Pt)
                Stat=OutputCmdBuff("ASSIGN: Xreal= "&VAL$(X)&"; Yreal= "&VAL$(Y)&"; Zreal= "&VAL$(Z)&";",0)
        END IF
        Hnum$= VAL$(HoleNumber(Hle))
        Stat=OutputCmdBuff("ASSIGN: Zone_num= "&VAL$(Wzone)&"; Start_hole= "&Hnum$&"; Holestartpt",0)
        IF NOT On_tool THEN
          CALL AskQuestion("rotary_ques","Rotary ques",VAL$(Wzone),"WZ= "&VAL$(Wzone))
          Stat=OutputCmdBuff("MACRO: rotary_zero",0)
        END IF
SUBEND

SUB Do_cycle(EntData,Group)
DIM Data_type$[256]
        Data_type$= UserDataStr(EntData,"Tool type:")
        SELECT Data_type$    ! Determines tool cycle based upon the tool type.
        CASE "ENDMILL","TAPERMILL","BULLMILL","BALLMILL","CHAMFERMILL"
                CALL Milling(EntData,Group)
        CASE "CENTER DRILL","TWIST DRILL","COUNTERBORE","COUNTER SINK","REAMER","TAP","BORING BAR","PORT CUTTER"
                CALL Drilling(EntData,Group)
        CASE "THREADER"
                CALL Threading(EntData,Group)
        CASE ELSE
                SUBEXIT
        END SELECT
SUBEND

SUB Toolch(EntData)
DIM Data_id$[128],Tool_name$[256],Date_str$[256]
DIM Header$[32000],Prog_desc$[256],Date_form$[256]
INTEGER Zone_data(50)

S_up= NamedVarVal("amo startup",WsAmoVars,1)
Do_nxt= NamedVarVal("output next tool",WsAmoVars,0)
Curr_tl= NamedVarVal("current tool",WsAmoVars,0)
Wzone= NamedVarVal("current loop work zone",WsAmoVars,0)
Out_zones= NamedVarVal("output zone data",WsAmoVars,0)

Dtable= FindNamedEntity("Amo process table")
IF NOT ValidGeometry(Dtable) THEN CALL CheckExit(1)

CALL FindTDataCols(Dtable,Tcol,Fcol,Scol)
Num_rows= NumberTableRows(Dtable)

Data_id$= ToolIdName(EntData)
Stat= GetUserDataName(EntData,Tool_name$)

! ** First line of command buffer.  Needs to be set to zero after
! ** first time used. Defaults to S_up.  But 0 should replace S_up if
! ** OutputCmdBuff is used in main prog.
! **
Prog_desc$= ""
Stat= CurrentHeader(Header$)
IF LEN(Header$) THEN
        Head=ReadUserData(WsGeneralString,"HEADER",Header$)
        IF ValidGeometry(Head) THEN
                Stat=GetUserString(Head,"Description:",Prog_desc$)
                Stat=DeleteEntity(Head)
        END IF
END IF

IF S_up THEN
        Stat= NamedVarStr("date format",WsAmoVars,"MM/dd/yyyy",Date_form$)
        Stat= DateString(Date_form$,Date_str$)
        Stat=OutputCmdBuff("ASSIGN: Date_str= """&Date_str$&""";",S_up)
        IF LEN(Prog_desc$) THEN Stat=OutputCmdBuff("ASSIGN: Prog_desc= """&Prog_desc$&""";",0)
        Debug_amo= NamedVarVal("Debug amo",WsAmoVars,0)
        IF Debug_amo THEN Stat=OutputCmdBuff("ASSIGN: Debug_turbo= "&VAL$(Debug_amo)&";",0)
        Stat=OutputCmdBuff("START OPERATION: #1",0)
END IF
Stat=OutputCmdBuff("ASSIGN: Tool_desc= """&Data_id$&""";",0)
Stat=OutputCmdBuff("ASSIGN: Syn_tool_desc= """&Tool_name$&""";",0)

CALL Set_tool_point(S_up)
Tnum= GetTableValue(Dtable,Curr_tl,Tcol)

Tnum_data= FindUserData("AMO TOOL NUMBERS",WsGeneralString)
IF S_up THEN Stat= DeleteEntity(Tnum_data)
IF NOT ValidGeometry(Tnum_data) THEN
        Tnum_data= CreateUserData(WsGeneralString,"AMO TOOL NUMBERS",CHR$(10))
        Tools_in= 1
ELSE
        Tools_in= GetUserValue(Tnum_data,"Number tools:")+1
END IF
Stat= PutUserString(Tnum_data,"Tool name "&VAL$(Tools_in)&":",Data_id$)
Stat= PutUserValue(Tnum_data,"Tool num "&VAL$(Tools_in)&":",Tnum)
Stat= PutUserValue(Tnum_data,"Number tools:",Tools_in)

Stat=OutputCmdBuff("ASSIGN: Tool_num= "&VAL$(Tnum)&";",0)
IF Do_nxt THEN
        Get_first= NamedVarVal("get first tool",WsAmoVars,0)
        Last_num= NamedVarVal("last next tool",WsAmoVars,0)
        FOR J= Curr_tl+1 TO Num_rows
                Nxtnum= GetTableValue(Dtable,J,Tcol)
                IF Nxtnum AND Nxtnum<>Tnum THEN Done_j
        NEXT J
        Need_first=1
        FOR J= 2 TO Curr_tl
                Nxtnum= GetTableValue(Dtable,J,Tcol)
                IF Nxtnum AND Nxtnum<>Tnum THEN Done_j
        NEXT J

Done_j:!
        IF NOT Get_first AND Need_first THEN
                Nxtnum= Last_num
        END IF
Nxt_tl: Stat=OutputCmdBuff("ASSIGN: Next_tool= "&VAL$(Nxtnum)&";",0)
END IF

CALL Output_feed_speed(EntData,Dtable,Curr_tl)

IF Out_zones THEN
        FOR M= 1 TO 50
                Zone_data(M)= 0
        NEXT M
        Zone_count= 0
        Num_rows= NumberTableRows(Dtable)
        FOR M= 2 TO Num_rows
                Zone_val= AmoTaskTableZone(Dtable,M)
                IF Zone_val THEN
                        FOR L= 1 TO Zone_count+1
                                IF Zone_data(L)= 0 THEN
                                        Zone_data(L)= Zone_val
                                        Zone_count= Zone_count+1
                                ELSE
                                        IF Zone_data(L)= Zone_val THEN Next_m
                                        IF Out_zones=2 AND Zone_data(L)>Zone_val THEN
                                                FOR K= Zone_count+1 TO L+1 STEP -1
                                                        Zone_data(K)= Zone_data(K-1)
                                                NEXT K
                                                Zone_data(L)= Zone_val
                                                Zone_count= Zone_count+1
                                                GOTO Next_m
                                        END IF
                                END IF
                        NEXT L
                END IF
Next_m: NEXT M
END IF

IF S_up THEN
        CALL Set_tmp_var("amo startup",0,"")
        CALL AskQuestion("startup_ques","Startup ques","NONE","NONE")
        CALL AskQuestion("tool_ques","Tool change ques",Tool_name$,Tool_name$)
        IF NOT Out_zones THEN
                IF Wzone THEN CALL Do_newzero(Wzone,1)
                Stat= OutputCmdBuff("MACRO: s_up",0)
        ELSE
                IF Wzone THEN CALL Do_newzero(Wzone,1)
                Stat= OutputCmdBuff("MACRO: startup1",0)
                FOR M= 1 TO Zone_count
                        Zone_val= Zone_data(M)
                        CALL AskQuestion("zone_data_ques","Zone data ques","WZ= "&VAL$(Zone_val),"WZ= "&VAL$(Zone_val))
                        CALL Do_newzero(Zone_val,2)
                        Stat= OutputCmdBuff("MACRO: zone_info",0)
                NEXT M
                IF Wzone THEN CALL Do_newzero(Wzone,1)
                Stat= OutputCmdBuff("MACRO: startup2",0)
        END IF
ELSE
        CALL AskQuestion("tool_ques","Tool change ques",Tool_name$,Tool_name$)
        IF Wzone THEN CALL Do_newzero(Wzone,1)
        Stat= OutputCmdBuff("MACRO: tool_change",0)     
END IF
SUBEND

SUB Output_feed_speed(EntData,Dtable,Curr_tl)
DIM Data_type$[256]

CALL FindTDataCols(Dtable,Tcol,Fcol,Scol)

Feed= GetTableValue(Dtable,Curr_tl,Fcol)
Speed= GetTableValue(Dtable,Curr_tl,Scol)
Data_type$= UserDataStr(EntData,"Tool type:")
SELECT Data_type$
CASE "ENDMILL","TAPERMILL","BULLMILL","BALLMILL","CHAMFERMILL"
        Stat=OutputCmdBuff("ASSIGN: Tfeed= "&VAL$(Feed)&"; Speed= "&VAL$(Speed)&";",0)
        Material= FindUserData("MATERIAL",WsMaterial)
        Zfeed= GetFeedrate(EntData,Material,"Zfeed")
        IF NOT Zfeed THEN Zfeed= Feed
        Stat=OutputCmdBuff("ASSIGN: Zfeed= "&VAL$(Zfeed)&";",0)
CASE ELSE
        Stat=OutputCmdBuff("ASSIGN: Zfeed= "&VAL$(Feed)&"; Speed= "&VAL$(Speed)&";",0)
END SELECT
SUBEND

SUB Milling(EntData,Group)
DIM Dname$[128],Name$[128],Mill_dir$[32],Plungename$[256],Data_name$[256]
DIM Diacomp$[64]
DIM Ques_str$[256]
DIM Endmill_order$[256],Answer$[256]
ENTITY PlungeGrp

Wzone= NamedVarVal("current loop work zone",WsAmoVars,0)
IF Wzone THEN
        Ques_str$= JoinStrings("WZ=",VAL$(Wzone)," ",ToolIdName(EntData))
ELSE
        Ques_str$= ToolIdName(EntData)
END IF

Comp_dir= 0

! This is the section that describes what to do with endmills.
! The Group of geometry is divided into individual groups and then
! the different types of functions can be ordered. NOTE: DO NOT
! reorder the group creation. Only reorder the milling functions.

Stat= GroupName(Group,Data_name$)

Rm_mach=1
HoleGrp=GrpByEntType(Group,WsHoleEnt)
IF ValidGeometry(HoleGrp) THEN
        MachGrp=SubtractGrps(Group,HoleGrp)
        First=1
        FOR Hole_ent=1 TO GroupCount(HoleGrp)
                E1=GroupElement(HoleGrp,Hole_ent)
                Hdia=EntityValue(E1,WsHoleDia)
                IF Hdia<=ToolDiameter(EntData) THEN
                        IF First THEN
                                Plungename$= Data_name$&" -- Plunge"
                                PlungeGrp= FindNamedGrp(Plungename$)
                                IF ValidGeometry(PlungeGrp) THEN
                                        Stat= DeleteEntity(PlungeGrp)
                                END IF
                                PlungeGrp=CreateGroup(Plungename$)
                                First=0
                        END IF
                        Stat=AddToGroup(PlungeGrp,E1)
                END IF
        NEXT Hole_ent
        IF ValidGeometry(PlungeGrp) THEN
                TmpGrp=SubtractGrps(HoleGrp,PlungeGrp)
                Stat= DeleteEntity(HoleGrp)
                IF ValidGeometry(TmpGrp) THEN
                        IF GroupCount(TmpGrp) THEN HoleGrp= TmpGrp
                END IF
        END IF
ELSE
        Rm_mach=0
        MachGrp= Group
END IF

Rm_geom=1
IF NOT ValidGeometry(MachGrp) THEN Do_passes
CpathsGrp= GrpByEntType(MachGrp,WsCPathFileEnt)
IF ValidGeometry(CpathsGrp) THEN
        GeomGrp= SubtractGrps(MachGrp,CpathsGrp)
ELSE
        Rm_geom=0
        GeomGrp= MachGrp
END IF
IF NOT ValidGeometry(GeomGrp) THEN Do_passes

Grp_grps= HighestParentGroup(GeomGrp)
Geo_pos= ElementGrpNum(Grp_grps,GeomGrp)
IF Geo_pos THEN Stat= RemoveFromGrp(Grp_grps,GeomGrp) 
IF Rm_geom THEN Stat=DeleteEntity(GeomGrp)


Do_passes:! ************ BEGIN Individual milling functions ****************
! Reorder these GOSUB's in the order they should be performed
! in case a single tool is performing multiple milling functions.
! to get rid of a cycle the GOSUB can be commented out.

Stat= NamedVarStr("endmill order",WsAmoVars,"PLUNGE;SURFACE;PATHS;ROUND",Endmill_order$)
FOR Which_e= 1 TO 4
Stat= StringFieldStr(Endmill_order$,";",Which_e,Answer$)
SELECT Answer$
CASE "PLUNGE"
GOSUB Plunge_holes
CASE "SURFACE"
GOSUB Cut_surfaces
CASE "PATHS"
GOSUB Cut_paths
CASE "ROUND"
GOSUB Round_cut
END SELECT
NEXT Which_e
! ************************* END Individual milling functions *****************

End_mill:! Do not touch this section of Deletes
IF Rm_mach THEN
IF ValidGeometry(MachGrp) THEN Stat= DeleteEntity(MachGrp)
IF ValidGeometry(GeomGrp) THEN Stat= DeleteEntity(GeomGrp)
ELSE
IF Rm_geom AND ValidGeometry(GeomGrp) THEN Stat= DeleteEntity(GeomGrp)
END IF
IF ValidGeometry(HoleGrp) THEN Stat= DeleteEntity(HoleGrp)
IF ValidGeometry(Grp_grps) THEN Stat= DeleteEntity(Grp_grps)
SUBEXIT

Plunge_holes:! ************ BEGIN Plunging function ************************
IF ValidGeometry(PlungeGrp) THEN CALL Drilling(EntData,PlungeGrp)
RETURN
! ************************** END Plunging function *************************

Cut_surfaces:! ************ BEGIN Surface function *************************
IF ValidGeometry(CpathsGrp) THEN
        CALL AskQuestion("surface_ques","Surface ques",Data_name$,Ques_str$)
        Num_cpaths= GroupCount(CpathsGrp)
        FOR I= 1 TO Num_cpaths
                E1= GroupElement(CpathsGrp,I)
                Stat=CPathFileName(E1,Name$)
                Cpath3d=GetAssocEnt(E1,Ws3dCpath)
                Stat=OutputCmdBuff("ASSIGN: Cutter_file= """&Name$&""";",0)
                CALL AskQuestion("cpath_ques","Cutter path ques",Data_name$&" FOR "&Name$,Data_name$&" FOR "&Name$,Name$)
                IF ValidGeometry(Cpath3d) THEN
                        IF GetUserValue(Cpath3d,"ZIGZAGS:") THEN
                                CALL AskQuestion("zigzag_ques","Zigzag ques",Data_name$&" FOR "&Name$,Data_name$&" FOR "&Name$,Name$)
                                Stat=OutputCmdBuff("MACRO: cut_zigzag",0)
                        ELSE
                                CALL AskQuestion("cut_surf_ques","Cut surface ques",Data_name$&" FOR "&Name$,Data_name$&" FOR "&Name$,Name$)
                                Stat=OutputCmdBuff("MACRO: cut_surface",0)
                        END IF
                ELSE
                        CALL AskQuestion("zigzag_ques","Zigzag ques",Data_name$&" FOR "&Name$,Data_name$&" FOR "&Name$,Name$)
                        Stat=OutputCmdBuff("MACRO: cut_zigzag",0)
                END IF
        NEXT I
        Stat= DeleteEntity(CpathsGrp)
END IF
RETURN
! *************************** END Surface function **************************

Cut_paths:! ******* BEGIN Cut_paths section *************
FOR F= 1 TO GroupCount(Grp_grps)
        E1= GroupElement(Grp_grps,F)
        Stat=GroupName(E1,Dname$)
        CALL AskQuestion("contour_ques","Contour ques",Data_name$,Ques_str$)
        SELECT GroupType(E1)
        CASE WsContourGroup,WsPocketPath,WsZigZagPath,WsOffsetPath
                GOSUB Cut_contours
        CASE WsPathGroup,WsGroupOfGroups,33
                GOSUB Cut_pathgroups
        CASE WsGrpOfPathGrps,27
                GOSUB Cut_grp_pathgroups
        CASE ELSE
                GOSUB Cut_contours
        END SELECT
NEXT F
RETURN
! *************************** END Cut_paths function **************************

Cut_grp_pathgroups:! ******* BEGIN Cut_grp_pathgroups section *************
Num1= GroupCount(E1)
FOR R= 1 To Num1
        Epg1= GroupElement(E1,R)
        FOR T= 1 To GroupCount(Epg1)
                Epg2= GroupElement(Epg1,T)
                IF ValidGeometry(Epg2) THEN CALL OutputOperatorInfo(Epg2)
        NEXT T
NEXT R
Last_grp= GroupElement(E1,Num1)
Num2= GroupCount(Last_grp)
Last_path= GroupElement(Last_grp,Num2)
CALL Output_comp(Last_path,Comp_dir)
Stat= GroupName(E1,Dname$)
Stat= OutputCmdBuff("ASSIGN: Group_name= """&Dname$&""";",0)
Stat= OutputCmdBuff("MACRO: mcut_multi_levels",0)

Last_point= ContEndPt(Last_path)
CALL Set_last_point(Last_point,0)
RETURN
! *********************** END Cut_grp_pathgroups section ***********************

Cut_pathgroups:! ******* BEGIN Cut_pathgroups section **********************
Num1= GroupCount(E1)
FOR R= 1 TO Num1
        Epg1= GroupElement(E1,R)
        IF ValidGeometry(Epg1) THEN CALL OutputOperatorInfo(Epg1)
NEXT R
Last_path= GroupElement(E1,Num1)
CALL Output_comp(Last_path,Comp_dir)
Stat= GroupName(E1,Dname$)
Stat= OutputCmdBuff("ASSIGN: Group_name= """&Dname$&""";",0)
Stat= OutputCmdBuff("MACRO: mcut_path_grp",0)
Last_point= ContEndPt(Last_path)
CALL Set_last_point(Last_point,0)
RETURN
! *********************** END Cut_pathgroups section ***********************

Cut_contours:! ********** BEGIN Cut_contours section ***********************
! This section will describe how to cut a single contour

! If the path is a POCKET OR AN OFFSET then find climb or conventional milling
! to set the comp_dir variable. If the path is NOT DEFINED AS A POCKET OR AN 
! OFFSET then call a routine for no_comp. The sections for comp_path and 
! No_comp_path are at the end of this SUB.

Stat= GroupName(E1,Name$)
OutputOperatorInfo(E1)
CALL Output_comp(E1,Comp_dir)

Stat= OutputCmdBuff("ASSIGN: Path_name= """&Name$&""";",0)
Stat= OutputCmdBuff("MACRO: contour_cut",0)
Last_point= ContEndPt(E1)
CALL Set_last_point(Last_point,0)
RETURN

! ************************** END Cut_contours section ************************

Round_cut:! **************** BEGIN Round_cut section ************************
IF NOT ValidGeometry(HoleGrp) THEN RETURN
OptimizeHoles(HoleGrp)

CALL AskQuestion("round_cycle_ques","Round cycle ques",Group_name$,Ques_str$)
CALL Round_thrd_holes(HoleGrp,"round_cut",1)
Last_point= ParameterPt(E1,0)
CALL Set_last_point(Last_point,0)
RETURN
! *************************** END Round_cut section *************************
SUBEND

SUB Drilling(EntData,Group)
DIM Data_name$[128],Dtype$[128],Data_type$[256]
DIM Ques_str$[256]

! This is the area for the Canned Cycles.

Wzone= NamedVarVal("current loop work zone",WsAmoVars,0)
IF Wzone THEN
        Ques_str$= JoinStrings("WZ=",VAL$(Wzone)," ",ToolIdName(EntData))
ELSE
        Ques_str$= ToolIdName(EntData)
END IF

CALL OptimizeHoles(Group)
Stat= GroupName(Group,Data_name$)
CALL OutputOperatorInfo(Group)

Data_type$= UserDataStr(EntData,"Tool type:")
IF CheckUserField(EntData,"Tool subtype:",1) THEN
        Stat= GetUserString(EntData,"Tool subtype:",Dtype$)
        Stat= OutputCmdBuff("ASSIGN: Tool_subtype= """&Dtype$&""";",0)
ELSE
        IF CheckUserField(EntData,"Drill type:",1) THEN
                Stat= GetUserString(EntData,"Drill type:",Dtype$)
                Stat= OutputCmdBuff("ASSIGN: Tool_subtype= """&Dtype$&""";",0)
        END IF
END IF

Stat= OutputCmdBuff("ASSIGN: Group_name= """&Data_name$&""";",0)
CALL AskQuestion("hole_ques","Hole ques",Data_name$,Ques_str$)
SELECT Data_type$
CASE "CENTER DRILL"
CALL AskQuestion("cdrill_ques","Cdrill ques",Data_name$,Ques_str$)
CASE "TWIST DRILL"
CALL AskQuestion("drill_ques","Drill ques",Data_name$,Ques_str$)
CASE "COUNTERBORE"
CALL AskQuestion("cbore_ques","Cbore ques",Data_name$,Ques_str$)
CASE "COUNTER SINK"
CALL AskQuestion("csink_ques","Csink ques",Data_name$,Ques_str$)
CASE "REAMER"
CALL AskQuestion("reamer_ques","Reamer ques",Data_name$,Ques_str$)
CASE "BORING BAR"
CALL AskQuestion("bore_ques","Bore ques",Data_name$,Ques_str$)
CASE "PORT CUTTER"
CALL AskQuestion("portcutter_ques","Port cutter ques",Data_name$,Ques_str$)
CASE "TAP"
        IF CurrentUnits= WsMetric THEN
                Tap_lead= GetUserValue(EntData,"Pitch:")
        ELSE
                Tpi= GetUserValue(EntData,"Threads-inch:")
                IF NOT Tpi THEN
                        Tap_lead= 0
                ELSE
                        Tap_lead= 1/Tpi
                END IF
        END IF
        Stat= OutputCmdBuff("ASSIGN: Pitch= "&VAL$(Tap_lead)&";",0)
        CALL AskQuestion("tap_ques","Tap ques",Data_name$,Ques_str$)
END SELECT
Stat= OutputCmdBuff("MACRO: hole_cycle",0)
Number= GroupCount(Group)
E1= GroupElement(Group,Number)
Last_point= ParameterPt(E1,0)
CALL Set_last_point(Last_point,0)
SUBEND

SUB Threading(EntData,Group)
DIM Data_name$[256],Dtype$[128],Name$[256]
DIM Holes_name$[256],Paths_name$[256]
DIM Ques_str$[256]
Quote$= CHR$(34)

Comp_dir= 0
Stat= GroupName(Group,Data_name$)
Holes_name$= Data_name$&" thread holes"
Paths_name$= Data_name$&" threads"
Oldgroup=FindNamedGrp(Holes_name$)
Stat= DeleteEntity(Oldgroup)
Oldgroup=FindNamedGrp(Paths_name$)
Stat= DeleteEntity(Oldgroup)

HoleGrp=GrpByEntType(Group,WsHoleEnt)
IF ValidGeometry(HoleGrp) THEN
        MachGrp=SubtractGrps(Group,HoleGrp)

        OptimizeHoles(HoleGrp)
        Stat= ChangeGrpName(HoleGrp,Holes_name$)
        IF ValidGeometry(MachGrp) THEN
                Stat=ChangeGrpName(MachGrp,Paths_name$)
        END IF

        Wzone= NamedVarVal("current loop work zone",WsAmoVars,0)
        IF Wzone THEN
                Ques_str$= JoinStrings("WZ=",VAL$(Wzone)," ",ToolIdName(EntData))
        ELSE
                Ques_str$= ToolIdName(EntData)
        END IF
        CALL AskQuestion("thread_ques","Thread ques",Holes_name$,Ques_str$)

        Holes_name$= Quote$&Holes_name$&Quote$
        Stat= OutputCmdBuff("ASSIGN: Group_name= "&Holes_name$&";",0)
        Stat= OutputCmdBuff("ASSIGN: Groupon",0)

        IF CurrentUnits= WsMetric THEN
                Pitch=GetUserValue(EntData,"Pitch:")
                Tpi= 1/Pitch
                Stat= OutputCmdBuff("ASSIGN: Thread_type=2;",0)
        ELSE
                Tpi=GetUserValue(EntData,"Threads-inch:")
                Pitch= 1/Tpi
                Stat= OutputCmdBuff("ASSIGN: Thread_type=1;",0)
        END IF
        Stat= OutputCmdBuff("ASSIGN: Pitch= "&VAL$(Pitch)&"; Tpi= "&VAL$(Tpi)&";",0)
        Thread_len=GetUserValue(EntData,"Thread length:")
        Stat= OutputCmdBuff("ASSIGN: Thread_length= "&VAL$(Thread_len)&";",0)

        Num_threads= Thread_len/Pitch
        CALL Round_thrd_holes(HoleGrp,"threadmill",0)
        Stat= OutputCmdBuff("ASSIGN: Groupoff",0)
        Last_hole= GroupCount(HoleGrp)
        E1= GroupElement(HoleGrp,Last_hole)
        Last_point= ParameterPt(E1,0)
        CALL Set_last_point(Last_point,0)
        IF ValidGeometry(MachGrp) THEN Machine_thread
ELSE
        MachGrp= Group
Machine_thread:!
        IF NOT ValidGeometry(MachGrp) THEN SUBEXIT
        IF GroupCount(MachGrp)=0 THEN SUBEXIT
        PathsGrp= FindGrpsByEle(MachGrp,WsTempGroup)
        IF NOT ValidGeometry(PathsGrp) THEN SUBEXIT

Thread_paths:!
        IF ValidGeometry(PathsGrp) THEN
                Num_paths= GroupCount(PathsGrp)
                IF NOT Num_paths THEN RETURN
                        IF NOT Done_finish THEN
                        Stat= OutputCmdBuff("ASSIGN: Finish_depth= 0;",0)
                        Stat= OutputCmdBuff("ASSIGN: Depth_of_cut= Finish_depth;",0)
                        Done_finish= 1
                END IF
                FOR I= 1 TO Num_paths
                        E1= GroupElement(PathsGrp,I)
                        Stat= GroupName(E1,Name$)

                        CALL Output_comp(E1,Comp_dir)
                        Stat= OutputCmdBuff("ASSIGN: Path_name= """&Name$&""";",0)
                        Stat= OutputCmdBuff("MACRO: contour_cut",0)
                NEXT I
                Last_point= ContEndPt(E1)
                CALL Set_last_point(Last_point,0)
        END IF
END IF
SUBEND

SUB Output_comp(E1,Comp_dir)
DIM Mill_dir$[256]

Mill_dir$="NONE"
OffsetBdy= GetAssocEnt(E1,WsOffsetBdy)
IF NOT ValidGeometry(OffsetBdy) THEN
        OffsetBdy= GetAssocEnt(E1,WsPocketBdy)
        IF ValidGeometry(Offsetbdy) THEN
                IF (EntityType(Offsetbdy)<>WsDataStringEnt) THEN
                        Mill_dir$="Climb"
                ELSE
                Stat= GetUserString(OffsetBdy,"MILL DIRECTION:",Mill_dir$)
                END IF
        ELSE
                SELECT GetDCompDirection(E1)
                CASE WsLeft
                        Mill_dir$="Climb"
                CASE WsRight
                        Mill_dir$="Conventional"
                CASE ELSE
                        Mill_dir$="NONE"
                END SELECT
        END IF
ELSE
        IF (EntityType(Offsetbdy)<>WsDataStringEnt) THEN
                Mill_dir$="Climb"
        ELSE
                Stat= GetUserString(OffsetBdy,"MILL DIRECTION:",Mill_dir$)
        END IF
END IF

IF Mill_dir$="NONE" THEN
        Stat= OutputCmdBuff("ASSIGN: Dia_comp_mode= 0;",0)
ELSE
        IF UPC$(Mill_dir$)="CLIMB" OR UPC$(Mill_dir$)= "CL" THEN
                IF Comp_dir=41 THEN SUBEXIT
                Comp_dir=41
                Stat= OutputCmdBuff("ASSIGN: Dia_comp_mode= 1;",0)
                Stat= OutputCmdBuff("ASSIGN: Comp_dir= 41;",0)
        ELSE
                IF Comp_dir=42 THEN SUBEXIT
                Comp_dir=42
                Stat= OutputCmdBuff("ASSIGN: Dia_comp_mode= 1;",0)
                Stat= OutputCmdBuff("ASSIGN: Comp_dir= 42;",0)
        END IF
END IF
SUBEND

SUB OptimizeHoles(Group)
Opt_type= NamedVarVal("amo opt type",WsAmoVars,2)
Opt_factor= 10
IF Opt_type=2 OR Opt_type=3 THEN
        Opt_ang= NamedVarVal("amo opt angle",WsAmoVars,90)
        Opt_row_dir= NamedVarVal("amo opt rdir",WsAmoVars,WsForward)
        Opt_hole_dir= NamedVarVal("amo opt hdir",WsAmoVars,WsReverse)
        Opt_tol= NamedVarVal("amo opt tol",WsAmoVars,.0001)
        Opt_zigzag= NamedVarVal("zigzag optimize",WsAmoVars,WsTrue)
        Stat= ReOrderPtGrp(Group,Opt_ang,Opt_row_dir,Opt_hole_dir,Opt_tol,Opt_zigzag)
END IF
IF Opt_type=1 OR Opt_type=3 THEN
        Stat= OptimizePointPath(Group,"LAST AMO POINT",Opt_factor)
END IF
Stat= DeleteEntity("LAST AMO POINT")
SUBEND

SUB FindTDataCols(Dtable,Tnum_col,Feed_col,Speed_col)
DIM Feedstr$[256]

Tnum_col=StringSearchRow(Dtable,"Tool #",1,0,0,1)
IF CurrentUnits= WsMetric THEN
        Feedstr$= "Feed(mmpm)"
ELSE
        Feedstr$= "Feed(ipm)"
END IF
Feed_col=StringSearchRow(Dtable,Feedstr$,1,0,0,1)
Speed_col=StringSearchRow(Dtable,"Speed(rpm)",1,0,0,1)
SUBEND

SUB OutputOperatorInfo(Group)
DIM B$[32000]

! If an op_info packet is attached to a group, this code outputs the info
Pprint= GetAssocEnt(Group,500001)
IF ValidGeometry(Pprint) THEN
        GOSUB Output_op_info
        SUBEXIT
END IF

! If op_info packets are attached to elements in a group,
! this code finds all packets and outputs

Num_ele= GroupCount(Group)
FOR Next_ele= 1 TO Num_ele
        E1=GroupElement(Group,Next_ele)
        Pprint= GetAssocEnt(E1,500001)
        IF ValidGeometry(Pprint) THEN GOSUB Output_op_info
NEXT Next_ele
SUBEXIT

Output_op_info:!
A= GetUserValue(Pprint,"Category:")
I= 1
LOOP
        EXIT IF NOT CheckUserField(Pprint,"Line "&VAL$(I)&":",1)
        B$= UserDataStr(Pprint,"Line "&VAL$(I)&":")
        EXIT IF B$=""
        Stat=OutputCmdBuff("ASSIGN: Op_info= """&B$&""";",0)
        Stat=OutputCmdBuff("MACRO: op_info",0)
        I= I+1
END LOOP
RETURN
SUBEND

SUB Round_thrd_holes(HoleGrp,Macro_name$,Round_cut)
DIM Group_name$[256]
DIM Ques_str$[256]

Wzone= NamedVarVal("current loop work zone",WsAmoVars,0)
IF Wzone THEN
        Ques_str$= JoinStrings("WZ=",VAL$(Wzone)," ",ToolIdName(EntData))
ELSE
        Ques_str$= ToolIdName(EntData)
END IF

Hdiar= 0
Hdepr= 0
Stat= GroupName(HoleGrp,Group_name$)
Num_holes= GroupCount(HoleGrp)
FOR I= 1 TO Num_holes
        E1= GroupElement(HoleGrp,I)
        Hdia= EntityValue(E1,WsHoleDia)
        Hdepth= EntityValue(E1,WsHoleDepth)

        Stat= OutputCmdBuff("ASSIGN: Diameter= "&VAL$(Hdia)&";",0)
        Stat= OutputCmdBuff("ASSIGN: Finish_depth= "&VAL$(Hdepth)&";",0)
        IF Round_cut THEN Stat= OutputCmdBuff("ASSIGN: Depth_of_cut= Finish_depth;",0)

        Hnum= HoleNumber(E1)
        IF Round_cut THEN CALL AskQuestion("round_ques","Round ques",Group_name$,Ques_str$)
        IF NOT Round_cut THEN Hnum= I
        Stat= OutputCmdBuff("ASSIGN: Start_hole= "&VAL$(Hnum)&"; Holestartpt",0)
        Stat= OutputCmdBuff("MACRO: "&Macro_name$,0)
NEXT I
SUBEND

SUB GetPostName(Dir$,Pname$,Post_name$)
DIM Answer$[256]
DIM Namelist$[32000],Namelist2$[32000]

Post_name$= FileNameString(Dir$,Pname$)
IF LEN(Pname$) AND DoesFileExist(FileNameString(Post_name$,"amofiles"))=2 THEN SUBEXIT

Ask_name:!
Stat=DirectoryNames(Dir$,"[A-Z,0-1,a-z]*",Namelist$)
Stat=AlphabeticalOrder(Namelist$,",",WsAscending,Namelist2$)
Namelist$=""
J=POS(Namelist2$,",")
WHILE J
        Answer$= Namelist2$[1,J-1]
        IF DoesFileExist(FileNameString(Dir$,Answer$,"amofiles"))=2 THEN
                IF DoesFileExist(FileNameString(Dir$,Answer$,"hole_cycle")) THEN
                        Namelist$=Namelist$&Answer$&","
                END IF
        END IF
        Namelist2$= Namelist2$[J+1]
        J=POS(Namelist2$,",")
END WHILE
Stat=GeneralListBox("POSTS","POST CHOSEN",Namelist$)

Stat=SetInputFormat("a99","")
Stat=GetValue("TURBO POST NAME",Answer$)
LowerSelectBox
IF Answer$="CANCEL" THEN CALL CheckExit(1)
CALL CheckExit(0)
Post_name$= FileNameString(Dir$,Answer$)
IF NOT (LEN(Answer$) AND DoesFileExist(FileNameString(Post_name$,"amofiles"))=2) THEN Ask_name
SUBEND

SUB AskQuestion(File_name$,Packet_name$,Special_field$,Field2$)
! Field2 is an update of Special_field.  Special_field is kept for old jobs
! that already have it in them.
DIM Answer$[256],Ques_file$[256]
DIM Command$[256],Prompt$[256]
DIM Var_name$[256],Varstr$[256]
DIM A$[256],Packet_data$[256],Special_ques$[256]
Ques_packet= 911
PlotOn

Got_packet= 0
Ques_file$= FileNameString("amofiles",File_name$)

Ques_count=1
First_time=1
S_up= NamedVarVal("amo startup",WsAmoVars,1)
IF Field2$="NONE" THEN
        Special_ques$=""
ELSE
        Special_ques$=" for "&Field2$
END IF
Question_loop:!

        Exit_loop=AskCommandQues(Ques_file$,Ques_count)

        IF Exit_loop THEN Command_load

        Value=CurrActionVal(Varstr$)
        Var_type=CurrActionTyp
        Stat=CurrActionName(Var_name$)
        Stat=CurrActionPrompt(Prompt$)
        Valid_field= 0
        Prompt$= JoinStrings(Prompt$,Special_ques$)
        IF LEN(Prompt$)>80 THEN Prompt$=Prompt$[1,80]

        SELECT Var_type
        CASE 10
                Stat=CurrActionName(Command$)
        CASE 1,2
                IF NOT Got_packet THEN GOSUB Make_packet
                IF Got_packet THEN Valid_field=CheckUserField(Ques_data,Var_name$&":",1)
                Stat=SetInputFormat(StringChoice("n0=","n4=",(Var_type=1)))
                Stat=SetEqualsValue(Value)
                IF Valid_field THEN
                        Answer=GetUserValue(Ques_data,Var_name$&":")
                ELSE
                        Answer=GetValue(Prompt$)
                        CALL CheckExit(0)
                        IF Got_packet THEN Stat= PutUserValue(Ques_data,Var_name$&":",Answer)
                END IF
                Command$="ASSIGN: "&Var_name$&"= "&VAL$(Answer)&";"
        CASE 3
                IF NOT Got_packet THEN GOSUB Make_packet
                IF Got_packet THEN Valid_field=CheckUserField(Ques_data,Var_name$&":",1)
                Stat=SetInputFormat("a99","")
                IF Valid_field THEN
                        Answer$=UserDataStr(Ques_data,Var_name$&":")
                ELSE
                        Answer=GetValue(Prompt$,Answer$)
                        CALL CheckExit(0)
                        IF Got_packet THEN Stat= PutUserString(Ques_data,Var_name$&":",Answer$)
                END IF
                Command$="ASSIGN: "&Var_name$&"= """&Answer$&""";"
        END SELECT

        IF Var_type THEN
                Stat=OutputCmdBuff(Command$,(S_up AND First_time))
                IF First_time THEN First_time= 0
        END IF
        Ques_count= Ques_count+1

Endquesloop:IF NOT Exit_loop THEN Question_loop

Command_load:!
IF S_up THEN UpdateCmdFile
PlotOff
SUBEXIT

Make_packet:!
A$= CHR$(10)&"QUESTION DATA"&CHR$(10)
Ques_grp= GrpFindUserData(Packet_name$,Ques_packet)
IF NOT ValidGeometry(Ques_grp) THEN
New_packet:!
        Ques_data= CreateUserData(Ques_packet,Packet_name$,A$)
        IF ValidGeometry(Ques_data) THEN
                Stat= PutUserString(Ques_data,"Name:",Packet_name$)
                Stat= PutUserString(Ques_data,"Packet data:",Field2$)
                Got_packet= 1
        END IF
ELSE
        Num_ques= GroupCount(Ques_grp)
        SELECT Num_ques
        CASE 0
                GOTO New_packet
        CASE 1
                Ques_data= GroupElement(Ques_grp,1)
                IF NOT CheckUserField(Ques_data,"Packet data:",1) THEN
                        Ques_data= GroupElement(Ques_grp,1)     
                        GOTO End_packet
                END IF
                Packet_data$= UserDataStr(Ques_data,"Packet data:")
                IF Packet_data$<>Special_field$ AND Packet_data$<>Field2$ THEN New_packet
                Got_packet= 1
        CASE ELSE
                FOR K= 1 TO Num_ques
                        Ques_data= GroupElement(Ques_grp,K)
                        IF NOT CheckUserField(Ques_data,"Packet data:",1) THEN
                                Ques_data= GroupElement(Ques_grp,K)     
                                GOTO End_packet
                        END IF
                        Packet_data$= UserDataStr(Ques_data,"Packet data:")
                        IF Packet_data$=Special_field$ THEN End_packet
                        IF Packet_data$=Field2$ THEN End_packet
                NEXT K
Bad_packet:     GOTO New_packet
End_packet:     Got_packet= 1
        END SELECT
END IF
Stat= DeleteEntity(Ques_grp)
RETURN

SUBEND

SUB Check_zone_table

CALL Set_tmp_var("did sort",0,"")
CALL Set_tmp_var("did table",0,"")

Amo_table= FindNamedEntity("Amo process table")
IF ValidGeometry(Amo_table) THEN SUBEXIT

Tasks= FindNamedGrp("AMO OPERATIONS")
IF NOT ValidGeometry(Tasks) THEN
        CALL Auto_sort_tasks
        Did_sort= NamedVarVal("did sort",WsAmoVars,0)
        IF NOT Did_sort THEN CALL CheckExit(1)
        Tasks= FindNamedGrp("AMO OPERATIONS")
END IF

CALL Choose_material
Method=NamedVarVal("amo direction",WsToolVars,0.0)
Use_tools=NamedVarVal("use tool data",WsAmoVars,WsTrue)
Init_tool=NamedVarVal("initial tool number",WsAmoVars,1)
Tool_inc=NamedVarVal("tool number increment",WsAmoVars,1)

Pc= PointXYZ(0,0,0)
Zonelist= FindUserData("AMO WORK ZONES",23051)
Amo_table= AmoTasksZonesTable(Tasks,Zonelist,Pc,Method)
IF NOT ValidGeometry(Amo_table) THEN CALL CheckExit(1)

Stat= RedimTableColumns(Amo_Table,1,WsTrue)
Stat= InsertIntoTable(Amo_Table,"Fixture",1,4)
Stat= TaskColFromWZData(Amo_Table,5,"Fixture number:")
Stat= AmoTaskTableTnums(Amo_Table,Use_tools,Init_tool)
Stat= RedimTableColumns(Amo_Table,2,WsTrue)
IF CurrentUnits= WsMetric THEN
        Stat=InsertIntoTable(Amo_Table,"Feed(mmpm)",1,6)
ELSE
        Stat=InsertIntoTable(Amo_Table,"Feed(ipm)",1,6)
END IF
Stat=InsertIntoTable(Amo_Table,"Speed(rpm)",1,7)
Material= FindUserData("MATERIAL",WsMaterial)
Stat= TaskTableFeedSpeed(Amo_Table,Material,7,6)
Stat= NameEntity(Amo_table,"Amo process table")
Stat= HideEntity(Amo_table)
Stat= DeleteEntity(Pc)
Stat= CleanAmoTasksTable(Amo_table)
CALL Set_tmp_var("did table",1,"")
SUBEND

SUB Choose_material
DIM Answer$[256]
DIM Dir$[256],Namelist$[32000],Namelist2$[32000]

Material= FindUserData("MATERIAL",WsMaterial)
IF ValidGeometry(Material) THEN SUBEXIT
Get_material:!
Stat= NamedVarStr("material dir",WsSystemVars,"/usr/weber/util/tooldata/materials/",Dir$)
Stat=DirectoryNames(Dir$,"*",Namelist$)
Stat= AlphabeticalOrder(Namelist$,",",WsAscending,Namelist2$)
Stat=GeneralListBox("MATERIALS","MATERIAL SELECTED",Namelist2$)
Stat=SetInputFormat("a99","")
Stat=GetValue("INPUT MATERIAL FILE NAME",Answer$)
LowerSelectBox
IF Answer$="CANCEL" THEN CALL CheckExit(1)
CALL CheckExit(0)
Material=ReadUserData(WsMaterial,"MATERIAL",FileNameString(Dir$,Answer$))
IF NOT ValidGeometry(Material) THEN Get_material
SUBEND

SUB Auto_sort_tasks
DIM Prop_dir$[512],Prop_file$[1024]
DIM Tool_name$[256],Tasks_file$[256]
WsEventData= 12345

Stat= NamedVarStr("properties dir",WsSystemVars,"/usr/weber/database/properties/",Prop_dir$)
Stat= NamedVarStr("tasks file",WsAmoVars,"autotasks",Tasks_file$)

CALL Set_tmp_var("did sort",0,"")
G1= FindNamedGrp("AMO OPERATIONS")
IF ValidGeometry(G1) THEN SUBEXIT
Task_ent= FindUserData("AMO OPERATIONS",WsTaskPacket)
IF ValidGeometry(Task_ent) THEN
        Group= PropGrpFromFields(Task_ent,"Number tools:","Tool ",1,WsToolData,WsEventData)
        IF NOT ValidGeometry(Group) THEN CALL CheckExit(1)
ELSE
        Stat=RemoveDupTools
        Prop_file$= FileNameString(Prop_dir$,"TaskTemplates",Tasks_file$)
        IF NOT DoesFileExist(Prop_file$) THEN
                Prop_file$= FileNameString(Prop_dir$,"TaskTemplates","autotasks")
        END IF
        Group= AutoSortMillTasks(Prop_file$)
        IF NOT ValidGeometry(Group) THEN CALL CheckExit(1)
        IF GroupCount(Group)= 0 THEN
                Stat= DeleteEntity(Group)
                CALL CheckExit(1)
        END IF
END IF
Stat= ChangeGrpName(Group,"AMO OPERATIONS")
CALL Set_tmp_var("did sort",1,"")
SUBEND

SUB Set_tool_point(Initial_pt)
        Lp_type= NamedVarVal("last point type",WsAmoVars,2)
        IF NOT Initial_pt AND Lp_type<>1 THEN SUBEXIT
        Opt_x= NamedVarVal("optimize x",WsAmoVars,0)
        Opt_y= NamedVarVal("optimize y",WsAmoVars,0)
        Opt_z= NamedVarVal("optimize z",WsAmoVars,0)
        IF Opt_x= -99999 AND Initial_pt THEN Opt_x= 0
        IF Opt_y= -99999 AND Initial_pt THEN Opt_y= 0
        IF Opt_z= -99999 AND Initial_pt THEN Opt_z= 0
        Last_point= PointXYZ(Opt_x,Opt_y,Opt_z)
        Set_last_point(Last_point,Initial_pt)
SUBEND

SUB Set_last_point(ENTITY Last_point,Initial_point)
IF NOT Initial_point THEN
        Lp_type= NamedVarVal("last point type",WsAmoVars,2)
        IF Lp_type=1 THEN
                Stat= XYZPointValues("LAST AMO POINT",Last_x,Last_y,Last_z)
                Stat= XYZPointValues(Last_point,New_x,New_y,New_z)
                IF New_x= -99999 THEN New_x= Last_x
                IF New_y= -99999 THEN New_y= Last_y
                IF New_z= -99999 THEN New_z= Last_z
                Stat= DeleteEntity(Last_point)
                Last_point= PointXYZ(New_x,New_y,New_z)
        END IF
        Stat= DeleteEntity("LAST AMO POINT")
END IF
Stat= NameEntity(Last_point,"LAST AMO POINT")
Stat= HideEntity(Last_point)
SUBEND

SUB Set_tmp_var(Name$,Value,Val_str$)

G1= FindNamedGrp("TEMP AMO VARS")
IF NOT ValidGeometry(G1) THEN G1= CreateGroup("TEMP AMO VARS")

IF LEN(Val_str$) THEN
        V1= CreateVariable(Name$,WsAmoVars,Val_str$)
ELSE
        V1= CreateVariable(Name$,WsAmoVars,Value)
END IF
IF NOT ElementGrpNum(G1,V1) THEN Stat= AddToGroup(G1,V1)

SUBEND
