Rename 'cvs2cl.pl' to the more common 'cvs2cl'.
[mdsms.git] / mdsms.c
diff --git a/mdsms.c b/mdsms.c
index a630131..757124d 100644 (file)
--- a/mdsms.c
+++ b/mdsms.c
@@ -1,3 +1,4 @@
+#define WANT_DECLARATIONS 1
 #include "config.h"
 #ifndef lint
 static char rcsid[] ATTR_UNUSED = "$Id$";
@@ -38,6 +39,9 @@ static char rcsid[] ATTR_UNUSED = "$Id$";
 #ifdef HAVE_SYS_TYPES_H
 #include <sys/types.h>
 #endif
+#ifdef HAVE_SYS_WAIT_H
+#include <sys/wait.h>
+#endif
 #ifdef HAVE_SYS_STAT_H
 #include <sys/stat.h>
 #endif
@@ -59,6 +63,9 @@ static char rcsid[] ATTR_UNUSED = "$Id$";
 #ifdef HAVE_LOCALE_H
 #include <locale.h>
 #endif
+#ifdef HAVE_STDDEF_H
+#include <stddef.h>
+#endif
 
 #ifdef HAVE_GETOPT_LONG
 #include <getopt.h>
@@ -66,6 +73,13 @@ static char rcsid[] ATTR_UNUSED = "$Id$";
 #include "getopt.h"
 #endif
 
+
+/* Always override possible system defintions as it is safe (used by glib) */
+#undef MAX
+#define MAX(a,b) ((a)>(b)?(a):(b))
+#undef MIN
+#define MIN(a,b) ((a)<(b)?(a):(b))
+
 #define NELEM(x) (sizeof((x))/sizeof(*(x)))
 
 #ifndef DEBUG
@@ -96,9 +110,29 @@ static int verbose
 static char *pname;
 static int dis_cleanup=0,devfd=-1;
 
-static char *phone,*device,*logname,*lockfile,*smsc,*maxretry,*readtime,*chartime,*cmdtime,*baud,*restore;
+static char *phone,*device,*logname,*lockfile,*smsmode,*pdusmscmode,*smsc,*maxretry,*readtime,*chartime,*cmdtime,*waittime,*baud,*restore;
 static int readbody;
-static long maxretryn=DEF_MAXRETRY,readtimen=-1,chartimen=DEF_CHARTIME,cmdtimen=DEF_CMDTIME,baudn=DEF_BAUD;
+static long maxretryn=DEF_MAXRETRY,readtimen=-1,chartimen=DEF_CHARTIME,cmdtimen=DEF_CMDTIME,waittimen=DEF_WAITTIME,baudn=DEF_BAUD;
+#ifdef HAVE_CRTSCTS
+static int handshake_rtscts;
+static unsigned handshake_stamp;
+#else
+#define handshake_rtscts (0)
+#endif
+static enum {
+       FSM_AUTO=0,
+       FSM_PDU,
+       FSM_TEXT
+       } force_smsmode=FSM_AUTO;
+static enum {
+       FPSM_AUTO=0,
+       FPSM_COUNT_IN,
+       FPSM_COUNT_OUT,
+       FPSM_NONE
+       } force_pdusmscmode=FPSM_AUTO,
+#define FPSM_MIN (FPSM_COUNT_IN)
+#define FPSM_MAX (FPSM_NONE)
+               try_pdusmscmode=FPSM_MIN;
 static size_t bodylen;
 /* --send / --send-mobildock / --receive specific */
 static char *body;
@@ -106,6 +140,8 @@ static char *body;
 static char *logoname,*gsmnet;
 /* --ring-send specific */
 static char *ringname;
