The Barbary Wars 1801-1805; 1815: Pirates/Corsairs from the Barbary Coast [Tunis, Algiers, Tripoli] raided American and European shipping in the Mediterranean Sea and demanded tribute for the goods and crews. If tribute was not paid, ships were captured or sunk, crews enslaved or held for ransom and the goods confiscated. President Jefferson sent the US Navy to end the piracy [1801-05]. The 2nd Barbary War in 1815 , over the same issue, was directed by President Madison.
Although I am not 100% sure, I believe from the accounts of Captain James Cunningham related by Isaac Prall, that Cunningham's was one of the US merchant vessels caught up in the actions of the Barbary Corsairs. His ship was all but destroyed and he was captured. Through the efforts of the Masons or another franternal organization to which he belonged, the captain's released was arranged.