The easiest way would probably be to look at the code for a script that does exactly what you want to do.