Have you looked at the code skimask gave here?
http://www.picbasic.co.uk/forum/showthread.php?t=6574