Added edge case guards to tools.R and unit tests