I wrote this a while ago, takes care of the basics. Going through it might help you understand how it works.