set display mode 800,600,32
 
segLimit = 50
dim segments(segLimit,4)   : `1=x1, 2=y1, 3=x2, 4=y2
 
segIndex = 0
 
blockSize = 20
 
 
 
sync on
 
 
 
do
   cls
 
 
   rem if mouse button clicked
   if mouseclick() = 1 and mFlag = 0
      mFlag = 1
      x1 = mousex()
      y1 = mousey()
   endif
 
   rem while holding mouse button down
   if mouseclick() = 1 and mFlag = 1
      x2 = mousex()
      y2 = mousey()
   endif
 
   rem draw all line segments currently stored
   badPosition = 0
   for i = 1 to segIndex
      ink rgb(184,184,184),0
      line segments(i,1),segments(i,2),segments(i,3),segments(i,4)
      if mFlag = 1
         t# = CX_2D_LineLine(x1,y1,x2,y2,segments(i,1),segments(i,2),segments(i,3),segments(i,4))
         if t# > 0 and t# < 1.0
            t2# = CX_2D_LineLine(segments(i,1),segments(i,2),segments(i,3),segments(i,4),x1,y1,x2,y2)
            if t2# > 0 and t2# < 1
               ix = x1 + (x2-x1)*t#
               iy = y1 + (y2-y1)*t#
               ink rgb(255,0,0),0
               circle ix,iy,4
               badPosition = 1
            endif
         endif
      endif
   next i
 
   rem if mouse button has been released
   if mouseclick() = 0
      if mFlag = 1
         rem if line is valid, store the values if there's room in the array
         if badPosition = 0
            if segIndex < segLimit
               inc segIndex, 1
               segments(segIndex,1) = x1
               segments(segIndex,2) = y1
               segments(segIndex,3) = x2
               segments(segIndex,4) = y2
            endif
         endif
         mFlag = 0
      endif
   endif
 
 
 
 
 
   rem display line
   if  mFlag = 1
      n# = (y2-y1)
      d# = (x2-x1)
      if d# <> 0 : slope# = n# / d# : else : slope# = 0 : endif
 
      length = CX_2D_LineLength#(x1,y1,x2,y2)
      blockCount# = length / blockSize
      for j = 0 to blockCount#-1
         t# = j/blockCount#
         bx = x1 + (x2-x1)*t#
         by = y1 + (y2-y1)*t#
         ink rgb(0,0,255),0
         box bx, by, bx+blockSize, by+blockSize
      next j
 
      if badPosition = 0 : ink rgb(0,255,0),0 : else : ink rgb(255,0,0),0 : endif
      line x1,y1,x2,y2
 
   endif
 
 
   sync
loop
 
`==============================================
`Finds intersection time of line[A,B] through
`line[C,D].  If lines intersection, value should
`be in set [0,1]
`==============================================
function CX_2D_LineLine(ax,ay,bx,by,cx,cy,dx,dy)
   num# = (dx-cx)*(ay-cy) - (dy-cy)*(ax-cx)
   den# = (dy-cy)*(bx-ax) - (dx-cx)*(by-ay)
   if den# = 0 then exitfunction -1
   Ua# = num# / den#
endfunction Ua#
 
 
`==============================================
`Returns the distance between two 2D points
`==============================================
function CX_2D_LineLength#(ax,ay, bx,by)
   x# = bx - ax
   y# = by - ay
   d# = sqrt(x#*x# + y#*y#)
endfunction d#