working version, could be optimized time-wise.