Wouldn't it be the reference to "$Value" and "$Val" in you Function which makes things wrong ?

"Function WRITEINREG($sub,$name,$value,$dtype)
...
$n=WriteValue($sub,$name,$val,$dtype)
..."