+/* --picture-send specific */
+static char *picturename;
 
 static enum modenum {
   MODE_UNKNOWN=0,
@@ -115,7 +151,8 @@ static enum modenum {
        MODE_SEND_MOBILDOCK=MODE_FIRST+1, /* --send-mobildock in before readtimen is set */
        MODE_RECEIVE       =MODE_FIRST+2, /* --receive */
        MODE_LOGO_SEND     =MODE_FIRST+3, /* --logo-send */
-       MODE_RING_SEND     =MODE_FIRST+4  /* --ring-send */
+       MODE_RING_SEND     =MODE_FIRST+4, /* --ring-send */
+       MODE_PICTURE_SEND  =MODE_FIRST+5  /* --picture-send */
        } mode=MODE_UNKNOWN;
 #define MODE_ORDER(x) ((x)-MODE_FIRST)
 #define MODE_NAME(x) (longopts[MODE_ORDER((x))].name)
@@ -235,11 +272,13 @@ static void usage(void)
 %s\
 \n\
 Usage: %s [-c|--config <cfgfile>] [-d|--device <device>]\n\
-             {--send | --send-mobildock | --receive | --logo-send}\n\
-             [-L|--log <file>] [-b|--baud <rate>]\n\
-             [-l|--lockfile <lock>] [-s|--smsc <smsc #>] [-m|--maxretry <#>]\n\
+             [-L|--log <file>] [-l|--lockfile <lock>]\n\
+             [-b|--baud <rate>] [-x|--xonxoff] [-C|--rtscts]\n\
+             [-M|--smsmode <mode>] [-P|--pdusmscmode <mode>]\n\
+             [-s|--smsc <smsc #>] [-m|--maxretry <#>]\n\
              [-r|--readtime <sec>] [-t|--chartime <msec>] [-T|--cmdtime <msec>]\n\
-             [-v|--verbose] [-h|--help] [-V|--version]\n\
+             [-w|--waittime <sec>] [-v|--verbose] [-h|--help] [-V|--version]\n\
+             {--send | --send-mobildock | --receive | --logo-send}\n\
   --send / --send-mobildock:\n\
              [-f|--file] <dest. phone> <msg text|msg filename>\n\
   --receive:\n\
@@ -248,14 +287,20 @@ Usage: %s [-c|--config <cfgfile>] [-d|--device <device>]\n\
              <dest. phone> <logo filename> [<GSMnet id>]\n\
   --ring-send:\n\
              <dest. phone> <ring filename>\n\
+  --picture-send:\n\
+             <dest. phone> <picture .ras filename>\n\
 \n\
  -c, --config\tRead this additional config file\n\
 \t\t(def. \"%s\" and \"$HOME%s\")\n\
  -d, --device\tMobile on this serial device (def. \"%s\")\n\
  -L, --log\tLog all important messages to this file (def. \"%s\")\n\
- -b, --baud\tSet baudrate, 2400-57600 supported (def. %d)\n\
  -l, --lockfile\tLock serial port by this file, \"%%s\" is basename of device\n\
 \t\t(def. \"%s\")\n\
+ -b, --baud\tSet baudrate, 2400-57600 supported (def. %d)\n\
+ -x, --xonxoff\tUse XON/XOFF (AKA software) serial port handshaking - default\n\
+ -C, --rtscts\tUse RTS/CTS (AKA hardware) serial port handshaking%s\n\
+ -M, --smsmode\tForce SMS as: \"pdu\" or 0: PDU mode, \"text\" or 1: text mode\n\
+ -P, --pdusmscmode\tForce PDU as: \"count-in\", \"count-out\", \"none\"\n\
  -s, --smsc\tUse this SMS Center number (def. query from mobile)\n\
  -m, --maxretry\tMaximum retries of any command before giving up (def. %d)\n\
  -r, --readtime\tSeconds for maximum wait time for response\n\
@@ -263,6 +308,7 @@ Usage: %s [-c|--config <cfgfile>] [-d|--device <device>]\n\
 \t\t multiplied %dx for long cmds)\n\
  -t, --chartime\tMilliseconds between each char (def. %dms)\n\
  -T, --cmdtime\tMilliseconds before each whole AT command (def. %dms)\n\
+ -w, --waittime\tSeconds to prevent timeout of 9110 FaxModem (def. %ds)\n\
  -v, --verbose\tIncrease verbosity level, more \"-v\"s give more messages\n\
  -h, --help\tPrint a summary of the options\n\
  -V, --version\tPrint the version number\n\
@@ -283,9 +329,14 @@ Usage: %s [-c|--config <cfgfile>] [-d|--device <device>]\n\
 \t\t* Group gfx : Specify \"%s\" to send logo as group graphics\n\
 \n\
 You may need to use the following line to catch all of this help text:\n\
-./mdsms 2>&1|more\n\
-\n"),version,PACKAGE,CONFIG_MAIN,CONFIG_HOME,DEF_DEVICE,DEF_LOGNAME,DEF_BAUD,DEF_LOCKFILE,DEF_MAXRETRY,
-DEF_READTIME,DEF_READTIME_MOBILDOCK,EXT_READTIME,DEF_CHARTIME,DEF_CMDTIME,
+./mdsms -h 2>&1|more\n\
+\n"),version,PACKAGE,CONFIG_MAIN,CONFIG_HOME,DEF_DEVICE,DEF_LOGNAME,DEF_LOCKFILE,DEF_BAUD,
+#ifdef HAVE_CRTSCTS
+               "",
+#else
+               _("\n\t\t(Not supported on this platform!)"),
+#endif
+DEF_MAXRETRY,DEF_READTIME,DEF_READTIME_MOBILDOCK,EXT_READTIME,DEF_CHARTIME,DEF_CMDTIME,DEF_WAITTIME,
 WORD_NET,WORD_GROUP);
        exit(EXIT_FAILURE);
 }
@@ -297,26 +348,34 @@ static const struct option longopts[]={
 {"receive"       ,0,0,MODE_RECEIVE},
 {"logo-send"     ,0,0,MODE_LOGO_SEND},
 {"ring-send"     ,0,0,MODE_RING_SEND},
+{"picture-send"  ,0,0,MODE_PICTURE_SEND},
 /* Mode aliases may follow in no particular order *
  * as long as no non-mode options is between them */
 {"send-md"       ,0,0,MODE_SEND_MOBILDOCK},
 {"recv"          ,0,0,MODE_RECEIVE},
 {"logo"          ,0,0,MODE_LOGO_SEND},
 {"ring"          ,0,0,MODE_RING_SEND},
-{"config"  ,1,0,'c'},
-{"device"  ,1,0,'d'},
-{"log"     ,1,0,'L'},
-{"baud"    ,1,0,'b'},
-{"lockfile",1,0,'l'},
-{"smsc"    ,1,0,'s'},
-{"maxretry",1,0,'m'},
-{"readtime",1,0,'r'},
-{"chartime",1,0,'t'},
-{"cmdtime" ,1,0,'T'},
-{"file"    ,0,0,'f'},
-{"verbose" ,0,0,'v'},
-{"help"    ,0,0,'h'},
-{"version" ,0,0,'V'}};
+{"picture"       ,0,0,MODE_PICTURE_SEND},
+{"config"      ,1,0,'c'},
+{"device"      ,1,0,'d'},
+{"log"         ,1,0,'L'},
+{"lockfile"    ,1,0,'l'},
+{"baud"        ,1,0,'b'},
+{"xonxoff"     ,0,0,'x'},
+{"rtscts"      ,0,0,'C'},
+{"smsmode"     ,1,0,'M'},
+{"pdusmscmode" ,1,0,'P'},
+{"smsc"        ,1,0,'s'},
+{"maxretry"    ,1,0,'m'},
+{"readtime"    ,1,0,'r'},
+{"chartime"    ,1,0,'t'},
+{"cmdtime"     ,1,0,'T'},
+{"waittime"    ,1,0,'w'},
+{"file"        ,0,0,'f'},
+{"verbose"     ,0,0,'v'},
+{"help"        ,0,0,'h'},
+{"version"     ,0,0,'V'},
+{NULL          ,0,0,0  }};
 
 static void processargs(int argp,char **args,const char *from);
 
@@ -512,15 +571,18 @@ static struct {
        char **const var;
        unsigned stamp;
        } optset[]={
-               { 'd',&device   },
-               { 'L',&logname  },
-               { 'b',&baud     },
-               { 'l',&lockfile },
-               { 's',&smsc     },
-               { 'm',&maxretry },
-               { 'r',&readtime },
-               { 't',&chartime },
-               { 'T',&cmdtime  },
+               { 'd',&device       },
+               { 'L',&logname      },
+               { 'l',&lockfile     },
+               { 'b',&baud         },
+               { 'M',&smsmode      },
+               { 'P',&pdusmscmode  },
+               { 's',&smsc         },
+               { 'm',&maxretry     },
+               { 'r',&readtime     },
+               { 't',&chartime     },
+               { 'T',&cmdtime      },
+               { 'w',&waittime     },
        };
 
 static void processargs(int argp,char **args,const char *from)
@@ -531,7 +593,7 @@ int i;
 
        seq++;
        optarg=NULL; optind=0; /* FIXME: Possible portability problem. */
