Fixed segfault. Not working correctly though. Output is incorrect.