Inserted checking line for ndim > 0
N -> changed to use range.size()