/*
 * libunicall - a library for universal call handling on both analogue and
 *              digital telephone circuits.
 *
 * testcall.c
 *
 * Written by Steve Underwood <steveu@coppice.org>
 *
 * Copyright (C) 2002 Steve Underwood
 *
 * All rights reserved.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 * $Id: testcall.c,v 1.20 2005/08/07 13:14:51 steveu Exp $
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <sys/signal.h>
#include <sys/select.h>
#include <sys/wait.h>
#include <sys/resource.h>
#include <sys/time.h>
#include <linux/zaptel.h>
#include <pthread.h>
#if defined(HAVE_SPANDSP_H)
#include <tiffio.h>
#endif
#if defined(HAVE_SPANDSP_H)
#include <spandsp.h>
#endif

#include "unicall.h"

#define FALSE 0
#define TRUE (!FALSE)

#define MAX_TRUNKS      240

enum
{
    OFFERED_ACTION_ACCEPT = 0,
    OFFERED_ACTION_ANSWER,
    OFFERED_ACTION_BUSY,
    OFFERED_ACTION_UNASSIGNED,
    OFFERED_ACTION_CONGESTED,
    OFFERED_ACTION_OOS,
    OFFERED_ACTION_RANDOM,
    OFFERED_ACTION_END
};

struct
{
    char *protocol_class;
    char *protocol_variant;
    int protocol_end;
    int chan_no;
    int caller_mode;

    char *tag;

    char originating_number[UC_MAXPHONENUMLEN + 1];
    char destination_number[UC_MAXPHONENUMLEN + 1];

    pthread_t thread;
    int sig_fd;
    int fd;
    uc_call_t *call;
    uc_crn_t crn;
    int block_head;
    int action_on_offered;
    
    int og_call_number;
    int ic_call_number;
    uc_callparms_t call_parms;

#if defined(HAVE_SPANDSP_H)
    dtmf_tx_state_t dtmf_tx_state;
    dtmf_rx_state_t dtmf_rx_state;
    char dtmf[101];
    int dtmf_ptr;
#endif

    int silent_samples;
    
    time_t last_call;
} chan_stuff[MAX_TRUNKS];

void channel_read_file(uc_t *uc, int chan, void *user_data, uint8_t *buf, int len);
int channel_write_file(uc_t *uc, int chan, void *user_data, uint8_t *buf, int max_len);
int channel_error(uc_t *uc, int chan, void *user_data, int cause);
int signaling_error(uc_t *uc, void *user_data, int cause);

void channel_read_file(uc_t *uc, int ch, void *user_data, uint8_t *buf, int len)
{
    int16_t pcm_buf[1024];
    int i;
    int xlen;
    char *s;
    char *t;
    char *u;
    char *v;
    char *w;
    char originating_number[UC_MAXPHONENUMLEN + 1];
    char destination_number[UC_MAXPHONENUMLEN + 1];
    int call_number;
    int chan;
    int hits;
    int ok;
    
    chan = (intptr_t) user_data;
    for (i = 0;  i < len;  i++)
        pcm_buf[i] = alaw_to_linear(buf[i]);
    /*endfor*/

