refine the code, add offline logic