Added comments and some checking, not tested yet!