Extract code processing to procedure

Add stop signal processing and correct port closing
Implement port selecting
Wrap code with try/catch
all works fine