I'm not sure if I got your specifications but something tells me your code is not even close of doing what you are supposed to do.

Why you don't start by using pseudo-code so your specs would get clear and the logic could be reviewed?