http://ola.hallengren.com/versions.html
http://sqlfool.com/2011/06/index-defrag-script-v4-1/
No need to roll your own solution.
Gail Shaw
Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability