How can I check the stock quantity with already number of added quantity in the cart before add it into cart?

I want to check and compare the order stock of inventory with the already added quantity in the cart when click on Add to Cart button. If user exceed the stock quantity I want to stop or show the error message to the user.

I checked in code there is one function mentioned below I guess it is used for adding the product in the cart.
function toBasket($sProductId = null, $dAmount = null, $aSel = null, $aPersParam = null, $blOverride = false)

Any help would be highly appreciated. Thanks