Add UDF for handling prevstates