final version. cleaned up code and comments