working code. cleaned up