fixed crashes but contains a lot of suplicate code