How Arabic Letter Changes from Isolated to Initial and Medial and Final??

How Arabic Letter Changes from Isolated to Initial and Medial and Final??

Salam to all members

This is my first posting but not the first visit to the forum. I have some problems to share with forum members if anyone may solve my problems. I want to write an algorihm for Arabic characters but I did not achieve the goal after trying for round about 10 hours. I will justify my problems with the help of steps (let suppose for some characters).
1. When I press a key for Arabic letter Beh (ب), its isolated form is displayed.
2. In step 2, not pressing any space, when I press another kety, say Kaf (ك), the letter Beh changes to its initial form while letter Kaf automatically changes to its final form.
3. In step 3, the step 2 is repeated untill the space button is not pressed.
HOW THIS WHOLE PROCESS IS PERFORMED, PLEASE GIVE ME YOUR KIND ATTENTION.