first complete working version of the code. probably needs more documentation and also more modularity in the code.