Major refactoring of serve_md function