#if defined(HAVE_SPANDSP_H)
    dtmf_rx(&chan_stuff[chan].dtmf_rx_state, pcm_buf, len);
    xlen = dtmf_get(&chan_stuff[chan].dtmf_rx_state,
                    chan_stuff[chan].dtmf + chan_stuff[chan].dtmf_ptr,
                    100 - chan_stuff[chan].dtmf_ptr);
    if (xlen > 0)
    {
    	s = chan_stuff[chan].dtmf + chan_stuff[chan].dtmf_ptr;
        while (*s)
        {
            if (*s == '#')
            {
                printf("%s Received DTMF '%s'\n", chan_stuff[chan].tag, chan_stuff[chan].dtmf);
                ok = FALSE;
                call_number = -1;
                if ((t = strchr(chan_stuff[chan].dtmf, '*')))
                {
                    *t++ = '\0';
                    if ((u = strchr(t, '*')))
                    {
                        *u++ = '\0';
                        if ((v = strchr(u, '*')))
                        {
                            *v++ = '\0';
                            if ((w = strchr(v, '*')))
                            {
                                *w++ = '\0';
                                sscanf(t, "%d", &call_number);
                                if (strcmp(u, chan_stuff[chan].call_parms.originating_number) == 0
                                    &&
                                    strcmp(v, chan_stuff[chan].call_parms.destination_number) == 0
                                    &&
                                    call_number == chan_stuff[chan].ic_call_number)
                                {
                                    ok = TRUE;
                                }
                            }
                        }
                    }
                }
                if (!ok)
                {
                    printf("%s Received DTMF string incorrect %d %d '%s' '%s' '%s' '%s'\n",
                           chan_stuff[chan].tag,
                           call_number,
                           chan_stuff[chan].ic_call_number,
                           u,
                           chan_stuff[chan].call_parms.originating_number,
                           v,
                           chan_stuff[chan].call_parms.destination_number);
                }
                chan_stuff[chan].dtmf_ptr = 0;
                xlen = 0;
                dtmf_put(&chan_stuff[chan].dtmf_tx_state, "A");
                break;
            }
            else if (*s == 'A')
            {
                /* We can disconnect now */
                printf("%s Received DTMF '%s'\n", chan_stuff[chan].tag, chan_stuff[chan].dtmf);
                uc_set_channel_read_callback(uc, 0, NULL, NULL);
                uc_set_channel_write_callback(uc, 0, NULL, NULL);
                if (uc_call_control(uc, UC_OP_DROPCALL, chan_stuff[chan].crn, (void *) UC_CAUSE_NORMAL_CLEARING))
            	    printf("A Drop Call failed\n");
                /*endif*/
    	    	chan_stuff[chan].dtmf_ptr = 0;
                xlen = 0;
            }
	    /*endif*/
            s++;
        }
        /*endwhile*/
        chan_stuff[chan].dtmf_ptr += xlen;
    }
    /*endif*/
#endif
}
/*- End of function --------------------------------------------------------*/

int channel_write_file(uc_t *uc, int ch, void *user_data, uint8_t *buf, int max_len)
{
    int16_t pcm_buf[1024];
    int i;
    int len;
    int chan;
    static int fd = -1;
    
    chan = (intptr_t) user_data;
#if defined(HAVE_SPANDSP_H)
    if (chan_stuff[chan].silent_samples > 0)
    {
        for (i = 0;  i < max_len;  i++)
            buf[i] = linear_to_alaw(0);
        /*endfor*/
        chan_stuff[chan].silent_samples -= max_len;
        len = max_len;
    }
    else
    {
        len = dtmf_tx(&chan_stuff[chan].dtmf_tx_state, pcm_buf, max_len);
        for (i = 0;  i < len;  i++)
            buf[i] = linear_to_alaw(pcm_buf[i]);
        /*endfor*/
    }
    /*endif*/
#else
    len = 0;
#endif
if (chan == 0)
{
    if (fd < 0)
        fd = open("txsound.au", O_WRONLY  | O_CREAT | O_TRUNC, 0666);
    if (fd >= 0)
        write(fd, buf, len);
}
    return len;
}
/*- End of function --------------------------------------------------------*/

int channel_error(uc_t *uc, int chan, void *user_data, int cause)
{
    printf("Error %d\n", cause);
    return  0;
}
/*- End of function --------------------------------------------------------*/

int signaling_error(uc_t *uc, void *user_data, int cause)
{
    printf("Error %d\n", cause);
    return  0;
}
/*- End of function --------------------------------------------------------*/

