# findErrorRows_OLD.R

## DEBUG:  Identify which row is causing an error in an *apply

#-------------------------------------
# TODO:  these are parameters required
groups <- 5
fun <- parseAddress
theData  <- fullList$Address
start <- 1
stop  <- length(theData) 
suppressWarnings <- TRUE
#-------------------------------------

findErrorRows <- function(theData, fun, margin=1, groups=5, start=1, stop=nrow(theData), suppressWarnings=TRUE)  {

    # Set Options to Suppress warnings, if flag is set
    if (suppressWarnings) {
      warn_bak <- getOption("warn")
      options("warn"=(-1))
    }

    ## CREATE THE EXPRESSION TO APPLY THE FUNCTION OVER EACH ROW
    problemCall <- expression(apply(theData[indexes], margin, fun))

    # CREATE THE SPLIT INDEXES
    splits <- c(0,floor((stop-start)*(1:groups)/groups)) + start

    ret <- 
    sapply(1:groups, function(i) {
      indexes <- splits[i]:splits[i+1]
      if (isErr(eval( problemCall )))  {
        return (indexes[1]:indexes[length(indexes)])
      }  else  {
        return(NA)
      }
     }
    )

          # #------------
          #     for (i in 1:groups) {

          #       indexes <- splits[i]:splits[i+1]
                
          #       if (isErr(eval( problemCall )))  {
          #         #TODO: recursive call, adjusting splits untill we find the specific error
          #         cat("Error exists between", indexes[1],":",indexes[length(indexes)], "\n")
          #       }  else  {
          #         cat("All Good between", indexes[1],":",indexes[length(indexes)], "\n")
          #       }
          #     }
          # #--------------

    # Put Wanrings Options back to previous state, if changes were made
    if (suppressWarnings) {
      options("warn"=warn_bak)
    }

    return(ret)
}
findErrorRows(tt, myTestFun)





#################################
###--------------------------####
### TESTING INFORMATION
myTestFun <- function(x) {
  if (!isErr(x['race']==3) & !is.na(x['race']==3)) {
    if (x['race']==3)  {stop("Woops. This is a sample error")}
  }  else  {
    if (x==3)  {stop("Woops. This is a sample error")}
  }
}
fun <-myTestFun
tt <- birthwt[sample(1:50, 30),]
tt$lwt[tt$race==3] <- -99
tt
threes <- which(tt$race==3)
threes
### END TESTS
###--------------------------
############################
