Fixed compilation errors.
Added a function and error checking.