Major code cleanup, added functions