returning 0 from here if (state == 4) would avoid extra checks  for error conditions IMO