completed the code.

still need to test and add comments.