It would be difficult to try give you a complete answer to your question for something that people write books about.
Recently I send a sample program to another person that asked a similiar question.
If you send me an email at firstname.lastname@example.org, I will send you some sample code that may help you.
The real solution is for you to purchase a book from MC Press to fully understand how to do this.
There are too many diffiferent variables to cover with this topic.