Restructuring, bug fix, and more friendly error reporting