Added error packet handling
Some improvements in code