Rewrote some parts of the code and added comments