first two posts on my blog here explains how it's done :
SEO Projects and Pictures Blog
have a read through and if you understand a little code you will surely get it. It's good .. you can make it do Adsense or the Amazon widget (or whatever you want) or other stuff as it just executes code depending on category.