Restructured the code, added helpers