
  '----------------------------------
  sub MatrixInv(MatrixType *m, sys n)
  '==================================

  'Uses the Gauss-Jordan Method.
  'Inverts matrix, m[], "in-place".

  'limit to max 16x16 matrix

  sys        pivot,row,col,maxrow
  MatrixType test,colmax,divisor,factor,temp
  sys        rowswitch,switchcount
  sys        i,j
  sys        rs[128] 'for limit array n=64

  '
  'TO RESOLVE MATRIX INDEX
  '=======================
  '
  indexbase 0
  #define mat(row,col) m[ col*n+row ]
  #define rowswitches(row,col) rs[ col*64+row ]
  int first=0
  int last=n-1
  '
  'TRAVERSE COLUMNS
  '================


  for pivot=first to last
  '
  '
  'GET THE MAXIMUM ELEMENT ON EACH PIVOT COL
  '=========================================
  '
  colmax=0
  maxrow=pivot
  '
  for row=pivot to last
    test=abs (mat(row,pivot))
    if test>colmax then
      colmax=test
      maxrow=row
    end if
  next

  if maxrow<>pivot then
    '
    '
    'SWAP ROWS TO GET THE MAX VALUE AT THE PIVOT
    '===========================================
    '
    for col=first to last
      temp=mat(pivot,col)
      mat(pivot,col)=mat(maxrow,col)
      mat(maxrow,col)=temp
    next
    '
    '
    'REMEMBER THE ROW SWAP
    '=====================
    '
    rowswitches(switchcount,0)=pivot
    rowswitches(switchcount,1)=maxrow
    switchcount++
  end if
  '
  '
  'DIVIDE THE PIVOT ROW BY THE PIVOT DIAGONAL
  '==========================================
  '
  'also setting the pivot diagonal to 1
  '
  divisor=mat(pivot,pivot)
  mat(pivot,pivot)=1
  '
  for col=first to last
    mat(pivot,col)=mat(pivot,col) / divisor
  next


  'APPLY PIVOT FACTORS TO ALL ELEMENTS (OTHER THAN PIVOT ROW)
  '==========================================================
  '
  'also setting each pivot row element to 0
  '
  for row=first to last
    if row<>pivot then
      factor=-mat(row,pivot)
      mat(row,pivot)=0
      for col=first to last
        mat(row,col)=mat(row,col)+mat(pivot,col) * factor
      next
    end if
  next

  next 'pivot


  '
  'SWAP COLUMN VALUES ACCORDING TO ORIGINAL ROW POSITIONS
  '======================================================
  '
  for rowswitch=switchcount-1 to 0 step-1
    i=rowswitches(rowswitch,0)
    j=rowswitches(rowswitch,1)
    for row=first to last
      temp = mat(row,i)
      mat(row,i)=mat(row,j)
      mat(row,j)=temp
    next 
  next
  '
  '
  end sub
