Added some common code + fixed memory leak.