-       while ((optc=getopt_long(argp,args,"c:d:L:b:l:s:m:r:t:T:fvhV",longopts,NULL))!=EOF) switch (optc) {
+       while ((optc=getopt_long(argp,args,"c:d:L:l:b:xCM:P:s:m:r:t:T:w:fvhV",longopts,NULL))!=EOF) switch (optc) {
                case 'c':
                        if (cfgstacki>=NELEM(cfgstack)) {
                                error(_("Looping (%d) during attempt to read config file \"%s\", break-out"),NELEM(cfgstack),from);
@@ -539,7 +601,7 @@ int i;
                                }
                        chk(cfgstack[cfgstacki++]=strdup(optarg));
                        break;
-               case 'd': case 'L': case 'b': case 'l': case 's': case 'm': case 'r': case 't': case 'T':
+               case 'd': case 'L': case 'b': case 'l': case 'M': case 'P': case 's': case 'm': case 'r': case 't': case 'T': case 'w':
                        for (i=0;i<NELEM(optset);i++)
                                if (optset[i].c==optc) {
                                        if (optset[i].stamp && optset[i].stamp!=seq) {
@@ -553,11 +615,22 @@ int i;
                                        }
                        assert(i<NELEM(optset));
                        break;
+               case 'x': case 'C':
+#ifdef HAVE_CRTSCTS
+                       if (handshake_stamp && handshake_stamp!=seq) break;
+                       handshake_rtscts=(optc=='C');
+                       handshake_stamp=seq;
+#else
+                       if (optc=='C')
+                               error(_("!RTS/CTS handshake NOT supported on this platform! Occured during parsing option %d from \"%s\""),optind-1,from);
+#endif
+                       break;
                case MODE_SEND:
                case MODE_SEND_MOBILDOCK:
                case MODE_RECEIVE:
                case MODE_LOGO_SEND:
                case MODE_RING_SEND:
+               case MODE_PICTURE_SEND:
                        if (mode_stamp && mode_stamp!=seq) break;
                        mode=optc;
                        mode_stamp=seq;
@@ -566,7 +639,9 @@ int i;
                        readbody++;
                        break;
                case 'v':
+#ifndef DEBUG  /* prevent suppositious overflow */
                        verbose++;
+#endif
                        break;
                case 'V':
                        fprintf(stderr,version);
@@ -593,10 +668,15 @@ static const struct nullcheck {
        enum modenum reqd;
        const char *name;
        } nullcheck[]={
-               {&phone,MODE_BIT(MODE_SEND)|MODE_BIT(MODE_SEND_MOBILDOCK)|MODE_BIT(MODE_LOGO_SEND),
+               {&phone,MODE_BIT(MODE_SEND)
+                      |MODE_BIT(MODE_SEND_MOBILDOCK)
+                      |MODE_BIT(MODE_LOGO_SEND)
+                      |MODE_BIT(MODE_RING_SEND)
+                      |MODE_BIT(MODE_PICTURE_SEND),
                        N_("destination phone number")},
-               {&logoname,MODE_BIT(MODE_LOGO_SEND),N_("logo filename")},
-               {&ringname,MODE_BIT(MODE_RING_SEND),N_("ring filename")},
+               {&   logoname,MODE_BIT(   MODE_LOGO_SEND),N_(   "logo filename")},
+               {&   ringname,MODE_BIT(   MODE_RING_SEND),N_(   "ring filename")},
+               {&picturename,MODE_BIT(MODE_PICTURE_SEND),N_("picture filename")},
                {&body,MODE_BIT(MODE_RECEIVE),N_("body text")}, /* we allow empty bodies for SENDs */
 #if 0
                {&gsmnet,MODE_BIT(MODE_LOGO_SEND),N_("GSM operator network code")},
@@ -720,13 +800,19 @@ static inline void cmdline_ring_send(void)
        if (!ringname) ringname=nextargstack();
 }
 
+static inline void cmdline_picture_send(void)
+{
+       cmdline_phone();
+       if (!picturename) picturename=nextargstack();
+}
+
 static void lockclose(int fd)
 {
        if (close(fd))
                error(_("Error closing lockfile \"%s\""),lockreal);
 }
 
-static inline int lockdevice(int attempt)
+static int lockdevice(int attempt)
 {
 int fd=-1;
 char buf[64];
@@ -811,10 +897,11 @@ static char state=-1;
        state=yes;
 }
 
-static const char *record;
+static const char *record,*recordend;
 static char *catchdata;
 static size_t catchdatal,catchdatasiz;
 
+static const char *reform(const char *s,int slot);
 static void catched(const char *end,char edata)
 {
 size_t len;
@@ -832,18 +919,19 @@ const char *p;
                memcpy(catchdata+catchdatal,record,len);
                catchdatal+=len;
                }
-       record=(p?NULL:end);
+       record   =(p?NULL:end);
+       recordend=(p?p   :end);
        assert(catchdatal<=catchdatasiz);
 }
 
 static int retrycnt=0;
 static void retrying(void)
 {
-       if (maxretryn>=0 && ++retrycnt>maxretryn) error(_("!Maximum command retry count (%ld) exceeded"),maxretryn);
+       if (maxretryn>=0 && ++retrycnt>=maxretryn) error(_("!Maximum command retry count (%ld) exceeded"),maxretryn);
        if (verbose>=2) error(_(".Retrying phase, %d out of %ld.."),retrycnt,maxretryn);
 }
 
-static char *reform(const char *s,int slot)
+static const char *reform(const char *s,int slot)
 {
 static struct formslot {
        char *s;
@@ -880,6 +968,8 @@ off_t o=d-fs->s;
        return(fs->s);
 }
 
+static char devcmd_empty_return='\0'; /* returned as catch when only newlines found */
+
 static char *devcmd(const char *term,const char *catch,const char *send,...) ATTR_PRINTFORMAT(3,4);
 static char *devcmd(const char *term,const char *catch,const char *send,...)
 {
@@ -889,21 +979,27 @@ static size_t bufl;
 ssize_t got;
 char *hit,*s;
 va_list ap;
-char errout,extend,noconvcr,edata;
+char errout,extend,catch_any,edata;
 long alarmtime;
 const char *osend;
 static const char emptystring[]="";
+size_t discard;
 
        if (!term) term="\nOK\n";
        if (!strcmp(send," ")) send=NULL; /* GCC formatstring-check workaround */
+       if (verbose>=2) error(_(".devcmd(sendfmt=%s,term=%s,catch=%s)"),
+               reform(send,0),reform(term,1),reform(catch,2));
        if (!(osend=send)) send="";
-       if ((noconvcr=(catch && *catch=='@'))) catch++;
+       if ((catch_any=(catch && !strcmp(catch,"@")))) catch=NULL;
        if ((errout=(*send=='!'))) send++;
        errout|=(maxretryn==-1);
        if ((extend=(*send=='~'))) send++;
        alarmtime=readtimen*(extend?EXT_READTIME:1);
-       d8("devcmd(), alarmtime=%ld, errout=%d, extend=%d, noconvcr=%d, osend=%p, bufl=%d, buf: %s\n",
-               alarmtime,errout,extend,noconvcr,osend,bufl,reform(buf,0));
+       buf[bufl]='\0'; /* for d8() below */
+       d8("devcmd(), alarmtime=%ld, errout=%d, extend=%d, catch_any=%d, osend=%p, bufl=%d, buf: %s\n",
+               alarmtime,errout,extend,catch_any,osend,bufl,reform(buf,0));
+       assert(!catch || !strchr(catch,'\r')); /* we are no longer supporting 'noconvcr'! */
+       assert(!term  || !strchr(term ,'\r'));
        if (0) {
 err:
                alarm(0);
@@ -918,8 +1014,7 @@ err:
                l=VARVPRINTF(buf,send,ap); bufl=l+(!!osend);
                va_end(ap);
                if (bufl>=sizeof(buf)-1) error(_("!Command too big (%d>%d)"),bufl,sizeof(buf)-1);
-               if (verbose>=2) error(_(".devcmd(send=%s,term=%s,catch=%s,timeout=%ld)"),
-                       reform(buf,0),reform(term,1),reform(catch,2),alarmtime);
+               if (verbose>=2) error(_(".devcmd formatted send=%s%s"),reform(buf,0),(osend?"+\"\\r\"":""));
                if (osend) buf[l]='\r';
                for (offs=0,got=0;offs<bufl;offs++) {
                        alarm(MAXSENDTIME);
@@ -939,7 +1034,7 @@ err:
                }
 
        if (!(terml=strlen(term))) {
-               assert(!catch);
+               assert(!catch); assert(!catch_any);
                return(NULL);
                }
        if (catch) {
@@ -948,13 +1043,12 @@ err:
                }
        else fragl=terml;
        fragl=MAX(fragl,MAX(strlen(ERROR_SUBSTR1),strlen(ERROR_SUBSTR2)));
-       record=NULL;
+       record=recordend=NULL;
        wasalarm=0;
        alarm(alarmtime);
-       edata=(noconvcr?'\r':'\n');
+       edata='\n';
        if (!osend) {
-               got=bufl;
-               bufl=0;
+               /* "bufl" important */
                goto skipread;
                }
        for (;;) {
@@ -967,22 +1061,30 @@ err:
                        got=read(devfd,buf+bufl,1);
                        }
                if (got<=0) {
+                       buf[bufl]='\0'; /* for strspn() below */
+                       if (!strcmp(term,"\n") && catch /* written to trap on 'devcmd("\n","+CMT:"," ")' */
+                           && bufl==strspn(buf,"\n" /* accept */)) { /* only newlines found */
+                               if (verbose>=2)
+                                       error(_(".Blank (%d newlines) input read, ignoring it"),bufl);
+                               bufl=0; /* discard newlines */
+                               return(&devcmd_empty_return);
+                               }
                        if (wasalarm) error(_("Maximum response timeout (%lds) exceeded"),alarmtime);
                        else error(_("^Couldn't read device data (ret=%d)"),got);
                        goto err;
                        }
-skipread:
                bufl2=bufl+got;
                buf[bufl2]='\0';
                s=buf+bufl;
                while (buf+bufl2>s && (s=memchr(s,'\0',buf+bufl2-s))) *s++=REPL_NULLCHAR;
                if (verbose>=3)
                        error(_("\nGot chunk of data from device: %s"),reform(buf+bufl,0));
-               if (!noconvcr) {
+               /* convert CR */ {
                        s=buf+bufl;
                        while (buf+bufl2>s && (s=memchr(s,'\r',buf+bufl2-s))) *s++='\n';
                        }
                bufl=bufl2;
+skipread:
                catched(buf+bufl,edata); assert(!record || record==buf+bufl);
                assert(bufl<sizeof(buf)-1);
                buf[bufl]='\0';
@@ -992,25 +1094,34 @@ skipread:
                        error(_("Found ERROR response on command %s"),reform(send,0));
                        goto err;
                        }
-               if (catch && !record && bufl>=catchl && (hit=strstr(buf,catch))) {
+/* "record" may get NULLed here after successful 'catch'
+ * but "recordend" will never be NULLed
+ */
+               if (catch && !recordend && bufl>=catchl && (hit=strstr(buf,catch))) {
                        record=hit+catchl;
                        catched(buf+bufl,edata); assert(!record || record==buf+bufl);
                        }
-               if (         bufl>= terml && (hit=strstr(buf,term))) {
+               if (catch_any && !recordend && buf[discard=strspn(buf,"\n" /* accept */)]) {
+                       record=buf+discard;
+                       catched(buf+bufl,edata); assert(!record || record==buf+bufl);
+                       }
+               if (((!catch && !catch_any) || catchdatal) && bufl>= terml
+                   && (hit=strstr((recordend?recordend:buf),term))) {
                        memmove(buf,hit+terml,(bufl2=(buf+bufl)-(hit+terml))); bufl=bufl2;
                        break;
                        }
                if (bufl<fragl) continue;
-               memmove(buf,buf+bufl-(fragl-1),(bufl2=fragl-1)); bufl=bufl2;
-               if (record) record=buf+fragl-1;
+               memmove(buf,buf+bufl-(fragl-1),(bufl2=fragl-1));
+               if (record   ) record-=bufl-bufl2;
+               if (recordend) recordend-=bufl-bufl2;
+               bufl=bufl2;
                }
        alarm(0);
        if (!catchdatal) {
-               if (!catch) return("");
-               error(_("Data requested on command %s but no found after term %s"),reform(send,0),reform(term,1));
-               goto err;
+               assert(!catch && !catch_any);
+               return("");
                }
-       assert(!!catch);
+       assert(!!catch || catch_any);
        record=emptystring;
        catched(record+1,edata);
        if (verbose>=2) error(_(".Returning data %s for cmd %s"),reform(catchdata,0),reform(send,1));
@@ -1060,7 +1171,6 @@ static inline void textconv(char *d,unsigned char *s,size_t len)
 static inline void smscset(void)
 {
 char *s,*t,*e,*serr;
-long l;
 unsigned char bin[2+(MAXNUMLEN+1)/2];
 
        if (smsc) devcmd(NULL,NULL,"\r\nAT+CSCA=\"%s\"",smsc);
@@ -1069,19 +1179,22 @@ unsigned char bin[2+(MAXNUMLEN+1)/2];
        if (!*s || !strcmp(s,"EMPTY"))
                error(_("!No SMSC set in mobile station found, please use option \"-s\""));
        if (verbose>=1) error(_("\nFound default SMSC in mobile: %s"),s);
-       if (*s!='"') error(_("!No left-quote found in: %s"),s);
-       if (!(t=strrchr(s+1,'"'))) error(_("!No right-quote found in: %s"),s);
-       if (s+1==t)
+       if (*s++!='"') error(_("!No left-quote found in: %s"),s);
+       if (!(t=strrchr(s,'"'))) error(_("!No right-quote found in: %s"),s);
+       if (s==t)
                error(_("!No SMS set in mobile station found, please use option \"-s\""));
        e=t++;
        while (isspace(*t)) t++;
-       if (*t++!=',') error(_("!No comma found after quotes in: %s"),s);
-       while (isspace(*t)) t++;
-       l=strtol(t,&serr,10);
-       if ((l!=ADDR_NAT && l!=ADDR_INT) || (serr && *serr))
-               error(_("!Type parse error in: %s"),s);
-       if (l==ADDR_NAT || s[1]=='+') s++;
-       else *s='+';
+       if (*t) {
+long l;
+
+               if (*t++!=',') error(_("!No comma found after quotes in: %s"),s);
+               while (isspace(*t)) t++;
+               l=strtol(t,&serr,10);
+               if ((l!=ADDR_NAT && l!=ADDR_INT) || (serr && *serr))
+                       error(_("!Type parse error in: %s"),s);
+               if (l==ADDR_INT && *s!='+') *--s='+';
+               }
        *e='\0';
        if (verbose>=2) error(_("\nDecoded SMSC address: %s"),s);
        if (!NEED_PDUSMSC()) return;
@@ -1151,7 +1264,7 @@ unsigned char bin[140]={
        0x05, /* IEI */
        0x04, /* IEDL */
        0x15, 0x83, /* dest port (group gfx) */
-       0x00, 0x00  /* src port (unused) */
+       0x15, 0x83  /* src port (unused) */
        };
 size_t got,r=0 /* GCC happiness */,w;
 ssize_t chars,bits;
@@ -1256,19 +1369,19 @@ long size;
 
 #define WORD(n) (((unsigned char)buf[(n)])|(((unsigned char)buf[(n)+1])<<8))
 
-       if (!(f=fopen(logoname,"rb")))
-               error(_("^!Cannot open ring file \"%s\" for r/o"),logoname);
-       if ((size=getfilesize(f,logoname))==-1)
+       if (!(f=fopen(ringname,"rb")))
+               error(_("^!Cannot open ring file \"%s\" for r/o"),ringname);
+       if ((size=getfilesize(f,ringname))==-1)
                error(_("!File size determination is essential to continue operation"));
        if (size<0x103)
                error(_("!File \"%s\" size %ld too small (must >=0x103)! Is it .000 file?"),
-                       logoname,size);
+                       ringname,size);
        if (fseek(f,0x100,SEEK_SET))
-               error(_("^Seeking error on \"%s\", ignoring"),logoname);
+               error(_("^Seeking error on \"%s\", ignoring"),ringname);
        size-=0x100;
        if (size<=BIN1_PAYLOAD) {
                if ((got=fread(bin1+7,1,size,f))!=size)
-                       error(_("^Read error on \"%s\", wanted %ld, got %d"),logoname,size,got);
+                       error(_("^Read error on \"%s\", wanted %ld, got %d"),ringname,size,got);
                error(_("\nSending ring tone \"%s\" as single SMS (size %ld, max %d)"),
                        ringname,size,BIN1_PAYLOAD);
                nokiaprep(bin1,7+size);
@@ -1289,12 +1402,97 @@ long size;
                        binn[11]=fragn;
                        want=MIN(size,BINN_PAYLOAD);
                        if ((got=fread(binn+12,1,want,f))!=want)
-                               error(_("^Read error on \"%s\", wanted %d, got %d"),logoname,want,got);
+                               error(_("^Read error on \"%s\", wanted %d, got %d"),ringname,want,got);
                        nokiaprep(binn,12+want);
                        size-=want;
                        }
                }
-       chkfclose(f,logoname);
+       chkfclose(f,ringname);
+#undef WORD
+}
+
+#define PICTURE_WIDTH  (72)
+#define PICTURE_HEIGHT (28)
+
+static inline void pictureread(void)
+{
+FILE *f;
+unsigned char bin1[140]={
+       6, /* UDH length */
+       0x05, /* IEI */
+       0x04, /* IEDL */
+       0x15, 0x8A, /* dest port (ring tones) */
+       0x15, 0x8A  /* src port (unused) */
+#define BIN1_PAYLOAD (140-7)
+       };
+unsigned char binn[140]={
+       11, /* UDH length */
+       0x05, /* IEI */
+       0x04, /* IEDL */
+       0x15, 0x8A, /* dest port (ring tones) */
+       0x15, 0x8A, /* src port (unused) */
+       0x00, 0x03, /* multipart */
+       /* 0x??, unique serial ID */
+       /* 0x??, total messages */
+       /* 0x??, message number (# from 1) */
+#define BINN_PAYLOAD (140-12)
+       };
+unsigned char header[]={
+       0x30,   /* version string '0' */
+       0x02,   /* item=OTA bitmap */
+#define PICTURE_BYTES ((PICTURE_WIDTH*PICTURE_HEIGHT+7)/8)
+#define PICTURE_BYTES_INCL_HEADER (PICTURE_BYTES +4/*header*/)
+       PICTURE_BYTES_INCL_HEADER>>8,PICTURE_BYTES_INCL_HEADER&0xFF,    /* picture size in bytes incl. header */
+       0x00, /* animation pictures - 0=static picture */
+       PICTURE_WIDTH,PICTURE_HEIGHT,   /* picture size in pixels */
+       0x01,   /* picture depth - B/W */
+       };
+size_t got,want;
+int totn,fragn;
+long size;
+
+#define WORD(n) (((unsigned char)buf[(n)])|(((unsigned char)buf[(n)+1])<<8))
+
+       if (!(f=fopen(picturename,"rb")))
+               error(_("^!Cannot open picture file \"%s\" for r/o"),picturename);
+       if ((size=getfilesize(f,picturename))==-1)
+               error(_("!File size determination is essential to continue operation"));
+       if (size!=PICTURE_BYTES)
+               error(_("!File \"%s\" size %ld doesn't match .res size for %dx%d picture"),
+                       picturename,size,PICTURE_WIDTH,PICTURE_HEIGHT);
+       if (size<=BIN1_PAYLOAD-sizeof(header)) {
+               memcpy(bin1+7,header,sizeof(header));
+               if ((got=fread(bin1+7+sizeof(header),1,size,f))!=size)
+                       error(_("^Read error on \"%s\", wanted %ld, got %d"),picturename,size,got);
+               error(_("\nSending picture \"%s\" as single SMS (size %ld, max %d)"),
+                       picturename,size,BIN1_PAYLOAD-sizeof(header));
+               nokiaprep(bin1,7+sizeof(header)+size);
+               }
+       else {
+               memcpy(binn+12,header,sizeof(header));
+               totn=(sizeof(header)+size+BINN_PAYLOAD-1)/BINN_PAYLOAD;
+               if (totn>0xFF)
+                       error(_("!File size %ld too large even for multi-SMS picture upload (max=%d)"),
+                               size,BINN_PAYLOAD*0xFF-sizeof(header));
+               binn[10]=totn;
+               if (verbose>=1)
+                       error(_("\nSending picture \"%s\" as %d multi-SMSes (size %ld, max %d, frag %d, header %d)"),
+                               picturename,totn,size,BIN1_PAYLOAD,BINN_PAYLOAD,sizeof(header));
+               binn[9]=time(NULL)&0x100; /* rand() would be better but it is a compatibility pain */
+               if (verbose>=1)
+                       error(_("\nUsing unique multi-SMS ID 0x%02X"),(unsigned)binn[9]);
+               for (fragn=1;fragn<=totn;fragn++) {
+size_t isheader=(fragn==1 ? sizeof(header) : 0);
+
+                       binn[11]=fragn;
+                       want=MIN(size,BINN_PAYLOAD-isheader);
+                       if ((got=fread(binn+12+isheader,1,want,f))!=want)
+                               error(_("^Read error on \"%s\", wanted %d, got %d"),picturename,want,got);
+                       nokiaprep(binn,12+isheader+want);
+                       size-=want;
+                       }
+               }
+       chkfclose(f,picturename);
 #undef WORD
 }
 
@@ -1378,7 +1576,7 @@ char *finame;
                }
 }
 
-static int datawait(char immed)
+static int datawait(int timeout)
 {
 int i;
 #ifdef HAVE_POLL
@@ -1389,13 +1587,14 @@ fd_set rfds,xfds;
 
        assert(devfd>=0);
 retry:
-       errno=0;
-
+       if (timeout && verbose>=2)
+               error(_(".Waiting for device incoming data.."));
 #ifdef HAVE_POLL
        ufd.fd=devfd;
        ufd.events=POLLIN;
        ufd.revents=0;
-       i=poll(&ufd,1,(immed?0:-1));
+       errno=0;
+       i=poll(&ufd,1,timeout*1000);
 #else /* HAVE_POLL */
 #ifdef HAVE_FD_SETSIZE
        if (devfd>=FD_SETSIZE)
@@ -1404,9 +1603,12 @@ retry:
 #endif /* HAVE_FD_SETSIZE */
        FD_ZERO(&rfds); FD_SET(devfd,&rfds);
        FD_ZERO(&xfds); FD_SET(devfd,&xfds);
+       errno=0;
        i=select(devfd+1,&rfds,NULL,&xfds,NULL);
 #endif /* HAVE_POLL */
-       if (immed && i==0) return(0);
+       if (i==0) return(0);
+       if (i==-1 && errno==EINTR)
+               goto retry; /* silent retry, for example SIGCHLD could occur */
        if (i!=1)
                error(_("^Failed (retval %d) while waiting for data, ignoring"),i);
 
@@ -1432,8 +1634,8 @@ retry:
 static char *check_format(const char *fmt,const char *string)
 {
 static char err[LINE_MAX],sub[50];
-char *subp,cf,cs;
-const char *sf,*ss;
+char cf,cs;
+const char *sf,*ss,*subp;
 
        for (sf=fmt,ss=string;(cf=*sf) && (cs=*ss);sf++,ss++) {
                subp=NULL;
@@ -1508,6 +1710,7 @@ int i;
        tm.tm_mon--;
        d7("mktime(y%dm%dd%dh%dm%ds%d)\n",
                tm.tm_year,tm.tm_mon,tm.tm_mday,tm.tm_hour,tm.tm_min,tm.tm_sec);
+       tm.tm_isdst=-1; /* "timezone" info not available */
        if ((receive_time=mktime(&tm))==-1)
                error(_("^mktime(3) failed for %s"),string);
 }
@@ -1543,13 +1746,27 @@ int i;
        memset(&tm,0,sizeof(tm)); /* may be redundant */
        for (i=0;i<NELEM(timeparse);i++)
                GETTIME(i)=DIGIT2ASC(s+timeparse[i].strpos);
-       if (tm.tm_year<70) tm.tm_year+=100;
-       tm.tm_mon--;
        maketime(s+2);
        return(1);
 #undef DIGIT2ASC
 }
 
+static void signal_chld(int signo)
+{
+int status;
+pid_t pid;
+
+       signal(SIGCHLD,(RETSIGTYPE (*)(int))signal_chld);
+       /* we don't care about siginterrupt(3) as it doesn't matter how it is set */
+
+       d2("signal_chld: signo=%d\n",signo);
+       while (0<(pid=waitpid(-1 /* ANY process */,&status,WNOHANG /* options */))) {
+               if (verbose>=2)
+                       error(_(".Child process w/PID %d has exited, %s, status=%d"),
+                                       pid,(WIFEXITED(status)? _("normally") : _("abnormally")),(WIFEXITED(status) ? WEXITSTATUS(status) : -1));
+               }
+}
+
 static void receive_text(char *bodyline)
 {
 char *buf,*s,*s1,*s2,*s3;
@@ -1559,12 +1776,17 @@ int i;
 FILE *f;
 
        d2("receive_text: %s\n",bodyline);
+       signal(SIGCHLD,(RETSIGTYPE (*)(int))signal_chld);
 #if RECEIVE_TEST
        pid=0;
 #else
        pid=fork();
 #endif
-       if (pid>0) return; /* parent context */
+       if (pid>0) {
+               if (verbose>=2)
+                       error(_(".Spawned child receive-SMS process w/PID %d"),pid);
+               return; /* parent context */
+               }
        if (pid==-1) {
                error(_("Can't fork(2), process spawning may block receive"));
                }
@@ -1622,10 +1844,10 @@ err:
        exit(EXIT_SUCCESS); /* cleanup() has been disabled */
 }
 
-static inline unsigned char fromhex(char c)
+static inline unsigned char fromhex(unsigned c)
 {
        c&=0xDF;
-       return(c<'A'?c-'0':(c-'A')+0xA);
+       return(c<'A'?c-('0'&0xDF):(c-('A'&0xDF))+0xA);
 }
 
 static int teldecode(char *text,unsigned char *bin,size_t digits)
@@ -1672,7 +1894,7 @@ int i;
 static void receive_pdu(char *pduline)
 {
 unsigned char pdu[140+0x100],*pdup,*pdue,oalen,inreg;
-char text[160+1],*textp,*s;
+char text[160+1],*textp,*s,*pdulinescan;
 size_t pdulinel=strlen(pduline),want;
 size_t udl,udlb;
 int inb,outb,xb;
@@ -1684,11 +1906,11 @@ int inb,outb,xb;
                { error(_("PDU length odd (%d): %s"),pdulinel,pduline); return; }
        if (pdulinel<2*13)
                { error(_("PDU length %d too small (min. 2*%d): %s"),pdulinel,13,pduline); return; }
-       for (pdup=pdu;*pduline;pduline+=2) {
-               if (!isxdigit(pduline[0]) || !(isxdigit(pduline[1])))
+       for (pdup=pdu,pdulinescan=pduline;*pdulinescan;pdulinescan+=2) {
+               if (!isxdigit(pdulinescan[0]) || !(isxdigit(pdulinescan[1])))
                { error(_("Invalid hex byte: %c%c on byte %d in: %s"),
-                       pduline[0],pduline[1],pdup-pdu,pduline); return; }
-               *pdup++=(fromhex(pduline[0])<<4)|fromhex(pduline[1]);
+                       pdulinescan[0],pdulinescan[1],pdup-pdu,pduline); return; }
+               *pdup++=(fromhex(pdulinescan[0])<<4)|fromhex(pdulinescan[1]);
                }
        pdue=pdup;
        free(receive_smsc);
@@ -1703,7 +1925,7 @@ int inb,outb,xb;
                if (pdu[1]==ADDR_INT) *s++='+';
                else {
                        if (pdu[1]!=ADDR_NAT)
-                               error(_("Unknown address type 0x%02X of %s, ignoring in PDU: %s"),_("SMSC"),pdu[1],pduline); return;
+                               error(_("Unknown address type 0x%02X of %s, ignoring in PDU: %s"),pdu[1],_("SMSC"),pduline); return;
                        }
                if (teldecode(s,pdu+2,2*(*pdu-1)-((pdu[1+(*pdu)]&0xF0)==0xF0)))
                        error(_("Some digits unrecognized in %s \"%s\", ignoring in PDU: %s"),_("SMSC"),receive_smsc,pduline);
@@ -1713,8 +1935,8 @@ int inb,outb,xb;
                error(_("Unrecognized PDU type 0x%02X at offset %d, dropping: %s"),*pdup,pdup-pdu,pduline);
        pdup++;
        free(receive_number);
-       if ((oalen=*pdup++)>10) /* OA len */
-               { error(_("Originating number too large (%d, max. %d): %s"),oalen,10,pduline); return; }
+       if ((oalen=*pdup++)>2*0x10) /* OA len */
+               { error(_("Originating number too large (0x%X, max. 2*0x%X): %s"),oalen,0x10,pduline); return; }
        if (pdup+(want=1+(oalen+1)/2+10)>pdue)
                { error(_("PDU length too short (want %d, is %d): %s"),(pdup-pdu)+want,pdue-pdu,pduline); return; }
        chk(receive_number=malloc(1+2*(*pdup)+1));
@@ -1722,7 +1944,7 @@ int inb,outb,xb;
        if (*pdup==ADDR_INT) *s++='+';
        else {
                if (*pdup!=ADDR_NAT)
-                       error(_("Unknown address type 0x%02X of %s, ignoring in PDU: %s"),_("originating number"),*pdup,pduline); return;
+                       error(_("Unknown address type 0x%02X of %s, ignoring in PDU: %s"),*pdup,_("originating number"),pduline); return;
                }
        pdup++;
        if (teldecode(s,pdup,oalen))
@@ -1752,14 +1974,13 @@ int inb,outb,xb;
 size_t udl1,udlb1;
 
                udlb1=pdue-pdup;
-               udl1=(udlb*8)/7;
+               udl1=(udlb1*8)/7;
                error(_("PDU data length (%d/7->%d/8) longer than data (%d), cut to %d/7->%d/8: %s"),
-                       udl,udlb,pdue-pdup,pduline);
+                       udl,udlb,pdue-pdup,udl1,udlb1,pduline);
                udl=udl1; udlb=udlb1;
                }
        else
-               error(_("Trailing garbage ignored in PDU data (UDL %d/7->%d/8, got %d) in: %s"),
-                       udl,udlb,pdue-pdup,pduline);
+               assert(pdup+udlb==pdue); /* should be checked by 'PDU length too short' above */
        textp=text;
        inb=outb=0;
        inreg=0; /* GCC happiness */
@@ -1777,7 +1998,7 @@ size_t udl1,udlb1;
 #if 0
                d4("inb=%d,outb=%d,xb=%d\n",inb,outb,xb);
 #endif
-               *textp|=((inreg>>(unsigned)(7-inb))&((1<<xb)-1))<<(unsigned)(8-outb);
+               *textp|=((inreg>>(unsigned)(8-inb))&((1<<xb)-1))<<(unsigned)(7-outb);
                inb-=xb; outb-=xb;
                if (!outb) {
                        *textp=charconv_recv(*textp,textp-text);
@@ -1798,6 +2019,7 @@ static struct {
                { &readtime,&readtimen,"readtime" },
                { &chartime,&chartimen,"chartime" },
                { &cmdtime ,&cmdtimen ,"cmdtime"  },
+               { &waittime,&waittimen,"waittime" },
                { &baud    ,&baudn    ,"baud"     },
        };
 
@@ -1808,6 +2030,7 @@ int i,cmgf=-1 /* GCC happiness */;
 unsigned fatal=0;
 speed_t portbaud=0 /* GCC happiness */;
 enum modenum argsmode;
+unsigned parts=0;
 
        if ((s=strrchr((pname=*argv),'/'))) pname=s+1;
 
@@ -1864,10 +2087,11 @@ char *buf=malloc(l+50);
        switch (mode) {
 
                case MODE_SEND:           /* FALLTHRU */
-               case MODE_SEND_MOBILDOCK: cmdline_send     (); break;
-               case MODE_LOGO_SEND:      cmdline_logo_send(); break;
-               case MODE_RING_SEND:      cmdline_ring_send(); break;
-               case MODE_RECEIVE:        cmdline_receive  (); break;
+               case MODE_SEND_MOBILDOCK: cmdline_send        (); break;
+               case MODE_LOGO_SEND:      cmdline_logo_send   (); break;
+               case MODE_RING_SEND:      cmdline_ring_send   (); break;
+               case MODE_PICTURE_SEND:   cmdline_picture_send(); break;
+               case MODE_RECEIVE:        cmdline_receive     (); break;
                default: assert(0);
                }
        cmdline_done();
@@ -1935,11 +2159,33 @@ size_t l=strlen(device);
                case MODE_RING_SEND:
                        ringread();
                        break;
+               case MODE_PICTURE_SEND:
+                       pictureread();
+                       break;
                case MODE_RECEIVE: break;
                default: assert(0);
                }
        if (readbody)
                error(_("Warning: -f / --file is forbidden with mode \"%s\""),MODE_NAME(mode));
+       if (smsmode) {
+                    if (!strcmp(smsmode,"pdu" ) || !strcmp(smsmode,"0"))
+                       force_smsmode=FSM_PDU ;
+               else if (!strcmp(smsmode,"text") || !strcmp(smsmode,"1"))
+                       force_smsmode=FSM_TEXT;
+               else
+                       error(_("!Unrecognized %s argument \"%s\", supported only: %s"),"-M/--smsmode",smsmode,"pdu/0/text/1");
+               }
+       if (pdusmscmode) {
+                    if (!strcmp(pdusmscmode,"count-in"))
+                       force_pdusmscmode=FPSM_COUNT_IN;
+               else if (!strcmp(pdusmscmode,"count-out"))
+                       force_pdusmscmode=FPSM_COUNT_OUT;
+               else if (!strcmp(pdusmscmode,"none"))
+                       force_pdusmscmode=FPSM_NONE;
+               else
+                       error(_("!Unrecognized %s argument \"%s\", supported only: %s"),"-P/--pdusmscmode",pdusmscmode,"count-in/count-out/none");
+               try_pdusmscmode=force_pdusmscmode;
+               }
 
        switch (baudn) {
                case  2400: portbaud= B2400; break;
@@ -1962,42 +2208,47 @@ time_t start,end;
                if ((end-=start)>LOCKREPORT)
                        logmsg(_("Device lock succeeded after %ld seconds"),(long)end);
                }
+
+retryopen:
+
        if (verbose>=1) error(_(".Opening device \"%s\".."),device);
        if ((devfd=open(device,O_RDWR|O_NDELAY))<0)
                error(_("^!Cannot open device \"%s\" for r/w access"),device);
        
-       if (tcgetattr(devfd,&restios))
-               error(_("^Unable to get termios settings"));
-       else {
-               restios.c_cflag=(restios.c_cflag&~(CBAUD|CBAUDEX))|B0|HUPCL;
-               restios_yes=1;
-               }
-       tios.c_iflag=IGNBRK|IGNPAR|IXON|IXOFF;
-       tios.c_oflag=0;
-       tios.c_cflag=CS8|CREAD|CLOCAL|HUPCL|portbaud;
-       tios.c_lflag=IEXTEN|NOFLSH;
-       memset(tios.c_cc,_POSIX_VDISABLE,sizeof(tios.c_cc));
-       tios.c_cc[VTIME]=0;
-       tios.c_cc[VMIN ]=1;
-           cfsetispeed(&tios,portbaud);
-       if (cfsetospeed(&tios,portbaud)|cfsetispeed(&tios,portbaud))
-               error(_("^Error setting termios baudrate on device"));
-       if (tcflush(devfd,TCIOFLUSH))
-               error(_("^Error flushing termios (TCIOFLUSH) on device"));
-       if (tcsetattr(devfd,TCSANOW,&tios))
-               error(_("^!Unable to set initial termios device settings"));
+retryall:
 
-       setalarm();
+               if (tcgetattr(devfd,&restios))
+                       error(_("^Unable to get termios settings"));
+               else {
+                       restios.c_cflag=(restios.c_cflag&~(CBAUD|CBAUDEX))|B0|HUPCL;
+                       restios_yes=1;
+                       }
+               tios.c_iflag=IGNBRK|IGNPAR|(handshake_rtscts ? 0 : IXON|IXOFF);
+               tios.c_oflag=0;
+               tios.c_cflag=CS8|CREAD|CLOCAL|HUPCL|portbaud|(handshake_rtscts ? CRTSCTS : 0);
+               tios.c_lflag=IEXTEN|NOFLSH;
+               memset(tios.c_cc,_POSIX_VDISABLE,sizeof(tios.c_cc));
+               tios.c_cc[VTIME]=0;
+               tios.c_cc[VMIN ]=1;
+                               cfsetispeed(&tios,portbaud);
+               if (cfsetospeed(&tios,portbaud)|cfsetispeed(&tios,portbaud))
+                       error(_("^Error setting termios baudrate on device"));
+               if (tcflush(devfd,TCIOFLUSH))
+                       error(_("^Error flushing termios (TCIOFLUSH) on device"));
+               if (tcsetattr(devfd,TCSANOW,&tios))
+                       error(_("^!Unable to set initial termios device settings"));
+
+               setalarm();
 
-retryall:
                devcmd("",NULL,"\r\nAT\033\032"); /* ESCAPE, CTRL-Z */
                devcmd(NULL,NULL,"\r\nAT");
                smscset();
                if (mode==MODE_SEND || mode==MODE_RECEIVE) {
                        cmgf=-1;
                        do {
-                               if (!devcmd(NULL,NULL,"!\r\nAT+CMGF=0")) {
-                                       if (!devcmd(NULL,NULL,"!\r\nAT+CMGF=1"))
+                               /* condition is _negative_ here: */
+                               if (force_smsmode==FSM_TEXT || !devcmd(NULL,NULL,"!\r\nAT+CMGF=0")) {
+                                       if (force_smsmode==FSM_PDU || !devcmd(NULL,NULL,"!\r\nAT+CMGF=1"))
                                                { retrying(); continue; }
                /* CMGF=1 */
                                        if (verbose>=1)
@@ -2019,70 +2270,98 @@ retryall:
                                        s=devcmd(NULL,"\n+CMGS:","!~%s\032",body);
                                        }
                                else {
-                                       devcmd("\n> ",NULL,"\r\nAT+CMGS=%d",(strlen(pdusmsc)+strlen(pdudata))/2);
-                                       s=devcmd(NULL,"\n+CMGS:","!~%s%s\032",pdusmsc,pdudata);
+                                       devcmd("\n> ",NULL,"\r\nAT+CMGS=%d",(
+                                                       (try_pdusmscmode==FPSM_COUNT_IN ? strlen(pdusmsc) : 0)
+                                                       +strlen(pdudata))/2);
+                                       s=devcmd(NULL,"\n+CMGS:","!~%s%s\032",
+                                                       (try_pdusmscmode!=FPSM_NONE ? pdusmsc : ""),
+                                                       pdudata);
+                                       if (!s && force_pdusmscmode==FPSM_AUTO) {
+                                               if (FPSM_MAX==try_pdusmscmode++)
+                                                       try_pdusmscmode=FPSM_MIN;
+                                               else
+                                                       retrycnt--;
+                                               }
                                        }
                                break;
                        case MODE_LOGO_SEND:
-                       case MODE_RING_SEND: {
+                       case MODE_RING_SEND:
+                       case MODE_PICTURE_SEND: {
 struct hexdata *hd;
 
                                restore="\r\nAT+CSMP=17,,0,0";
                                devcmd(NULL,NULL,"\r\nAT+CSMP=81,,0,245");
-                               devcmd("\n> ",NULL,"\r\nAT+CMGS=\"%s\"",phone);
                                while ((hd=hexdata)) {
+                                       devcmd("\n> ",NULL,"\r\nAT+CMGS=\"%s\"",phone);
                                        if (!(s=devcmd(NULL,"\n+CMGS:","!~%s\032",hd->data))) break;
-                                       hexdata=hd->next;
+                                       if ((hexdata=hd->next)) pushargstack_one(s,0);
                                        free(hd);
+                                       parts++;
                                        }
                                } break;
-                       case MODE_RECEIVE:
+                       case MODE_RECEIVE: {
+int gotdatawait;
+
                                restore="\r\nAT+CNMI=,0";
                                devcmd(NULL,NULL,"\r\nAT+CNMI=,2");
                                devcmd(NULL,NULL,"\r\nAT+CSDH=0");
+continue_receive:
                                unlockdevice(0);
                                /* Never bail-out when we got up to this point */
                                if (maxretryn!=-1 && verbose>=1)
                                        error(_(".Initialization successful, infinite retry count set"));
                                maxretryn=-1;
 #if RECEIVE_TEST
-               receive_headerparse(" \"+420602123456\",,\"99/10/25,03:21:03-00\"");
-               receive_accept("TESTBODY");
-               exit(EXIT_SUCCESS);
+       receive_headerparse(" \"+420602123456\",,\"99/10/25,03:21:03-00\"");
+       receive_accept("TESTBODY");
+       exit(EXIT_SUCCESS);
 #endif
-                               datawait(0);
+                               gotdatawait=datawait(waittimen);
                                if (!lockdevice(1)) {
                                        if (verbose>=1)
                                                error(_(".Dialout detected, waiting for lock.."));
+                                       if (verbose>=1) error(_(".Closing device \"%s\".."),device);
+                                       if (close(devfd))
+                                               error(_("Error closing device \"%s\""),device);
                                        lockdevice(0);
-                                       goto retryall;
+                                       goto retryopen;
                                        }
                                d1("Lock-device succeeded\n");
                                do {
-                                       d1("Reading a message for us...\n");
-                                       if (!(s=devcmd("\r","@+CMT:"," ")))
+                                       if (!(s=devcmd("\n","+CMT:"," ")))
                                                goto retryall;
+                                       if (s==&devcmd_empty_return) { /* only newlines found */
+                                               if (gotdatawait==0) /* timeout, rather reinitialize the modem */
+                                                       goto retryall;
+                                               goto continue_receive;
+                                               }
+                                       d1("Reading a message for us...\n");
                                        if (cmgf && !(i=receive_headerparse(s)))
                                                error(_("Receive-header parsing failed on: %s"),s);
-                                       if (!(s=devcmd("\r","@\n"," ")))
+                                       if (!(s=devcmd("\n","@"," ")))
                                                goto retryall;
                                        if (cmgf) {
                                                if (i) receive_text(s);
                                                }
                                        else receive_pdu(s);
-                                       if (!devcmd("\n",NULL," ")) /* eat last '\n' */
-                                               goto retryall;
-                                       } while (datawait(1));
+                                       } while (datawait(0));
                                goto retryall;
-                               break;
+                               }
+
                        default: assert(0);
                        }
                if (!s) { retrying(); goto retryall; }
 
-       while (isspace(*s)) s++;
-       if (verbose>=1) error(_("\nMessage successfuly sent with MR (Message Reference): %s"),s);
+       pushargstack_one(s,0); s=NULL;
+       if (verbose>=1) while ((s=nextargstack())) {
+               while (isspace(*s)) s++;
+               error(_("\nMessage successfuly sent with MR (Message Reference): %s"),s);
+               }
        devcmd(NULL,NULL,"\r\nAT");
 
-       logmsg(_("SMS sent (after %d retries), message reference: %s"),retrycnt,s);
+       if (parts)
+               logmsg(_("SMS sent (after %d retries), %d part(s)"),retrycnt,parts);
+       else
+               logmsg(_("SMS sent (after %d retries)"),retrycnt);
        return(EXIT_SUCCESS);
 }