File: fax_funcs.c

package info (click to toggle)
acfax 981011-11
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 448 kB
  • ctags: 736
  • sloc: ansic: 5,498; makefile: 34
file content (1633 lines) | stat: -rw-r--r-- 47,044 bytes parent folder | download | duplicates (7)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
/*
    ACfax - Fax reception with X11-interface for amateur radio
    Copyright (C) 1995-1998 Andreas Czechanowski, DL4SDC

    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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

    andreas.czechanowski@ins.uni-stuttgart.de
*/
    
/* fax_funcs.c - all fax-specific functions should be placed here.
 *		 This file depends on neary everything; It calls the hardware-
 *		 specific setup, the filter setup, and needs some X11-
 *		 variables for writing into the canvas.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include "x_image.h"
#include <X11/Intrinsic.h>
#include "sblaster.h"
#include "mod_demod.h"
#include "widgets.h"
#include "fax_funcs.h"

/* some variables that are allowed to be global */
int	lpm;		/* lines per minute */
int     ixoc;           /* number of pixels of one scan-line / PI */
int	devi;		/* deviation in Hz (+/- of middle) */
int     mod_mode;       /* can be MOD_FM or MOD_AM */
int     aptstart;       /* possible APT start values */
int     aptstop;        /* possible APT stop values */
int	aptdur;		/* apt duration in millisecs (for transmitting) */
int	vertical;	/* vertical or horizontal line direction */
int     right2left;     /* boolean indicating reverse line writing direction */
int     bot2top;        /* boolean indicating reverse line stacking direction */
int	invphase;	/* polarity of phase-in-signal to use */
int	invimage;	/* inverse colormap usage */
/* and the private variables */
int	fax_inited = 0;	/* if fax_init was called */
unsigned canwid;	/* width of the Pixmap to draw in */
unsigned canhei;	/* height of the Pixmap */
int	sxpos, sypos;	/* current coordinates of received/xmitted data */
int	pixpos, linepos; /* current coordinates of received/xmitted data */
int	imline;		/* currently processed line of XImage */
void	(*update_area)(XImage *, int, int, int, int, unsigned, unsigned);
	/* called to copy XImage to Pixmap and update the window-area required */
void	(*mode_notify)(int); /* notifies main program of changes of fax_state */
int	mcolor;		/* color-mode selected */
int	dmaxval;	/* number of usable grayscale-values - 1 */
int	compval;	/* comparator value for APT-counter */
int	flip;		/* flipping of green and blue parts of the colormap */
int	rotate;		/* rotation of the colormap */
int     fax_state;      /* one of FAX_APT, FAX_PHAS or FAX_RX */
char	*core_dta;	/* storage for raw demodulated data (accumulating) */
char	*core_start;	/* start of core for image-processing */
char	*core_wptr;	/* pointer to next written element in core_dta */
char	*core_maxptr;	/* pointer beyond the last element in core_dta */
void	(*disp_func)(int); /* pointer to function displaying the data-stream */
int	(*save_func)(int, int);
			/* pointer to function saving image to file */
void	(*fax_tx_func)(int); /* pointer to function transmitting image */
int	disp_locked;	/* flag indicating that disp_func should not be called
			   from fax_rx_backgnd */
int	save_locked;	/* same as above for save_func */
void    (*apt_notify)(int); /* pointer to function evaluating APT frequency */
unsigned smplf;		/* number of samples per second << 16 */
unsigned smpl_line;	/* number of samples per line << 16 */
unsigned hsmpl_sec;	/* half the number of samples per second */
int     aptncmax;       /* maximum "empty" points in an APT-line */
int	phstate = 0;	/* state (0=waiting, 1=active) of phase-finder */
int	phlines;	/* number of recognized phase-lines */
unsigned hsmpl_line;    /* half the number of samples per line */
int	phposa[24];	/* phase position A (middle of line) */
int	phposb[24];	/* phase position B (edges of line) */
int	phsdir[24];	/* phase direction (beginning or end of line) */
int	phaseavg;	/* average phase position calculated */
char	*demod_ptr;	/* pointer to raw demodulated data */
int	demod_cnt;	/* number of decoded points per call */
char	*mod_ptr;	/* pointer to raw data being modulated */
char	*mod_end;	/* pointer to first byte behind end of modulator-space */
FILE	*fsfile;	/* file pointer of current save-file */
char	faxsavename[256]; /* current name of save-file */
char	*saveline;	/* storage for 1 image-line in save_func */
XtAppContext	mainapp; /* main app.context (needed for interv.timer) */
XtIntervalId	chstime; /* for the repetitive called background function */
XtInputId	dspxid = 0; /* for the background function when using select() */
XEvent	event;		/* event needed to form the XtAppMainLoop */
unsigned twidth;	/* width of transmitted image */
unsigned theight;	/* height of transmitted image */
int	tx_phlines;	/* number of phase-in lines to be transmitted */
char	*timg_ptr;	/* array holding image to be transmitted (pixel oriented) */
FILE	*ftfile;	/* pointer to file-struct for transmission */

/*
 * init_fax initializes the "core"-space where the raw decoded data resides.
 * This practice is not very nice to memory-limited systems, but has the
 * advantage of being able to back up from nearly any setup-error (including
 * wrong lpm, IOC, direction and color-mode but excluding tuning-errors)
 */
void init_fax(void)
{
  if (fax_inited) return;
  fprintf(stderr, "initializing FAX procedures and alloc'ing core-space\n");
  lpm = 120;
  ixoc = 288;
  devi = 400;
  mod_mode = MOD_FM | FIL_MIDL;
  dmaxval = 63;
  compval = dmaxval >> 1;
  core_dta = malloc(CORESIZE);
  core_start = core_dta;
  core_wptr = core_dta;
  core_maxptr = core_dta + COREMAX;
  interface_init(&demod_ptr, &demod_cnt);
  setup_mode(mod_mode, dmaxval, devi, &smplf);
  hsmpl_sec = smplf >> 17;
  aptncmax = hsmpl_sec / 25;
  mod_end = demod_ptr + demod_cnt;
  mod_ptr = demod_ptr;
  fprintf(stderr, "smplf = %08x (16.16), demod_cnt = %d\n", smplf, demod_cnt);
  disp_func = decode_fax_gray;
  fax_tx_func = transmit_fax_gray;
  save_func = save_fax_gray;
  fsfile = NULL;
  saveline = NULL;
  apt_notify = apt_control;
  chstime = (XtIntervalId) 0;

  timg_ptr = NULL;
  ftfile = NULL;

  fax_inited = 1;
}

/* exit_fax frees the core_dta space, so that other program-parts may
   allocate memory without having a dead-space overhead.
*/
void exit_fax(void)
{
  if (!fax_inited) return;
  free(core_dta);
  fax_inited = 0;
}

