Reworked main logic; needs optimization