Well there's probably something wrong with the way inv_open_bag and inv_close_bag functions are working. Not sure how those functions are defined, but the logic doesn't look too nice; an if(key_i) inside another if(key_i) doesn't look like a good technique.