Getting and setting Territory Assignments in a function

Getting and setting Territory Assignments in a function

Hi,
How do I get the current territory, and set/change territory assignments in a function? I want to be able to programmatically set the assigned territory for a contact with a function.