  % Title "Intersections Demo"
 '% Animated
 '% ScaleUp
 '% PlaceCentral
 '% AnchorCentral
  uses consoleG
  uses GLO2\GeoPlanar
  uses chaos

  sub drawintersections()
  =======================


  type linex
    float x1,y1 'first point
    float x2,y2 'second point
    float le    'length
    int dl      'deletion flag
    int p1,p2   'point indexes
  end type

  string tab="    "
  point  p
  int    a
  float le

  seed=0x12379823

  pointex pn[100]
  linex dn[10000]
  float r[16]
  indexbase 0

  int i,j,k,q
  '
  '
  /*
 'grid
  q=36
  for i=0 to 5
    for j=0 to 5
      r[0]= i*0.3'+rnd()*.02
      r[1]=-j*0.3'+rnd()*.02
      pn[i*6+j]={ r[0],r[1] }
    next
  next
  */
  '
  '/*
  q=50
  for i=0 to q-1
    r[0]=rnd
    r[1]=rnd
    pn[i]={ r[0],r[1]}
  next
  '*/
  '
  k=0
  float x,y
  for i=0 to q-2
    for j=i+1 to q-1
      le=sqdist pn[i], pn[j]
      dn[k]={ pn[i].x,pn[i].y,pn[j].x,pn[j].y,le,0,i,j }
      k++
    next
  next
  '
  macro compare(c,a,b)
    if dn(a).le>dn(b).le
      c=1
    endif
  end macro
  '
  'NewSortIndex(idx, k, kf, filter, compare)
  reindex(idx, k, kf, filter, compare)
  '
  int mi,mj
  int ct
  line *dni,*dnj 'pointers for intersection test
  for i=0 to k-2
    mi=idx[i]
    @dni=@dn[mi]
    if dn[mi].dl=0
      for j=i+1 to k-1
        mj=idx[j]
        @dnj=@dn[mj]
        if dn[mj].dl=0
          'mark longer line for deletion
          a=intersected dni,dnj,p
          if a=16 'excluding ends <16
            ct++
            dn[mj].dl=1
          endif
        endif
      next 'j
    endif
  next 'i
  '

  'shading
  'flat 'default

  '
  color 0,1,1
  printl "intersect" tab k tab ct

  scale 10,10
  move 1,-1
  '
  color 0,1,1
  int e
  e=k-1
  linex dln[1000]
  int dc
  int p1,p2,n
  pointex*ph
  for i=0 to e
    mi=idx[i]
    if not dn[mi].dl
      dln[dc]=dn[mi]
      p1=dln[dc].p1 'first point index
      p2=dln[dc].p2 'second point index
      @ph=@pn[p1] 'first hub
      n=ph.n
      ph.pp[n]=p1 'store hub index
      ph.n++
      @ph=@pn[p2] 'second hub
      n=ph.n
      ph.pp[n]=p2 'store hub index
      ph.n++
      dc++ 'index next dln
      drawline @dn[mi]
    endif
  next
  '
  pointsize 7
  color 1,1,0
  '
  for i=0 to q-1
    drawpoint @pn[i]
  next
  del idx
  end sub


  sub main()
  ==========
  string s
  cls 0,0,0
  pushstate
  scale 2,2
  'typeface=1
  printl "Intersection Points"
  popstate
  '
  move 0,-2
  '
  PushState
  move 1,-1
  DrawIntersections
  PopState
  '
  
  end sub

  EndScript
