How to write a library from a stand-alone program

There are lots of open-source programs out there. It can be anything from example files in a SDK to fully-fledged projects on GitHub or Google Code. One often wants to include the logic of these programs into her own projects. A beginner may think that the easiest way would be to write some shell code that takes the example program as-is, and tries convoluted ways to transform inputs/outputs adapter for testing and visual inspection into machine-processable data.