static void initiate_call(uc_t *uc, int chan, uc_event_t *e)
{
    uc_makecall_t makecall;
    uc_callparms_t *callparms;
    int ret;

    printf ("%s Initiating call\n", chan_stuff[chan].tag);
    if ((callparms = uc_new_callparms(NULL)) == NULL)
        return;
    /*endif*/
    strcpy(chan_stuff[chan].call_parms.originating_number, chan_stuff[chan].originating_number);
    strcpy(chan_stuff[chan].call_parms.destination_number, chan_stuff[chan].destination_number);
    uc_callparm_originating_number(callparms, chan_stuff[chan].originating_number);
    uc_callparm_destination_number(callparms, chan_stuff[chan].destination_number);
    makecall.callparms = callparms;
    makecall.crn = 0;
    chan_stuff[chan].og_call_number++;
    if ((ret = uc_call_control(uc, UC_OP_MAKECALL, 0, (void *) &makecall)) != UC_RET_OK)
        fprintf(stderr, "Make call failed - %d\n", ret);
    /*endif*/
    chan_stuff[chan].crn = makecall.crn;
    free(callparms);
}
/*- End of function --------------------------------------------------------*/

static void handle_uc_event(uc_t *uc, void *user_data, uc_event_t *e)
{
    time_t now;
    int chan;
    int on_offered;
    char buf[80];

    chan = (intptr_t) user_data;
    switch (e->e)
    {
    case UC_EVENT_DEVICEFAIL:
        break;
    case UC_EVENT_PROTOCOLFAIL:
        printf("%s -- Protocol failure on channel %d, cause (%d) %s\n", chan_stuff[chan].tag, e->gen.channel, e->gen.data, uc_error_message(uc, e->gen.data));
        fprintf(stderr, "%s -- Protocol failure on channel %d, cause (%d) %s\n", chan_stuff[chan].tag, e->gen.channel, e->gen.data, uc_error_message(uc, e->gen.data));
        break;
    case UC_EVENT_SIGCHANSTATUS:
        printf("%s -- Signalling channel status - %s\n", chan_stuff[chan].tag, e->sigchanstatus.ok  ?  "Up"  :  "Down");
        fprintf(stderr, "%s -- Signalling channel status - %s\n", chan_stuff[chan].tag, e->sigchanstatus.ok  ?  "Up"  :  "Down");
        break;
    case UC_EVENT_ALARM:
        printf("%s -- %s - 0x%X/0x%X\n", chan_stuff[chan].tag, uc_event2str(e->e), e->alarm.raised, e->alarm.cleared);
        fprintf(stderr, "%s -- %s - 0x%X\n", chan_stuff[chan].tag, uc_event2str(e->e), e->alarm.raised, e->alarm.cleared);
        break;
    case UC_EVENT_FARBLOCKED:
        printf("%s -- %s! :-(\n", chan_stuff[chan].tag, uc_event2str(e->e));
        fprintf(stderr, "%s -- %s! :-(\n", chan_stuff[chan].tag, uc_event2str(e->e));
        chan_stuff[chan].block_head &= ~1;
        break;
    case UC_EVENT_FARUNBLOCKED:
        printf("%s -- %s! :-)\n", chan_stuff[chan].tag, uc_event2str(e->e));
        fprintf(stderr, "%s -- %s! :-)\n", chan_stuff[chan].tag, uc_event2str(e->e));
        chan_stuff[chan].block_head |= 1;
        if (chan_stuff[chan].block_head == 3)
        {
            if (chan_stuff[chan].caller_mode)
                initiate_call(uc, chan, e);
            /*endif*/
        }
        /*endif*/
        break;
    case UC_EVENT_LOCALBLOCKED:
        printf("%s -- %s! :-(\n", chan_stuff[chan].tag, uc_event2str(e->e));
        fprintf(stderr, "%s -- %s! :-(\n", chan_stuff[chan].tag, uc_event2str(e->e));
        chan_stuff[chan].block_head &= ~2;
        break;
    case UC_EVENT_LOCALUNBLOCKED:
        printf("%s -- %s! :-)\n", chan_stuff[chan].tag, uc_event2str(e->e));
        fprintf(stderr, "%s -- %s! :-)\n", chan_stuff[chan].tag, uc_event2str(e->e));
        chan_stuff[chan].block_head |= 2;
        if (chan_stuff[chan].block_head == 3)
        {
            if (chan_stuff[chan].caller_mode)
                initiate_call(uc, chan, e);
            /*endif*/
        }
        /*endif*/
        break;
    case UC_EVENT_DIALING:
        printf("%s -- %s on channel %d\n", chan_stuff[chan].tag, uc_event2str(e->e), e->gen.channel);
        fprintf(stderr, "%s -- %s on channel %d\n", chan_stuff[chan].tag, uc_event2str(e->e), e->gen.channel);
        break;
    case UC_EVENT_PROCEEDING:
        printf("%s -- Proceeding on channel %d\n", chan_stuff[chan].tag, e->gen.channel);
        break;
    case UC_EVENT_ACCEPTED:
        printf("%s -- Accepted on channel %d\n", chan_stuff[chan].tag, e->gen.channel);
        fprintf(stderr, "%s -- Accepted on channel %d\n", chan_stuff[chan].tag, e->gen.channel);
        if (uc_call_control(uc, UC_OP_ANSWERCALL, e->offered.crn, NULL))
            fprintf(stderr, "Answer Call failed\n");
        /*endif*/
        break;
    case UC_EVENT_DETECTED:
        printf("%s -- %s on channel %d, CRN %d\n",
               chan_stuff[chan].tag, uc_event2str(e->e),
               e->gen.channel, e->gen.crn);
        fprintf(stderr, "%s -- %s on channel %d, CRN %d\n", chan_stuff[chan].tag, uc_event2str(e->e), e->gen.channel, e->gen.crn);
        chan_stuff[chan].crn = e->gen.crn;
        chan_stuff[chan].ic_call_number++;
        break;
    case UC_EVENT_MOREDIGITS:
        printf("%s -- %s on channel %d\n", chan_stuff[chan].tag, uc_event2str(e->e), e->gen.channel);
        fprintf(stderr, "%s -- %s on channel %d\n", chan_stuff[chan].tag, uc_event2str(e->e), e->gen.channel);
        break;
    case UC_EVENT_ALERTING:
        printf("%s -- %s on channel %d\n", chan_stuff[chan].tag, uc_event2str(e->e), e->gen.channel);
        fprintf(stderr, "%s -- %s on channel %d\n", chan_stuff[chan].tag, uc_event2str(e->e), e->gen.channel);
        /* This is just a notification of call progress. We need take no action at this point. */
        break;
    case UC_EVENT_FARDISCONNECTED:
        printf("%s -- %s on channel %d\n",
               chan_stuff[chan].tag,
               uc_event2str(e->e),
               e->fardisconnected.channel);
        fprintf(stderr,
                "%s -- %s on channel %d\n",
                chan_stuff[chan].tag,
                uc_event2str(e->e),
                e->fardisconnected.channel);
        /* Kill any outstanding audio processing */
        uc_set_channel_read_callback(uc, 0, NULL, NULL);
        uc_set_channel_write_callback(uc, 0, NULL, NULL);
        if (uc_call_control(uc, UC_OP_DROPCALL, e->fardisconnected.crn, (void *) UC_CAUSE_NORMAL_CLEARING))
            fprintf(stderr, "C Drop Call failed\n");
        /*endif*/
        break;
    case UC_EVENT_DROPCALL:
        printf("%s -- %s on channel %d\n", chan_stuff[chan].tag, uc_event2str(e->e), e->gen.channel);
        fprintf(stderr, "%s -- %s on channel %d\n", chan_stuff[chan].tag, uc_event2str(e->e), e->gen.channel);
        if (uc_call_control(uc, UC_OP_RELEASECALL, e->gen.crn, NULL))
            fprintf(stderr, "Release Call failed\n");
        /*endif*/
        break;
    case UC_EVENT_RELEASECALL:
        printf("%s -- %s on channel %d\n", chan_stuff[chan].tag, uc_event2str(e->e), e->gen.channel);
        fprintf(stderr, "%s -- %s on channel %d\n", chan_stuff[chan].tag, uc_event2str(e->e), e->gen.channel);
        if (chan_stuff[chan].caller_mode)
            initiate_call(uc, chan, e);
        /*endif*/
        break;
    case UC_EVENT_OFFERED:
        printf("%s -- %s on channel %d, CRN %d (ANI: %s, DNIS: %s)\n",
               chan_stuff[chan].tag,
               uc_event2str(e->e),
               e->offered.channel,
               e->offered.crn,
               e->offered.parms.originating_number,
               e->offered.parms.destination_number);
        fprintf(stderr,
                "%s -- %s on channel %d, CRN %d (ANI: %s, DNIS: %s)\n",
                chan_stuff[chan].tag,
                uc_event2str(e->e),
                e->offered.channel,
                e->offered.crn,
                e->offered.parms.originating_number,
                e->offered.parms.destination_number);
        memcpy(&chan_stuff[chan].call_parms, &e->offered.parms, sizeof(chan_stuff[chan].call_parms));
        if (!chan_stuff[chan].caller_mode)
        {
            time(&now);
            on_offered = chan_stuff[chan].action_on_offered;
            if (on_offered == OFFERED_ACTION_RANDOM)
            {
                do
                    on_offered = rand() & 0x7;
                while (on_offered >= OFFERED_ACTION_END);
            }
            /*endif*/
            switch (on_offered)
            {
            case OFFERED_ACTION_ACCEPT:
                fprintf(stderr, "%s -- +++ ACCEPT (%d)\n", chan_stuff[chan].tag, now - chan_stuff[chan].last_call);
                if (uc_call_control(uc, UC_OP_ACCEPTCALL, e->offered.crn, NULL))
                    fprintf(stderr, "Accept Call failed\n");
                /*endif*/
                break;
            case OFFERED_ACTION_ANSWER:
                fprintf(stderr, "%s -- +++ ANSWER (%d)\n", chan_stuff[chan].tag, now - chan_stuff[chan].last_call);
                if (uc_call_control(uc, UC_OP_ANSWERCALL, e->offered.crn, NULL))
                    fprintf(stderr, "Answer Call failed\n");
                /*endif*/
                break;
            case OFFERED_ACTION_BUSY:
                fprintf(stderr, "%s -- +++ BUSY (%d)\n", chan_stuff[chan].tag, now - chan_stuff[chan].last_call);
                if (uc_call_control(uc, UC_OP_DROPCALL, e->offered.crn, (void *) UC_CAUSE_USER_BUSY))
                    fprintf(stderr, "E Drop Call failed\n");
                /*endif*/
                break;
            case OFFERED_ACTION_UNASSIGNED:
                fprintf(stderr, "%s -- +++ UNASSIGNED (%d)\n", chan_stuff[chan].tag, now - chan_stuff[chan].last_call);
                if (uc_call_control(uc, UC_OP_DROPCALL, e->offered.crn, (void *) UC_CAUSE_UNASSIGNED_NUMBER))
                    fprintf(stderr, "F Drop Call failed\n");
                /*endif*/
                break;
            case OFFERED_ACTION_CONGESTED:
                fprintf(stderr, "%s -- +++ CONGESTED (%d)\n", chan_stuff[chan].tag, now - chan_stuff[chan].last_call);
                if (uc_call_control(uc, UC_OP_DROPCALL, e->offered.crn, (void *) UC_CAUSE_NETWORK_CONGESTION))
                    fprintf(stderr, "G Drop Call failed\n");
                /*endif*/
                break;
            case OFFERED_ACTION_OOS:
                fprintf(stderr, "%s -- +++ OUT OF SERVICE (%d)\n", chan_stuff[chan].tag, now - chan_stuff[chan].last_call);
                if (uc_call_control(uc, UC_OP_DROPCALL, e->offered.crn, (void *) UC_CAUSE_DEST_OUT_OF_ORDER))
                    fprintf(stderr, "H Drop Call failed\n");
                /*endif*/
                break;
            }
            /*endswitch*/
            chan_stuff[chan].last_call = now;
        }
        /*endif*/
        break;
    case UC_EVENT_ANSWERED:
        printf("%s -- %s on channel %d\n", chan_stuff[chan].tag, uc_event2str(e->e), e->gen.channel);
        fprintf(stderr, "%s -- %s on channel %d\n", chan_stuff[chan].tag, uc_event2str(e->e), e->gen.channel);
        uc_set_channel_read_callback(uc, 0, channel_read_file, (void *) (intptr_t) chan);
    	chan_stuff[chan].og_call_number++;
#if defined(HAVE_SPANDSP_H)
        dtmf_rx_init(&chan_stuff[chan].dtmf_rx_state, NULL, NULL);
        dtmf_tx_init(&chan_stuff[chan].dtmf_tx_state);
        chan_stuff[chan].silent_samples = 4000;
        sprintf(buf, "*%08d*%s*%s*#", chan_stuff[chan].og_call_number, chan_stuff[chan].originating_number, chan_stuff[chan].destination_number);
        printf("%s -- '%s'\n", chan_stuff[chan].tag, buf);
        dtmf_put(&chan_stuff[chan].dtmf_tx_state, buf);
#endif
        uc_set_channel_write_callback(uc, 0, channel_write_file, (void *) (intptr_t) chan);
        break;
    case UC_EVENT_CONNECTED:
        printf("%s -- %s on channel %d\n", chan_stuff[chan].tag, uc_event2str(e->e), e->gen.channel);
        fprintf(stderr, "%s -- %s on channel %d\n", chan_stuff[chan].tag, uc_event2str(e->e), e->gen.channel);
        uc_set_channel_read_callback(uc, 0, channel_read_file, (void *) (intptr_t) chan);
    	chan_stuff[chan].ic_call_number++;
#if defined(HAVE_SPANDSP_H)
        dtmf_rx_init(&chan_stuff[chan].dtmf_rx_state, NULL, NULL);
        dtmf_tx_init(&chan_stuff[chan].dtmf_tx_state);
        chan_stuff[chan].silent_samples = 4000;
        sprintf(buf, "*%08d*%s*%s*#", chan_stuff[chan].og_call_number, chan_stuff[chan].originating_number, chan_stuff[chan].destination_number);
        printf("%s -- '%s'\n", chan_stuff[chan].tag, buf);
        dtmf_put(&chan_stuff[chan].dtmf_tx_state, buf);
#endif
        uc_set_channel_write_callback(uc, 0, channel_write_file, (void *) (intptr_t) chan);
        break;
    default:
        printf ("%s -- %s\n", chan_stuff[chan].tag, uc_event2str(e->e));
        fprintf(stderr, "%s --!! Unknown signaling event %d\n", chan_stuff[chan].tag, uc_event2str(e->e), e->e);
        break;
    }
    /*endswitch*/
}
/*- End of function --------------------------------------------------------*/