/*
 * setup_fax sets up all the variables for FAX-reception and transmission.
 * s_lpm : lines per minute (no change if set to 0)
 * s_ixoc: IOC to use (pixels per line = PI * IOC) (no change if set to 0)
 * mode  : fax-specific mode setings such as writing direction and order,
 *	   phase-in polarity and grayscale or color-mode
 * s_devi: deviation to use for FM (no change if set to 0)
 * s_modem : (de-)modulator-specific settings as filter to use, AM or FM 
 */
void setup_fax(int s_lpm, int s_ixoc, unsigned mode,
	Widget toplevel, unsigned width, unsigned height,
	int s_devi, unsigned s_modem)
{
  unsigned id;
  unsigned filter, mmode;
  void (*old_func)(int);

  /* be sure initialisation is done */
  init_fax();

  mainapp = XtWidgetToApplicationContext(toplevel);
  /* if size is given or has changed, re-create X-images */
  if ((width) || (height)) {
    if (width)
      canwid = width;
    if (height)
      canhei = height;
    create_images(toplevel, canwid, canhei);
  }
  /* check if the (de-)modulator needs readjustment */
  filter = s_modem & FIL_MASK;
  mmode = s_modem & MOD_BITS;
  if ((filter) || (mmode) || (s_devi)) {
    fprintf(stderr, "setting filter & mmode = 0x%04x\n", (filter | mmode));
    if (s_devi) {
      if (s_devi < 100) s_devi = 100;
      if (s_devi > 1200) s_devi = 1200;
      devi = s_devi;
    }
    setup_mode((filter | mmode), dmaxval, s_devi, &smplf);
    hsmpl_sec = smplf >> 17;
    aptncmax = hsmpl_sec / 25;
    if (filter)
    {
      mod_mode = (~FIL_MASK & mod_mode) | filter;
    }
    if (mmode)
    {
      mod_mode = (~MOD_BITS & mod_mode) | mmode;
    }
  }

  if (s_lpm) {
    if (s_lpm < 60) s_lpm = 60;
    if (s_lpm > 500) s_lpm = 500;
    lpm = s_lpm;
    fprintf(stderr, "changing lpm to %d\n", lpm);
  }
  if (s_ixoc) {
    if (s_ixoc < 60) s_ixoc = 60;
    if (s_ixoc > 600) s_ixoc = 600;
    ixoc = s_ixoc;
    fprintf(stderr, "changing ioc to %d\n", ixoc);
  }
  if ((id = mode & FAX_POL)) {
    if (id == FAX_CNOR) {
      invimage = 0;
    } else {
      invimage = 1;
    }
    fprintf(stderr, "setting invimage mode to %d\n", invimage);
  }
  if ((id = mode & FAX_CFLS)) {
    if (id == FAX_CUNFL)  {
      flip = 0;
    } else {
      flip = 1;
    }
    fprintf(stderr, "setting color-flip to %d\n", flip);
  }
  if ((id = mode & FAX_CROTS)) {
    switch(id) {
      case FAX_CROT0:
	rotate = 0;
	break;
      case FAX_CROT1:
	rotate = 1;
	break;
      case FAX_CROT2:
	rotate = 2;
	break;
    }
    fprintf(stderr, "setting color-rotation to %d\n", rotate);
  }
  if ((id = mode & FAX_DIR)) {
    if (id & FAX_TOP2BOT)
      bot2top = 0;
    else if (id & FAX_BOT2TOP)
      bot2top = 1;

    if (id & FAX_LEF2RIG)
      right2left = 0;
    else if (id & FAX_RIG2LEF)
      right2left = 1;

    fprintf(stderr, "changing direction to h=%d, v=%d\n", right2left, bot2top);
  }
  if ((id = mode & FAX_ROT)) {
    if (id == FAX_HOR) {
	vertical = 0;
    } else {
	vertical = 1;
    }
    fprintf(stderr, "selecting %s direction\n",
	 (vertical) ? "vertical" : "horizontal");
  }
  if ((id = mode & FAX_PHS)) {
    if (id == FAX_PWHT) {
	invphase = 1;
    } else {
	invphase = 0;
    }
    fprintf(stderr, "phase inversion mode = %d\n", invphase);
  }
  if ((id = mode & FAX_CMODE)) {
    switch (id) {
      case FAX_GRAY:
	mcolor = 0;
	break;
      case FAX_COLOR:
	mcolor = 1;
	break;
    }
    fprintf(stderr, "receive mode is %s\n", (mcolor) ? "color" : "grayscale");
  }
  /* now, all modifications to variables are done.
     some recomputations are to be done dependant on what has changed... */
  if (mode & FAX_CMODS)
    if (mcolor) {
      fill_cmap_col(invimage, flip, rotate);
    } else {
      fill_cmap_gray(invimage);
    }
  if ((mode & (FAX_DIR | FAX_ROT | FAX_CMODE | FAX_CMODS))
	|| (s_ixoc) || (s_lpm) || (width) || (height)
	|| (s_modem & MOD_BITS)) {
    if (mcolor) {
      disp_func = decode_fax_gray;
      save_func = save_fax_gray;
    } else {
      disp_func = decode_fax_gray;
      save_func = save_fax_gray;
    }
    /* recomputations are done in disp_func() */
    fprintf(stderr, "initializing disp_func\n");
    disp_func(D_CPINIT | D_WDINIT | D_LDINIT);
    /* now call function to re-create picture */
#if stillneeded	/* the disp_func should lock itself */
    old_func = disp_func;
    disp_func = NULL;
    fprintf(stderr, "calling disp_func to re-display image\n");
    old_func(D_ALLOWX);
    disp_func = old_func;
#else
    fprintf(stderr, "calling disp_func to re-display image\n");
    disp_func(D_ALLOWX);
#endif
  }
  if ((mmode) && (dspxid != 0))
  {
    /* re-initiate data reception, because changing the modulation mode
     * (and thus changing the sample rate) requires the data stream to
     * stop. [Later, this should be RX or TX depending on what we do] */
    fax_rx_backgnd((XtPointer) NULL, &dspfd, (XtInputId *) NULL);
  }
}

/* enable FAX reception: set auto-initializing background function */
void receive_on(void)
{
#ifndef DSP_SELECT
  if (chstime != (XtIntervalId) 0) return;
#endif
  fax_state = FAX_APT;
  mode_notify(fax_state);
#ifdef DSP_SELECT
  dspxid = XtAppAddInput(mainapp, dspfd, (XtPointer) XtInputReadMask,
		fax_rx_backgnd, (XtPointer) NULL);
  fprintf(stderr, "dspxid from XtAppAddInput is %ld\n", dspxid);
  /* initiate the reading of data. Once started, it is called by
   * XtAppMainLoop() which uses select() to listen on dspfd. */
  fax_rx_backgnd((XtPointer) NULL, &dspfd, &dspxid);
#else
  chstime = XtAppAddTimeOut(mainapp, 250, fax_rx_backgnd, (XtPointer) NULL);
#endif
}

