added complete code in appendix