static void *run_uc(void *arg)
{
    uc_t *uc;
    uc_event_t *e;
    struct timeval tv = {0,0};
    struct timeval *next;
    fd_set rfds;
    fd_set wfds;
    fd_set efds;
    int res;
    int dfd;
    int chan;
    int logging_level;

    chan = (int) (intptr_t) arg;

    dfd = chan_stuff[chan].fd;
    uc = uc_new(dfd, dfd, chan_stuff[chan].protocol_class, chan_stuff[chan].protocol_variant, chan_stuff[chan].protocol_end, 1);
    if (uc == NULL)
    {
        fprintf(stderr, "Unable to create instance\n");
        return NULL;
    }
    /*endif*/
    uc_set_signaling_callback(uc, handle_uc_event, (void *) (intptr_t) chan);
    uc_set_signaling_error_callback(uc, signaling_error, (void *) (intptr_t) chan);
    uc_set_channel_error_callback(uc, 0, channel_error, (void *) (intptr_t) chan);
    logging_level = UC_LOG_SEVERITY_MASK;
    logging_level |= (UC_LOG_SHOW_TAG | UC_LOG_SHOW_PROTOCOL);
    uc_set_logging(uc, logging_level, 1, chan_stuff[chan].tag);
    uc_call_control(uc, UC_OP_UNBLOCK, 0, (void *) -1);
    for (;;)
    {
        FD_ZERO(&rfds);
        FD_ZERO(&wfds);
        FD_ZERO(&efds);
        FD_SET(dfd, &rfds);
        FD_SET(dfd, &wfds);
        FD_SET(dfd, &efds);

        if ((next = uc_schedule_next(uc)))
        {
            gettimeofday(&tv, NULL);
            tv.tv_sec = next->tv_sec - tv.tv_sec;
            tv.tv_usec = next->tv_usec - tv.tv_usec;
            if (tv.tv_usec < 0)
            {
                tv.tv_usec += 1000000;
                tv.tv_sec -= 1;
            }
            /*endif*/
            if (tv.tv_sec < 0)
            {
                tv.tv_sec = 0;
                tv.tv_usec = 0;
            }
            /*endif*/
        }
        /*endif*/
        res = select(dfd + 1, &rfds, NULL, &efds, next  ?  &tv  :  NULL);
        if (res >= 0)
        {
            if (res == 0)
                uc_schedule_run(uc);
            /*endif*/
            while ((e = uc_check_event(uc)))
            {
                printf("Non-callback signaling event\n");
                handle_uc_event(uc, (void *) (intptr_t) chan, e);
            }
            /*endwhile*/
        }
        else if (errno != EINTR)
        {
            fprintf(stderr, "Error (%d) on select: %s\n", errno, strerror(errno));
        }
        /*endif*/
    }
    /*endfor*/
    return NULL;
}
/*- End of function --------------------------------------------------------*/