void receive_off(void)
{
#ifdef DSP_SELECT
  XtRemoveInput(dspxid);
  dspxid = (XtInputId) 0;
#else
  XtRemoveTimeOut(chstime);
#endif
  interface_stop();
  chstime = (XtIntervalId) 0;
}

#ifdef DSP_SELECT
/* this is the reception routine triggered upon input from DSP device */
void fax_rx_backgnd(XtPointer client_data, int *source, XtInputId *xid)
#else
/* this is the reception routine which calls itself after 250ms */
void fax_rx_backgnd(XtPointer client_data, XtIntervalId *xid)
#endif
{
  int space;

/*
  if (init_rx) {
    init_rx = 0;
    core_wptr = core_dta;
  }
*/
/*
  fprintf(stderr, "receiving data\n");
*/
  /* get the input samples and demodulate the input data stream */
  do_receive();

  /* update the signal-level scrollbar display */
  set_sigdisplay((double)rx_level / 255.0);

  /* always watch for APT frequencies */
/*
  fprintf(stderr, "decoding APT\n");
*/
  decode_apt(0);

  /* if we are in the phasing state, compute the phase-position */
  if (fax_state == FAX_PHAS)
    sync_phase(0);

  /* copy the data into the core_dta array and advance the write-pointer */
  if (fax_state == FAX_RX) {
    space = core_maxptr - core_wptr;
    if (space >  demod_cnt)
      space = demod_cnt;
    memcpy(core_wptr, demod_ptr, space);
    core_wptr += space;
  }

#ifdef DSP_SELECT
  /* we don't need to retrigger ourself - do nothing */
#else
  /* add a new timeout to call this function again */
/*
  printf("adding new timeout\n");
*/
  chstime = XtAppAddTimeOut(mainapp, 250, fax_rx_backgnd, (XtPointer) NULL);
#endif

  /* if disp_func is set, call that function (e.g. main FAX decoder loop) */
  if ((disp_func) && !(disp_locked)) {
/*
    fprintf(stderr, "calling disp_func\n");
*/
    disp_func(0);
  }
  /* if save_func is set (saving of received image enabled), call function */
  if ((save_func) && !(save_locked)) {
/*
    fprintf(stderr, "calling save_func\n");
*/
    save_func(F_DOSAVE, 0);
  }
}

/*
 * grayscale FAX decoding main routine.
 * init is used to control the behavior and initialize some internal
 * variables. It is bit-wise coded as follows :
 *  D_CPINIT : initialize read-pointer to start of core-buffer
 *  D_WDINIT : initialize x-position to the start-value
 *  D_LDINIT : initialize y-position to the start-value
 *  D_ALLOWX : periodically call XtAppProcessEvent during processing
 *	(requires that this function is NOT called from fax_rx_backgnd !)
 */
void decode_fax_gray(int init)
{
  XtInputMask msk;

#ifdef FAST8BIT
  static char *imptr;
  static char *imptinit;
  static int  impinc;
#endif

  /* pointer to sample-point for current pixel and current start-of-line */
  static char *core_line, *core_pix;
  /* sample-values per line or per pixel-value, 16bit int, 16bit frac */
  static unsigned inc_pix, inc_line;
  /* current index to pixel or line in sample-array, 16bit int, 16bit frac */
  static unsigned idx_pix, idx_line, idx_p0;
  /* increment between actual and previous pixel/line position */
  static unsigned ipix, iline;
  /* pixel-in-line-position start/increment/end */
  static int pixinit, pixinc, pixend;
  /* line-in-image-position start/increment/end, max. line of XImage */
  static int lineinit, lineinc, lineend, imgmax;
  static int (*put_pix)(struct _XImage *, int, int, unsigned long);

  if (init & D_INITS) {
    /* smpl_line is the number of core_dta points per line << 16 */
    smpl_line = 60.0 / lpm * smplf;
    if (vertical) {
      inc_pix = smpl_line / canhei;
      inc_line = (int)(ixoc * M_PI * 65536.0 / canhei); 
      imgmax = DEFWIDTH;
      put_pix = verimag->f.put_pixel;
    } else {
      inc_pix = smpl_line / canwid;
      inc_line = (int)(ixoc * M_PI * 65536.0 / canwid); 
      imgmax = DEFHEIGHT;
      put_pix = horimag->f.put_pixel;
    }
    if (!(vertical) && (right2left)) {
      pixinit = canwid - 1;
      pixinc = -1;
      pixend = -1;
#ifdef FAST8BIT
      imptinit = horimag->data + canwid - 1;
      impinc = -1;
#endif
    } else
    if ((vertical) && (bot2top)) {
      pixinit = canhei - 1;
      pixinc = -1;
      pixend = -1;
#ifdef FAST8BIT
      imptinit = verimag->data + (canhei - 1) * verimag->bytes_per_line;
      impinc = -verimag->bytes_per_line;
#endif
    } else {
      pixinit = 0;
      pixinc = 1;
      pixend = (vertical) ? canhei : canwid;
#ifdef FAST8BIT
      imptinit = (vertical) ? verimag->data : horimag->data;
      impinc = (vertical) ? verimag->bytes_per_line : 1;
#endif
    }
    /* initialize the line-advance variables and pointers */
    if (!(vertical) && (bot2top)) {
	lineinit = canhei - DEFHEIGHT;
	lineinc = -1;
	lineend = -1;
    } else
    if ((vertical) && (right2left)) {
	lineinit = canwid - DEFWIDTH;
	lineinc = -1;
	lineend = -1;
    } else {
	lineinit = 0;
	lineinc = 1;
	lineend = (vertical) ? canwid : canhei;
    }

    if (init & D_WDINIT) {
      pixpos = pixinit;
    }

    if (init & D_LDINIT) {
      linepos = lineinit;
      if ((!(vertical) && (bot2top)) || ((vertical) && (right2left)))
	imline = imgmax - 1;
      else
	imline = 0;
    }
#ifdef FAST8BIT
    if ((init & D_LDINIT) || (init & D_WDINIT)) {
      imptr = imptinit + impinc * pixpos;
      if (vertical)
	imptr += imline;
      else
	imptr += horimag->bytes_per_line * imline; 
    }
#endif

    if (init & D_CPINIT) {
      /* initialize the fractional index pointers */
      idx_pix = idx_line = idx_p0 = 0;
      core_pix = core_line = core_start;
      ipix = iline = 0;
    }
    fprintf(stderr,"initialisation done :\n"
	"pixinit = %d, pixinc = %d, pixend = %d\n"
	"lineinit = %d, lineinc = %d, lineend = %d\n"
	"imline = %d, imgmax = %d\n",
	pixinit, pixinc, pixend,
	lineinit, lineinc, lineend,
	imline, imgmax);
	
    disp_locked = 0;
    return;
  }
  if (init & D_ALLOWX) {
    printf("redrawing from %d, %d, corepos = %d\n", pixpos, linepos, core_pix - core_dta);
  }
  disp_locked = 1;
  do {
    /* if it is better to wait for more data, cancel function and wait
       until it is called next time */
    if (core_pix >= core_wptr)
      break;

    /* enter a new brightness-value (0..63) into core_dta */

#ifdef FAST8BIT
    *imptr = coltab[*(unsigned char *)core_pix];
    imptr += impinc;
#else
    if (vertical)
      put_pix(verimag, imline, pixpos, coltab[*(unsigned char *)core_pix]);
    else
      put_pix(horimag, pixpos, imline, coltab[*(unsigned char *)core_pix]);
#endif

    /* shift the x-position, and if we have reached the end... */
    pixpos += pixinc;
    if (pixpos == pixend) {
      /* re-start from left border */
      pixpos = pixinit;
      /* now we have one more complete line, copy it from core_dta to the
	 horimag (an Ximage). Use fast methode by advancing pointers */

      /* check if we wave filled up all lines of horimag, or if we just
	 have got as many lines that we can complete the picture. */
      imline += lineinc;
      if ((imline == imgmax) || (imline < 0) || (linepos + imline == lineend)) {
	while ((init & D_ALLOWX) && ((msk = XtAppPending(mainapp)))) {
	  XtAppProcessEvent(mainapp, msk);
	}
	if (vertical)
	  if (right2left) {
	    update_area(verimag, 0, 0, linepos, 0, (DEFWIDTH-1) - imline, canhei);
	  } else {
	    update_area(verimag, 0, 0, linepos, 0, imline, canhei);
	  }
	else
	  if (bot2top) {
	    update_area(horimag, 0, 0, 0, linepos, canwid, (DEFHEIGHT-1) - imline);
	  } else {
	    update_area(horimag, 0, 0, 0, linepos, canwid, imline);
	  }
	if (((vertical) && (right2left)) || (!(vertical) && (bot2top))) {
	  imline = imgmax - 1;
	  linepos -= imgmax;
	  if (linepos < 0)
	    linepos = lineinit;
	} else {
	  imline = 0;
	  linepos += imgmax;
	  if (linepos >= lineend)
	    linepos = 0;
	}
      }

#ifdef FAST8BIT
      if (vertical)
	imptr = imptinit + imline;
      else
	imptr = imptinit + horimag->bytes_per_line * imline;
#endif

      idx_line += inc_line;
      iline = (idx_line >> 16) & 0xffff;
      idx_line &= 0xffff;
      core_line += iline * ((smpl_line >> 16) & 0xffff);

      /* we must also initialize the pixel-counters here ! */
      idx_p0 += iline * (smpl_line & 0xffff);
      core_line += (idx_p0 >> 16) & 0xffff;
      core_pix = core_line;
      idx_p0 &= 0xffff;
      idx_pix = idx_p0;
      ipix = 0;

      /* jump over the stuff below... */
      continue;
    }
    /* shift the sample-point (16 bits integer, 16 bits fractional part) */
    idx_pix += inc_pix;
    ipix = (idx_pix >> 16) & 0xffff;
    core_pix += ipix;
    idx_pix &= 0xffff;
  } while (1);
  if (init & D_FLUSHIMG) {
    if (vertical)
	if (right2left) {
	  update_area(verimag, 0, 0, linepos, 0, (DEFWIDTH-1) - imline, canhei);
	} else {
	  update_area(verimag, 0, 0, linepos, 0, imline, canhei);
	}
    else
	if (bot2top) {
	  update_area(horimag, 0, 0, 0, linepos, canwid, (DEFHEIGHT-1) - imline);
	} else {
	  update_area(horimag, 0, 0, 0, linepos, canwid, imline);
	}
  }
  disp_locked = 0;
}

