Is there any particular reason you have to write it yourself? I have a released and documented module you can use.