void increment_digit_string(char *buf)
{
    int i;
    
    i = strlen(buf);
    while (i > 0)
    {
        i--;
        if (buf[i] < '9')
        {
            buf[i]++;
            return;
        }
        buf[i] = '0';
    }
}
/*- End of function --------------------------------------------------------*/

int get_configuration(char *configuration)
{
    FILE *conf;
    char buf[133];
    char buf2[133];
    int value;
    int value2;
    int chan;
    int i;
    char originating_number[UC_MAXPHONENUMLEN + 1];
    char destination_number[UC_MAXPHONENUMLEN + 1];
    char protocol_class[80];
    char protocol_variant[80];
    int protocol_end;
    int caller_mode;
    int action_on_offered;
    
    chan = 0;
    if ((conf = fopen(configuration, "r")) == NULL)
        return -1;
    while (fgets(buf, 132, conf))
    {
        if (buf[0] == '#')
            continue;
        /*endif*/
        if (sscanf(buf, "protocol-class %s", protocol_class) == 1)
        {
        }
        else if (sscanf(buf, "protocol-variant %s", protocol_variant) == 1)
        {
        }
        else if (sscanf(buf, "protocol-end %s", buf2) == 1)
        {
            protocol_end = (strcmp(buf2, "cpe") == 0)  ?  UC_MODE_CPE  :  UC_MODE_CO;
        }
        else if (sscanf(buf, "caller %s", buf2) == 1)
        {
            caller_mode = (strcmp(buf2, "yes") == 0);
        }
        else if (sscanf(buf, "originating-no %s", originating_number) == 1)
        {
        }
        else if (sscanf(buf, "destination-no %s", destination_number) == 1)
        {
        }
        else if (sscanf(buf, "circuits %d-%d", &value, &value2) == 2)
        {
            for (i = value;  i <= value2;  i++)
            {
                chan_stuff[chan].chan_no = i;
                chan_stuff[chan].protocol_class = strdup(protocol_class);
                chan_stuff[chan].protocol_variant = strdup(protocol_variant);
                chan_stuff[chan].protocol_end = protocol_end;
                chan_stuff[chan].caller_mode = caller_mode;
                strcpy(chan_stuff[chan].originating_number, originating_number);
                strcpy(chan_stuff[chan].destination_number, destination_number);
                increment_digit_string(originating_number);
                increment_digit_string(destination_number);
                chan_stuff[chan].action_on_offered = action_on_offered;
                fprintf(stderr,
                        "Chan %d, class '%s', variant '%s', end %d, caller %d, from '%s' to '%s'\n",
                        chan_stuff[chan].chan_no,
                        chan_stuff[chan].protocol_class,
                        chan_stuff[chan].protocol_variant,
                        chan_stuff[chan].protocol_end,
                        chan_stuff[chan].caller_mode,
                        chan_stuff[chan].originating_number,
                        chan_stuff[chan].destination_number);
                chan++;
            }
        }
        else if (sscanf(buf, "on-offered %s", buf2) == 1)
        {
            if (strcmp(buf2, "accept") == 0)
                action_on_offered = OFFERED_ACTION_ACCEPT;
            else if (strcmp(buf2, "answer") == 0)
                action_on_offered = OFFERED_ACTION_ANSWER;
            else if (strcmp(buf2, "busy") == 0)
                action_on_offered = OFFERED_ACTION_BUSY;
            else if (strcmp(buf2, "unassigned") == 0)
                action_on_offered = OFFERED_ACTION_UNASSIGNED;
            else if (strcmp(buf2, "congested") == 0)
                action_on_offered = OFFERED_ACTION_CONGESTED;
            else if (strcmp(buf2, "oos") == 0)
                action_on_offered = OFFERED_ACTION_OOS;
            else if (strcmp(buf2, "random") == 0)
                action_on_offered = OFFERED_ACTION_RANDOM;
            else
                action_on_offered = OFFERED_ACTION_ACCEPT;
        }
        else
        {
            fprintf(stderr, "Invalid configuration file entry '%s'\n", buf);
            fclose(conf);
            return -1;
        }
    }
    fclose(conf);
    return 0;
}
/*- End of function --------------------------------------------------------*/