/*
 * this function should be used by the main program to initiate saving
 * of an image. If name is not given, it is constructed of date and time.
 */
int save_faxfile(char *name, int width)
{
  time_t tp; 
  char date[16];	/* string to build date for automatic savefile-name */

  /* check if save-file is already open */
  if (fsfile)
    return SAVE_BUSY;
  /* if no name is given, generate autosave-filename from date and time */
  if (name) {
    strcpy(faxsavename, name);
  } else {
    time(&tp);
    strftime(date, 14, "%m.%d-%H:%M", localtime(&tp));
    sprintf(faxsavename, "%s/faxsave_%s.pgm", FAX_SAVEDIR, date);
  }
  return save_func(F_OPEN, width);
}

/* properly close the save-file */
void close_faxsave(void)
{
  if (!(fsfile))
    return;
  save_func(F_GETDIM, 0);
  save_func(F_DOSAVE, 0);
  save_func(F_CLOSE, 0);
}

/*
 * fax-image saving function, writes grayscale ppm-images (pgm).
 * The image cannot be rotated, only flipped in writing-direction.
 * init defines the action to be done :
 * F_DOSAVE : save image if file is opened, close when completed
 * F_OPEN : open file, faxsavename contains the name and width the width
 *	    of the image. If width is not given, the best resolution is taken
 *	    (width = PI * IOC)
 * F_CLOSE : close file and adjust data in header to actual values
 * F_GETDIM : get dimensions and parameters of image into internal variables
 * the filename must previously be put into faxsavename.
 */ 
