Added a lot of functions for more readability, correct termination if out of meory