more efficent and confirmed correct calculation code