Improved algorithm so that multiple inputs are now correctly calculated.