Added some more comments. Made function throw NullPointerException if an input is null.