rewrote a lot for readability