Major refactor with minor bugs