
/* This function is called by several trigger functions including
 * move_preupd_func.plsql, move_update_func.plsql and
 * move_delete_func.plsql. It receives three arguments; the origin, the
 * destination, and the routing algorithm to use. It calls other functions
 * in order to connect to the PCMiler database, look up the miles, and
 * finally, close the connection. This function is designed to perform a
 * single mileage lookup; therefore, it opens and closes the PCMiler
 * database connection on it's own. */
PG_FUNCTION_INFO_V1(pcm_getmiles_s);        /* notify of load convention */
Datum pcm_getmiles_s (PG_FUNCTION_ARGS)
{
    text *arg1 = PG_GETARG_TEXT_P(0);       /* origin,province */
    text *arg2 = PG_GETARG_TEXT_P(1);       /* destination,province */
    int2 routeType = PG_GETARG_INT16(2);    /* type of lookup - see above */
    char *orig = palloc (VARSIZE(arg1) - VARHDRSZ + 1);
    char *dest = palloc (VARSIZE(arg2) - VARHDRSZ + 1);
    float8 result;                          /* return value */
    long miles;                             /* 10th's of miles */
    PCMServerID serverID;

    snprintf (orig, VARSIZE(arg1) - VARHDRSZ + 1, VARDATA(arg1));
    snprintf (dest, VARSIZE(arg2) - VARHDRSZ + 1, VARDATA(arg2));

#ifndef DEBUG
    elog (NOTICE, "ORIG: %s, DEST: %s", orig, dest);
#endif

    serverID = PCMilerConnect ();           /* connect to PCMiler server */
    if (serverID == 0) return 0;            /* could not connect to server */

    miles = PCMGetMiles (serverID, orig, dest, routeType);
    PCMilerClose (serverID);                /* close the connection */

    pfree (orig);                           /* free the memory */
    pfree (dest);                           /* free the memory */

    if (miles < 0) result = 0;
    else result = miles / 10.0;             /* answer always in 10th's of
                                               miles */
    PG_RETURN_FLOAT8(result);
}

