/*
 * CM_CRC.pgc - cm 모듈 서비스 CM_CRC (one service = one file).
 * Split out of the former inline cm_svr.pgc; runs on the caller's XA
 * branch (no EXEC SQL CONNECT). Advertised by cm_svr at tpsvrinit.
 */
#include "CM_CRC.h"

/* ----- service-local pure helper(s) ----- */
/* CRC-16/CCITT-FALSE over a string. */
static unsigned int cm_crc16(const char *s)
{
    unsigned int crc = 0xFFFF; int i, j;
    for (i = 0; s[i]; i++) {
        crc ^= (unsigned int)(unsigned char)s[i] << 8;
        for (j = 0; j < 8; j++)
            crc = (crc & 0x8000) ? ((crc << 1) ^ 0x1021) & 0xFFFF : (crc << 1) & 0xFFFF;
    }
    return crc & 0xFFFF;
}


/* 14. CM_CRC - CRC16 계산 (순수 계산). */
void CM_CRC(TPSVCINFO *p)
{
    UBFH *b = (UBFH *)p->data;
    char in[256], out[8];
    unsigned int crc;
    gets_(b, T_STR1, in, sizeof(in));
    crc = cm_crc16(in);
    sprintf(out, "%04X", crc);
    sets_(b, T_STR4, out);
    setl(b, T_ARG1, (long)crc);
    OK(b);
}
