Rewrote some parts for readability