not the cleanest code i ever made but the logic seems correct to me