Have you thought through the steps a program must take to do what you are asking?
Can you list the steps you have so far and ask any questions about the problems you are having in getting the logic...