Check the return values of WriteValue() and the value of @ERROR and @SERROR after each call.

You may well not have permission to write / create these keys.