Didn't want to modify the code below risking missing some error checks or free()s.. The latter part of the code needs some cleanup anyway which we should do in the future