added comments and made code cleaner, also checked variables so we don't get overflow