int save_fax_gray(int init, int width)
{
  XtInputMask msk;
  /* width and height of saved image */
  static unsigned swidth, sheight;
  static char *ldptr, *ldpinit, *ldpend;
  static int ldpinc;
  /* end of picture in core-space */
  static char *save_wptr = NULL;
  /* pointer to sample-point for current pixel and current start-of-line */
  static char *core_line, *core_pix;
  /* sample-values per line or per pixel-value, 16bit int, 16bit frac */
  static unsigned inc_pix, inc_line;
  /* current index to pixel or line in sample-array, 16bit int, 16bit frac */
  static unsigned idx_pix, idx_line, idx_p0;
  /* increment between actual and previous pixel/line position */
  static unsigned ipix, iline;
  /* pixel-in-line-position start/increment/end */
/*
  static int pixinit, pixinc, pixend;
*/
  /* line-in-image-position start/increment/end, max. line of XImage */
/*
  static int lineinit, lineinc, lineend, imgmax;
*/
  /* whether the writing-direction must be reversed */
  static int flip;
  int pos;

  if (init == F_OPEN) {
    /* close "old" file first */
    if (fsfile)
      save_fax_gray(F_CLOSE, 0);
     if (width > 0)
      swidth = width;
    else
      swidth = (ixoc * M_PI) + 0.5;
    fsfile = fopen(faxsavename, "wb");
    if (!(fsfile)) {
      return SAVE_NPERM;
    }
    fprintf(stderr, "save file \"%s\", %d pix/line\n", faxsavename, swidth);
    fputs("P5\nxxxxx\nyyyyy\n63\n", fsfile);
    /* allocate space for the one line */
    saveline = malloc(swidth + 4);
    /* do not initialize too much here, the user may change parameters
    of the picture while receiving... */
    save_wptr = NULL;
    return SAVE_OK;
  } else if (init == F_CLOSE) {
    if (!(fsfile))
      return SAVE_OK; /* no save-file open, doesn't matter */
    fprintf(stderr,"closing savefile\n");
    pos = ftell(fsfile);
    sheight = sypos;
    rewind(fsfile);
    fprintf(fsfile, "P5\n%05u\n%05u\n", swidth, sheight);
    fseek(fsfile, pos, SEEK_SET);
    fclose(fsfile);
    fsfile = NULL;
    if (saveline)
      free(saveline);
    save_wptr = NULL;
    return SAVE_OK;
  } else if (init == F_GETDIM) {
    if (!(fsfile))
      return SAVE_NFILE; /* no save-file open, can't get dimensions */
    /* now initialize all the variables... */
    fprintf(stderr, "getting image settings...");
    inc_pix = smpl_line / swidth;
    inc_line = (int)(ixoc * M_PI * 65536.0 / swidth); 
    idx_pix = idx_line = idx_p0 = 0;
    core_pix = core_line = core_start;
    save_wptr = core_wptr;
    ipix = iline = 0;
    flip = (vertical) ? 1 : 0;
    if (bot2top) flip ^= 1;
    if (right2left) flip ^= 1;
    if (flip) {
      ldpinit = saveline + (swidth - 1);
      ldpinc = -1;
      ldpend = saveline - 1;
    } else {
      ldpinit = saveline;
      ldpinc = 1;
      ldpend = saveline + swidth;
    }
    ldptr = ldpinit;
    sypos = 0;
    sheight = 0;
    return SAVE_OK;
  }
  /* no open save-file, or variables not initialized, so return */
  if (!(fsfile) || !(save_wptr)) return SAVE_NFILE;
  save_locked = 1;
  fprintf(stderr,"saving image...");
  while (core_pix < save_wptr) {
    if (invimage)
      *ldptr = dmaxval - *(unsigned char *)core_pix;
    else
      *ldptr = *(unsigned char *)core_pix;
    ldptr += ldpinc;
    if (ldptr == ldpend) {
      ldptr = ldpinit;
      sypos++;
      fwrite(saveline, swidth, 1, fsfile);

      while ((msk = XtAppPending(mainapp))) {
	XtAppProcessEvent(mainapp, msk);
      }
      idx_line += inc_line;
      iline = (idx_line >> 16) & 0xffff;
      idx_line &= 0xffff;
      core_line += iline * ((smpl_line >> 16) & 0xffff);

      /* we must also initialize the pixel-counters here ! */
      idx_p0 += iline * (smpl_line & 0xffff);
      core_line += (idx_p0 >> 16) & 0xffff;
      core_pix = core_line;
      idx_p0 &= 0xffff;
      idx_pix = idx_p0;
      ipix = 0;

      /* jump over the stuff below... */
      continue;
    }
    idx_pix += inc_pix;
    ipix = (idx_pix >> 16) & 0xffff;
    core_pix += ipix;
    idx_pix &= 0xffff;
  }
  fprintf(stderr,"done.\n");
  save_locked = 0;
  return SAVE_OK;
}

/* called when save-function has terminated writing */
void faxsave_complete(int init)
{
   /* this makes save_func call itself recursively, but should not hurt */
   save_func(F_CLOSE, 0);
}

/*
 * wait for a phasing signal, keep track of the phase-pulses, and preset
 * core_start on end of the phase_signal. This is done by correlating the
 * digitized gray-values (reduced to 1 or 0) with two sawtooth-signals,
 * each with a periode of one scan line, and one of them shifted by a
 * half scan-line against the other. This lets us find the position of
 * the phase-pulse relative to our scan-line. Lines are recognized as
 * phase-in-lines when they contain at most 3/32 and at least 1/32 of values
 * that are above (or below for inverse phase) the middle of the gray-scale.
 */
void sync_phase(int init)
{
  /* run counters, count pixels per line (16bit int, 16bit frac) */
  static int phsarc, phsbrc;
  /* accumulators for the integration */
  static int phsaacc = 0, phsbacc = 0;
  /* these are counted up until limit to form the sawtooth-signal */
  static int phsainc, phsbinc;
  /* number of sample-points processed */
  static int npoints = 0;
  /* number of points having the right level (black) for a sync pulse */
  static int nphpts = 0;
  /* minimum/maximum  number of black points per line that must be present */
  static int minphpts, maxphpts;
  static char done = 0;
  char *dtaptr;
  int pcnt;
  int i,j;

  dtaptr = demod_ptr;
  pcnt = demod_cnt;
  if (init) {
    phstate = 0;
    hsmpl_line = smpl_line >> 17;
    phsaacc = phsbacc = 0;
    phsarc = smpl_line;
    phsbrc = smpl_line >> 1;
    phsainc = - hsmpl_line;
    phsbinc = 0;
    minphpts = (smpl_line >> 16) >> 5;
    maxphpts = minphpts * 3;
    nphpts = 0;
    phlines = 0;
    done = 0;
    core_wptr = core_dta;
    core_start = core_dta;
    fprintf(stderr, "initialized sync-phase-detector\n");
    return;
  }

  while (pcnt > 0) {
      if ((!(invphase) && *dtaptr > compval) ||
	   ((invphase) && *dtaptr < compval)) {
	phsaacc += phsainc;
	phsbacc += phsbinc;
	nphpts++;
      }
      phsainc++;
      phsbinc++;
      npoints++;
      dtaptr++;
      pcnt--;
      phsarc -= 65536;
      if (phsarc <= 0) {
	done = 1; /* this indicates the end-of-line */
	phsarc += smpl_line;
	phsainc = - hsmpl_line;
      }
      phsbrc -= 65536;
      if (phsbrc <= 0) {
	phsbrc += smpl_line;
	phsbinc = - hsmpl_line;
      }
      if (done) {
#if (DEBUG & DBG_SYN)
	fprintf(stderr, "got line with %d of %d points phase-value\n",
		nphpts, npoints);
#endif
	/* check if it was probably a phase-in line */
	if (nphpts < maxphpts && nphpts > minphpts) {
	  if (phlines < 24) {
	    /* use the accumulator with the lower absolute-value */
	    if (abs(phsaacc) < abs(phsbacc)) {
	      i = phsaacc / nphpts;
#if (DEBUG & DBG_SYN)
	      fprintf(stderr, "sync line %d: A=%d\n", phlines, i);
#endif
	      phposa[phlines] = i;
	      if (i < 0)
		phsdir[phlines] = 1; /* left half */
	      else
		phsdir[phlines] = 0; /* right half */
	    } else {
	      i = phsbacc / nphpts;
#if (DEBUG & DBG_SYN)
	      fprintf(stderr, "sync line %d: B=%d\n", phlines, i);
#endif
	      phposb[phlines] = i;
	      if (i < 0)
		phsdir[phlines] = 2; /* right half */
	      else
		phsdir[phlines] = 3; /* left half */
	    }
	    if (phstate == 0) { /* first sync line */
	      phstate = 1;
	    } else if (phstate == 1) { /* any sync line */
	    }
	    phlines++;
	  } else { /* phlines >= 24 */
	    /* ignore any further sync-lines... */
	  }
	} else {
	  /* no sync line, we are still waiting for one or they have passed */
	  if (phstate == 0) {
	    /* no sync line yet - just wait ?! */
	  } else if (phstate == 1) {
	    /* now begin to compute the ultimate sync-position */
	    j = 0;
	    /* count the lines in the left half */
	    for (i=0; i<phlines; i++) {
	      if (phsdir[i] & 1) j++;
	    }
	    phaseavg = 0;
	    if (j > (phlines >> 1)) { /* more points in the left half */
#if (DEBUG & DBG_SYN)
	      fprintf(stderr, "calculating for left half...\n");
#endif
	      for (i=0; i<phlines; i++)
		if (phsdir[i] & 2)
		  phaseavg += phposb[i] - hsmpl_line;
		else
		  phaseavg += phposa[i];
	    } else { /* more points in the right half */
#if (DEBUG & DBG_SYN)
	      fprintf(stderr, "calculating for right half...\n");
#endif
	      for (i=0; i<phlines; i++)
		if (phsdir[i] & 2)
		  phaseavg += phposb[i] + hsmpl_line;
		else
		  phaseavg += phposa[i];
	    }
	    phaseavg /= phlines;
	    phaseavg += hsmpl_line;
#if (DEBUG & DBG_SYN)
	    fprintf(stderr, "phase average = %d\n", phaseavg);
#endif
	    /* now prepare the core_start pointer for reception */
	    /* calculate difference from sync-pos to end of line */
	    j = (smpl_line >> 16);
	    i = demod_cnt - pcnt + phaseavg;
	    if (i > j)
	      i -= j;
	    /* start decoding at the beginning of the core */
	    core_wptr = core_dta;
	    core_start = core_dta + i;
	    /* now enter the real reception mode. When returning into the
		fax_rx_backgnd, fax_state is set to FAX_RX so that the data
		we just processed can also be used for the picture. */
	    fax_rx_start(1);
	    /* no more data to process */
	    return;
	  }
	} /* if (sync_line_detected) */
	/* re-initialize the both accumulators and sample-point counters */
	phsaacc = 0;
	phsbacc = 0;
	npoints = 0;
	nphpts = 0;
	done = 0;
      } /* if (done) */
  } /* while (pcnt > 0) */
}

