Adjust code arrangement to be more consistent with the original code, removed some exception raising