add metrics support and re-arrange the code