Battery charging algorithm from rumirand's kernel