fixed terminate function