Restructured most of the code