function samurai_refund($params)
{
    $setup = Samurai::setup(array('sandbox' => $params['testMode'], 'merchantKey' => $params['merchantKey'], 'merchantPassword' => $params['merchantPass'], 'processorToken' => $params['procToken']));
    $gatewayid = $params['gatewayid'];
    $transid = $params['transid'];
    $amount = $params['amount'];
    $trans = Samurai_Transaction::find($transid);
    if ($amount) {
        $trans->reverse($amount);
    } else {
        $trans->reverse();
    }
    if ($trans->isSuccess()) {
        $refid = $trans->attributes['reference_id'];
        return array('status' => 'success', 'transid' => $refid);
    } else {
        $allerrors = "This transaction could not be processed:\n";
        foreach ($trans->errors as $context => $errors) {
            foreach ($errors as $error) {
                $allerrors .= $error->description . "\n";
            }
        }
        return array('status' => 'error', 'rawdata' => $allerrors);
    }
}
 $lastname = $result['lastname'];
 $address1 = $result['address1'];
 $address2 = $result['address2'];
 $city = $result['city'];
 $state = $result['state'];
 $postcode = $result['postcode'];
 $country = $result['country'];
 echo "Processing {$firstname} {$lastname} ({$clientid}): ";
 $d2 = select_query("tblclients", "cardtype, cardlastfour, AES_DECRYPT(cardnum, '{$cchash}') as cardnum, AES_DECRYPT(expdate, '{$cchash}') as expdate", array("id" => $clientid));
 $result2 = mysql_fetch_assoc($d2);
 $cardtype = $result2['cardtype'];
 $cardnum = $result2['cardnum'];
 $expmonth = substr($result2['expdate'], 0, 2);
 $expyear = substr($result2['expdate'], 2, 2);
 if ($cardnum) {
     $setup = Samurai::setup(array('merchantKey' => $merchantKey, 'merchantPassword' => $merchantPass, 'processorToken' => $procToken));
     $create = Samurai_PaymentMethod::create(array('card_number' => $cardnum, 'card_type' => $cardtype, 'expiry_month' => $expmonth, 'expiry_year' => $expyear, 'first_name' => $firstname, 'last_name' => $lastname, 'address_1' => $address1, 'address_2' => $address2, 'city' => $city, 'state' => $state, 'zip' => $postcode, 'country' => $country));
     if (!$create->hasErrors()) {
         $create->save();
         $create->retain();
         $token = $create->token;
         $gatewayids[$clientid] = $token;
         if ($removeexisting) {
             $delete = update_query('tblclients', array('cardnum' => ''), array('id' => $clientid));
             echo "Done. (Card Data Removed)\n";
         } else {
             echo "Done.\n";
         }
     } else {
         foreach ($create->errors as $context => $errors) {
             foreach ($errors as $error) {