/*
 * calculate the APT frequency by counting low->high->low transitions.
 * not very nice, but it works :-S . This funcion always computes the
 * APT for 0.5 seconds, independant from demod_cnt, which can be very
 * high on systems that use a large block-size for the audio-devide.
 * After each calculation, apt_notify() is called with the frequency as
 * argument.
 */
void decode_apt(int dummy)
{
  /* how many transitions (half-waves) we have counted */
  static int apthws = 0;
  /* how many consecutive points were on one side of the comparator-value */ 
  static int aptncact = 0;
  /* the phase (black or white) we processed last time */
  static int phs = 0;
  static int npoints = 0;
  char *dtaptr;
  int pcnt;

  dtaptr = demod_ptr;
  pcnt = demod_cnt;
  /* If we have to start with the "black" phase, do it before the main-loop
     starts. This prevents us from ugly goto's (shudder) */
  if (phs) {
    while (pcnt) {
      pcnt--;
      if (++npoints >= hsmpl_sec) {
	apt_notify(apthws);
	apthws = 0;
	npoints = 0;
      }
      if (*(unsigned char *)dtaptr++ <= compval) {
	if (aptncact > aptncmax)
	  apthws = 0;
	else
	  apthws++;
	break;
      }
      aptncact++;
    }
  }
  while (pcnt > 0) {
    aptncact = 0;
    while (pcnt) {
      pcnt--;
      if (++npoints >= hsmpl_sec) {
#if (DEBUG & DBG_APT)
	fprintf(stderr,"APT freq. pos = %d\n", apthws);
#endif
	apt_notify(apthws);
	apthws = 0;
	npoints = 0;
      }
      if (*(unsigned char *)dtaptr++ > compval) {
	if (aptncact > aptncmax)
	  apthws = 0;
	else
	  apthws++;
	break;
      }
      aptncact++;
    }
    aptncact = 0;
    while (pcnt) {
      pcnt--;
      if (++npoints >= hsmpl_sec) {
#if (DEBUG & DBG_APT)
	fprintf(stderr,"APT freq. neg = %d\n", apthws);
#endif
	apt_notify(apthws);
	apthws = 0;
	npoints = 0;
      }
      if (*(unsigned char *)dtaptr++ <= compval) {
	if (aptncact > aptncmax)
	  apthws = 0;
	else
	  apthws++;
	break;
      }
      aptncact++;
    }
  }
  /* now mark the phase for the next call... */
  if (*(unsigned char *)(dtaptr-1) <= compval)
    phs = 0;
  else
    phs = 1;
}

void apt_control(int aptfrq)
{
  static int cnt;
/*
  fprintf(stderr, "apt_control: %d\n", aptfrq);
*/
  switch (fax_state) {
    /* wait for one of the valid APT frequencies */
    case FAX_APT:
	if (abs(aptfrq - aptstart) < 2) {
	  if (++cnt >= 2) fax_rx_phase(1);
	} else {
	  cnt = 0;
	}
	break;
    /* here, a new start or a stop (interrupt) may occur */
    case FAX_PHAS:
    case FAX_RX:
	if (abs(aptfrq - aptstop) < 2) {
	  if (++cnt >= 2) fax_rx_stop(1);
	} else {
	  cnt = 0;
	}
	break;
  }
}

void fax_rx_start(int internal)
{
  fprintf(stderr,"starting fax reception\n");
  /* if we come from phasing, initialize disp_func */
  if (fax_state == FAX_PHAS)
    disp_func(D_CPINIT | D_WDINIT | D_LDINIT);
  fax_state = FAX_RX;
  if (internal)
    mode_notify(fax_state);
}

void fax_rx_phase(int internal)
{
  fprintf(stderr,"entering phase-in mode\n");
  sync_phase(1);
  fax_state = FAX_PHAS;
  if (internal)
    mode_notify(fax_state);
}

void fax_rx_stop(int internal)
{
  fprintf(stderr,"stopping fax reception\n");
  fax_state = FAX_APT;
  /* flush rest of image (in horimag/verimag) */
  disp_func(D_FLUSHIMG);
  /* get current image-parameters for saving */
  save_func(F_GETDIM, 0);
  save_func(F_DOSAVE, 0);
  save_func(F_CLOSE, 0);
  if (internal)
    mode_notify(fax_state);
}

