better error handling and added some documentation
moved code around to have same function order as in the header