This logic is truly terrible and I know for certain there is an easier way to calculate this. I also know there are some bugs here. But, the user-facing result is not bad so let's start with this.