*! version 1.0.2  13jan2006  by Marc-Andreas Muendler: muendler@ucsd.edu
program define matins
  version 8
  syntax newvarname , Matrix(string) [ IFRow(string) IFCol(string) OVERwrite ]
  local matname = subinstr("`1'",`","',"",.)
  local cols = colsof(`matname')
  local rows = rowsof(`matname')
  tempname newmat
  * local newmat "newmat"
  if "`ifrow'"=="" & "`ifcol'"=="" {
    disp as err "row or column list required"
    exit 100
    }
  if "`ifrow'"~="" & "`ifcol'"~="" {
    disp as err "simultaneous row and column lists not allowed"
    exit 101
    }

  /* Row Keep and Order */
  if "`ifrow'"~="" {
    tempname addrow
    mat `addrow' = J(1,colsof(`matname'),.)
    * check existence of rows
    local rownames : rowfullnames `matname'
    local totrow : word count `rownames'
    tokenize `rownames'
    foreach row in `ifrow' {
      mat rownames `addrow' = `row'
      capture local chk = rowsof(`newmat')
      if _rc~=0 {
        if rownumb(`matname',"`row'")~=. {
          mat `newmat' = `matname'[rownumb(`matname',"`row'"),1..colsof(`matname')]
          }
        else {
          mat `newmat' = `addrow'
          }
        }
      else {
        if rownumb(`matname',"`row'")~=. {
          mat `newmat' = `newmat' \ `matname'[rownumb(`matname',"`row'"),1..colsof(`matname')]
          }
        else {
          mat `newmat' = `newmat' \ `addrow'
          }
        }
      }
    }

  /* Col Keep and Order */
  if "`ifcol'"~="" {
    tempname addcol
    mat `addcol' = J(rowsof(`matname'),1,.)
    * check existence of columns
    local colnames : colfullnames `matname'
    local totcol : word count `colnames'
    tokenize `colnames'
    foreach col in `ifcol' {
      mat colnames `addcol' = `col'
      capture local chk = colsof(`newmat')
      if _rc~=0 {
        if colnumb(`matname',"`col'")~=. {
          mat `newmat' = `matname'[1..rowsof(`matname'),colnumb(`matname',"`col'")]
          }
        else {
          mat `newmat' = `addcol'
          }
        }
      else {
        if colnumb(`matname',"`col'")~=. {
          mat `newmat' = `newmat' , `matname'[1..rowsof(`matname'),colnumb(`matname',"`col'")]
          }
        else {
          mat `newmat' = `newmat' , `addcol'
          }
        }
      }
    }

  /* Finalize */
  if "`matrix'"=="`matname'" {
    mat drop `matname'
    mat `matname' = `newmat'
    }
  else {
    capture local check = colsof(`matrix')
    if _rc==0 & "`overwrite'"=="" {
       disp as err "no; matrix " in yellow "`matrix'" in red " would be lost"
       exit 4
       }
    mat `matrix' = `newmat'
    }

end