' ----------------------------------------------------------------------
' DiskFile   : randpoly.ave : Set Random Polygons
' Programmer : Brian Biggs
' Created    : 26-Mar-96
' Revisions  : .
' Function   : Selects a percentage of ground truth polygons to withhold
'              for validation purposes by creating a field called "Validate"
'              and placing a boolean TRUE in the cell for each polygon
'              to withhold.  The script operates on shape files only.
' Called By  : .
' ----------------------------------------------------------------------

' set common vars
theProj = av.GetProject
theView = av.GetActiveDoc
If (theView.GetClass.GetClassName <> "View") then
  MsgBox.Info("View needs to be active.","")
  Exit
End

' get theme to withhold polys for
thmList = theView.GetThemes
shpList = {}
For Each t in thmList
  If (t.CanEdit) Then
    shpList.Add(t)
  End
End
If (shpList.Count = 0) then
  MsgBox.Error("A shape theme must be available to run script.","No Shape Themes")
  Exit
End
pikThm = MsgBox.ChoiceAsString(shpList,"Please choose a theme:","Pick Theme")
If (pikThm = NIL) then
  Exit
End

' get Ftab for pikThm
pikFtab = pikThm.GetFtab

' get field to select from
selFld = MsgBox.ChoiceAsString(pikFtab.GetFields,"Please choose a field to select from:","Choose Field")
If (selFld = NIL) then
  Exit
End

' get percentage to withhold
numStr = MsgBox.Input("Please enter a percentage to withhold:","Withhold Percentage","50")
If (numStr = NIL) then
  Exit
End
aPerc = numStr.AsNumber

' add validate field
pikFtab.SetEditable(TRUE)
valFld = pikFtab.FindField("Validate")
If (valFld <> NIL) then
  yesNo = MsgBox.YesNo("Field "+"Validate".Quote+" exists.  Reuse?","",TRUE)
  If (yesNo = TRUE) then
    pikFtab.RemoveFields({valFld})
  Else
    MsgBox.Info("Processed terminated.","")
    Exit
  End
End
valFld = Field.Make("Validate",#FIELD_LOGICAL,8,0)
pikFtab.AddFields({valFld})

' get unique types in selFld
typList = {}
For Each r In pikFtab
  i = pikFtab.ReturnValue(selFld,r)
  typList.Add(i)
End
typList.RemoveDuplicates

' open shape table
pikThm.EditTable
pikTab = theProj.FindDoc("Attributes of "+pikThm.AsString)

' start random selection loop
aMin = 0
For Each b In typList
  aBitMap = pikFtab.GetSelection
  aBitMap.ClearAll
 
  ' query selected class
  pikFtab.Query("(["++selFld.AsString++"] = "+b.AsString.Quote+" )",aBitMap,#VTAB_SELTYPE_OR)
  pikFtab.SetSelection(aBitMap)
  pikTab.PromoteSelection

  ' determine number of randoms to create based on percentage
  aMax = aBitMap.Count
  aCnt = aMax * (aPerc/100)
  aCnt.Round
  
  ' create list of random numbers
  randList = {}
  While (randList.Count < aCnt)
    aRand = Number.MakeRandom(aMin,aMax)
    randList.Add(aRand)
    randList.RemoveDuplicates
  End
  
  ' set Validate cell true for each number in list
  For Each n In randList
    aRec = pikTab.ConvertRowToRecord(n)
    pikFtab.SetValue(valFld,aRec,TRUE)
  End
End

pikFtab.SetEditable(FALSE)