For most people, the easiest approach to automate tasks is to record an interactive command sequence (which will expose the required APIs), and then to edit the recorded result.
See
http://www.clausbrod.de/OneSpaceModeling/MacroModelClipping for additional hints on how to proceed from a recorded command sequence to an automated function.
Claus