Refactor the codes

    * Add error checking
    * Split functions by row