Maybe you should write an UDF for this?