cid#1194925 Resource leak

reorganise the code to keep coverity happy

Change-Id: I18fc2dfd17f97edf1d17c57caaed4cc9d2fedd13