This line will probably get executed multiple times with the same type_id. Could we move it outside this loop?