/*
 * this function is called by the callback-function of the Canvas-widget
 * to move the picture in writing-direction, when phasing in has failed
 * or was missed. px and py contain the coordinates of the button-press.
 */
void shift_fax_coords(unsigned px, unsigned py)
{
  void (*old_func)();
  unsigned tmp_pos;

  fprintf(stderr, "coords = %d, %d\n", px, py);
  old_func = disp_func;
  disp_func = NULL;
  if (vertical) {
    if (bot2top)
	tmp_pos = smpl_line / canhei * (canhei - py);
    else
	tmp_pos = smpl_line / canhei * py;
  } else {
    if (right2left)
	tmp_pos = smpl_line / canwid * (canwid - px);
    else
	tmp_pos = smpl_line / canwid * px;
  }
  core_start += (tmp_pos >> 16);
  tmp_pos = (smpl_line >> 16);
  if (core_start - core_dta > tmp_pos)
    core_start -= tmp_pos;
  old_func (D_CPINIT | D_WDINIT | D_LDINIT);
  old_func (D_ALLOWX);
  disp_func = old_func;
}

/*
 * this function is called by the callback-function of the Canvas-widget
 * to re-adjust the sampling frequency to correct the line-shifting
 * caused by slightly deadjusted samling frequency.
 */
void correct_fax_azimut(int dx, int dy)
{
  void (*old_func)();
  int flip;
  int df;

  fprintf(stderr, "coords = %d, %d\n", dx, dy);
  flip = 0;
  if (right2left) flip ^= 1;
  if (bot2top) flip ^= 1;
  if (vertical) {
    df = (smplf * (double)dy) / (dx * M_PI * ixoc);
  } else {
    df = (smplf * (double)dx) / (dy * M_PI * ixoc);
  }
  if (flip) df = -df;
  smplf += df;
  fprintf(stderr, "delta freq.=%2.3f smplf=%4.3f\n",
	(double)df / 65536.0, (double)smplf / 65536.0);
  tune_frequency(smplf);

  old_func = disp_func;
  disp_func = NULL;
  old_func (D_CPINIT | D_WDINIT | D_LDINIT);
  old_func (D_ALLOWX);
  disp_func = old_func;
}

/*----------------------- FAX transmission --------------------------*/

void fax_tx_stop(int internal)
{
  fprintf(stderr,"stopping FAX-transmission\n");
  if (internal)
    mode_notify(fax_state);
}

void fax_tx_start(int internal)
{
  fprintf(stderr,"transmitting image\n");
  fax_state = FATX_TX;
  fax_tx_func(D_WDINIT | D_LDINIT);
  if (internal)
    mode_notify(fax_state);
}

void fax_tx_apta(int internal)
{
  fprintf(stderr,"transmitting APT-start\n");
  transmit_apt(APTX_ISTART);
  fax_state = FATX_APTA;
  if (internal)
    mode_notify(fax_state);
}

void fax_tx_aptb(int internal)
{
  fprintf(stderr,"transmitting APT-stop\n");
  transmit_apt(APTX_ISTOP);
  fax_state = FATX_APTB;
  if (internal)
    mode_notify(fax_state);
}

void fax_tx_phase(int internal)
{
  fprintf(stderr,"entering TX-phase-in mode\n");
  transmit_phase(1);
  fax_state = FATX_PHAS;
  if (internal)
    mode_notify(fax_state);
}

int load_txfile(char *name)
{
  char line[80];
  char lctab[256];
  char *pline, *sp;
  int ncols;
  int color;
  char *cp;
  int i,j;

  if (timg_ptr)
    free(timg_ptr);
  if ((ftfile = fopen(name, "rb")) == NULL) {
    perror("open_txfile");
    return -1;
  }
  if (fgets(line, 79, ftfile) == NULL) {
    perror("read_format");
    return -1;
  }
  if (!strcmp(line, "P5\n"))
    color = 0;
  else if (!strcmp(line, "P6\n"))
    color = 1;
  else
    return -2; /* unrecognized format */
  if (color)
    return -3; /* not yet supported */
  do {
    if (fgets(line, 79, ftfile) == NULL) {
      perror("read_header");
      return -1;
    }
  } while (*line == '#');
  twidth = atoi(line);
  if (fgets(line, 79, ftfile) == NULL) {
    perror("read_header");
    return -1;
  }
  theight = atoi(line);
  if (fgets(line, 79, ftfile) == NULL) {
    perror("read_header");
    return -1;
  }
  timg_ptr = malloc(twidth*theight);
  pline = malloc(twidth);
  if (!(timg_ptr) || !(pline)) {
    if (timg_ptr) free(timg_ptr);
    if (pline) free(pline);
    perror("alloc_txmem");
    return -4;
  }
  ncols = atoi(line) + 1;
  if (ncols > 256)
    return -3;
  for (i=0; i<ncols; i++)
    lctab[i] = (64 * i) / ncols;
  cp = timg_ptr;
  for (i=0; i<theight; i++) {
    if (fread(pline, twidth, 1, ftfile) != 1) {
      perror("read_pixmap");
      free(timg_ptr);
      free(pline);
      return -5;
    }
    sp = pline;
    for (j=0; j<twidth; j++)
      *cp++ = lctab[*(unsigned char *)sp++];
  }
  free(pline);
  fclose(ftfile);
  return 0;
}

/*
 * Fax-transmission background-routine :
 * This works a little different from the receiving-routine.
 * Transmission-data is not stored in a core-space, it is
 * transmitted directly out of the image-memory. Every function
 * called here must keep track of the pointer in the decptr-space
 * and give back control if the task is done or the pointer has reached
 * the end of the buffer.
 */
#ifdef DSP_SELECT
void fax_tx_backgnd(XtPointer client_data, int *source, XtInputId *xid)
#else
void fax_tx_backgnd(XtPointer client_data, XtIntervalId *xid)
#endif
{
  int space;

  /* if we are in the phasing state, compute the phase-position */
  if (fax_state == FATX_APTA)
    transmit_apt(0);

  if (fax_state == FATX_PHAS)
    transmit_phase(0);

  if (fax_state == FATX_TX)
    fax_tx_func(0);

  if (fax_state == FATX_APTB)
    transmit_apt(0);

#ifdef DSP_SELECT
#else
  /* add a new timeout to call this function again */
/*
  printf("adding new timeout\n");
*/
  chstime = XtAppAddTimeOut(mainapp, 250, fax_rx_backgnd, (XtPointer) NULL);
#endif

  /* if disp_func is set, call that function (e.g. main FAX decoder loop) */
  if ((disp_func) && !(disp_locked)) {
/*
    fprintf(stderr, "calling disp_func\n");
*/
    fax_tx_func(0);
  }
/*
  fprintf(stderr, "transmitting data\n");
*/
  do_transmit();
}