int main(int argc, char *argv[]) 
{
    pthread_attr_t attr;
    int chan;
    char dev_name[20];
    int j;
    int x;
    ZT_PARAMS p;

    if (argc < 2)
    {
        fprintf(stderr, "you did not specified a configuration file\n");
        fprintf(stderr, "Usage: testcall [config_file]\n");
        exit(1);
    }
    /*endif*/
    if (get_configuration(argv[1]) < 0)
    {
        fprintf(stderr, "Can't read the configuration file\n");
        exit(1);
    }
    /*endif*/
    uc_start();    
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
    /* Create and start a thread for each defined channel */
    for (chan = 0;  chan < MAX_TRUNKS;  chan++)
    {
        if (chan_stuff[chan].protocol_class == NULL)
            continue;
        /*endif*/
        sprintf(dev_name, "%d", chan_stuff[chan].chan_no);
        if ((chan_stuff[chan].sig_fd = uc_channel_open(chan_stuff[chan].protocol_class, chan_stuff[chan].protocol_variant, chan_stuff[chan].protocol_end, dev_name)) < 0)
        {
            fprintf(stderr, "Failed to open channel: %s\n", strerror(errno));
            exit(1);
        }
        /*endif*/
        chan_stuff[chan].fd = chan_stuff[chan].sig_fd;

        sprintf(dev_name, "Chan %3d:", chan_stuff[chan].chan_no);
        chan_stuff[chan].tag = strdup(dev_name);
        printf("Thread for channel %d\n", chan);
        if (pthread_create(&chan_stuff[chan].thread, &attr, run_uc, (void *) (intptr_t) chan))
            exit(2);
        /*endif*/
    }
    /*endfor*/
    for (;;)
    {
        usleep(5000000);
        printf("Main thread\n");
    }
    /*endfor*/

    return 0;
}
/*- End of function --------------------------------------------------------*/
/*- End of file ------------------------------------------------------------*/

