first working version. need optimization to decrease cpu time.