void transmit_fax_gray(int init)
{
  /* pointer to sample-point for current pixel and current start-of-line */
  static char *timg_line, *timg_pix;
  /* sample-values per line or per pixel-value, 16bit int, 16bit frac */
  static unsigned inc_pix, inc_line, inc_p0;
  /* current index to pixel or line in sample-array, 16bit int, 16bit frac */
  static unsigned idx_pix, idx_line, idx_p0;
  /* increment between actual and previous pixel/line position */
  static unsigned ipix, iline;
  /* pixel-in-line-position start/increment/end */
  static int pixinit, pixinc, pixend;
  /* line-in-image-position start/increment/end, max. line of XImage */
  static int lineinit, lineinc, lineend, imgmax;
  static int (*put_pix)(struct _XImage *, int, int, unsigned long);
  /* bytes per line or per pixel, depends on direction (hor, vert, r2l, b2t) */
  static int bytes_per_line, bytes_per_pixel;

  if (init & D_INITS) {
    /* smpl_line is the number of core_dta points per line << 16 */
    smpl_line = 60.0 / lpm * smplf;
    if (vertical) {
      inc_pix = smpl_line / theight;
      inc_line = (int)(ixoc * M_PI * 65536.0 / theight); 
      imgmax = DEFWIDTH;
      put_pix = verimag->f.put_pixel;
      bytes_per_pixel = twidth;
      bytes_per_line = 1;
    } else {
      inc_pix = smpl_line / twidth;
      inc_line = (int)(ixoc * M_PI * 65536.0 / twidth); 
      imgmax = DEFHEIGHT;
      put_pix = horimag->f.put_pixel;
      bytes_per_pixel = 1;
      bytes_per_line = twidth;
    }
    if (!(vertical) && (right2left)) {
      pixinit = twidth - 1;
      pixinc = -1;
      pixend = -1;
      bytes_per_pixel = -bytes_per_pixel;
    } else
    if ((vertical) && (bot2top)) {
      pixinit = theight - 1;
      pixinc = -1;
      pixend = -1;
      bytes_per_pixel = -bytes_per_pixel;
    } else {
      pixinit = 0;
      pixinc = 1;
      pixend = (vertical) ? theight : twidth;
    }
    /* initialize the line-advance variables and pointers */
    if (!(vertical) && (bot2top)) {
        lineinit = theight - 1;
        lineinc = -1;
        lineend = -1;
	bytes_per_line = -bytes_per_line;
    } else
    if ((vertical) && (right2left)) {
        lineinit = twidth - 1;
        lineinc = -1;
        lineend = -1;
	bytes_per_line = -bytes_per_line;
    } else {
        lineinit = 0;
        lineinc = 1;
        lineend = (vertical) ? twidth : theight;
    }
  }


  if (init) {
    timg_line = timg_ptr;
    /* twidth, theight, timg_ptr */
    if (vertical) {
      inc_pix = 65536.0 * theight * lpm / ((60.0/65536.0) * smplf);
      inc_line = 65536.0 * theight / (M_PI * ixoc);
    } else {
      inc_pix = 65536.0 * twidth * lpm / ((60.0/65536.0) * smplf);
      inc_line = 65536.0 * twidth / (M_PI * ixoc);
    }
      if (right2left) {
	pixinc = -1;
	timg_line += (twidth - 1);
      } else {
	pixinc = 1;
      }
      if (bot2top) {
	pixinc = -twidth;
	timg_line += (theight - 1) * twidth;
      } else {
	pixinc = twidth;
      }
      timg_pix = timg_line;
    inc_p0 = 0;
    return;
  }
  while (mod_ptr < mod_end) {
    *mod_ptr++ = *timg_pix;

    pixpos += pixinc;
    if (pixpos == pixend) {
      pixpos = pixinit;
      linepos += lineinc;
      if (linepos == lineend) {
	/* we have transmitted the entire picture ! */
	break;
      }
      idx_line += inc_line;
      iline = (idx_line >> 16) & 0xffff;
      idx_line &= 0xffff;
      timg_pix += bytes_per_pixel;
      timg_pix += iline * twidth; /* twidth == bytes_per_line */
      continue; /* jump over stuff below */
    }
    idx_pix += inc_pix;
    ipix = (idx_pix >> 16) & 0xffff;
    idx_pix &= 0xffff;
    timg_pix += ipix * bytes_per_pixel;
  }
  fax_tx_aptb(1);
}

/*
 * transmit an APT-tone. This function returns if either the pointer to
 * decptr reaches the end of the buffer or the duration is reached.
 * init can have the following values :
 * APTX_ISTART: initialize for aptstart-frequency
 * APTX_ISTOP:	initialize for apt stop-frequency
 * 0:		start/continue transmission
 */
void transmit_apt(int init)
{
  XtInputMask msk;
  static int acc = 0;
  static int ap_inc;
  static int dur;

  if (init == APTX_ISTART) {
    ap_inc = 4.294967296e6 * aptstart / (double) smplf;
    dur = (smplf >> 16) * aptdur / 1000;
    return;
  } else if (init == APTX_ISTOP) {
    ap_inc = 4.294967296e6 * aptstop / (double) smplf;
    dur = (smplf >> 16) * aptdur / 1000;
    return;
  }
  while ((dur > 0) && (mod_ptr < mod_end)) {
      acc += ap_inc;
      if (acc & 0x8000)
	*mod_ptr = dmaxval;
      else
	*mod_ptr = 0;
      mod_ptr++;
      dur--;
  }
  if (mod_ptr >= mod_end)
    mod_ptr = demod_ptr;
  if (dur <= 0) {
      if (fax_state == FATX_APTA)
	fax_tx_phase(1);
      else
	fax_tx_stop(1);
  }
}

/*
 * transmit the phase-in signal for the image, which consists of 95% black
 * and 5% white (or inverted if invphase is set). These 5% have to appear
 * as one half to both the left and right margin of the image. The phase
 * where we start is not important, but where we stop and give control
 * to the function transmitting the contents of the loaded image.
 * tx_phlines determines the number of lines for phasing, after which
 * a line with 100% white is intersected to start the receiver.
 * if init is set, variables are initialized and the function returns.
 */
void transmit_phase(int init)
{
  static int inc_pix;
  static int idx_pix;
  static int idx_min, idx_max;
  static int txlines;

  if (init) {
    inc_pix = lpm * (double) smplf / 60;
    idx_min = 1638;
    idx_max = 63807;
    idx_pix = 0x8000;
    txlines = tx_phlines + 1;
    return;
  }
  while ((txlines >= 0) && (mod_ptr < mod_end)) {
    idx_pix += inc_pix;
    if (idx_pix > 63807 || idx_pix < 1638)
     *mod_ptr = (invphase ? 0 : dmaxval);
    else
     *mod_ptr = (invphase ? dmaxval : 0);
    mod_ptr++;
    if (idx_pix > 0xffff)
      txlines--;
    idx_pix &= 0xffff;
  }
  if (mod_ptr >= mod_end)
    mod_ptr = demod_ptr;
  if (txlines <= 0)
    fax_tx_start(1);
}