summaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
authorhibby <d@vehibberd.com>2026-10-06 21:24:40 +0100
committerhibby <d@vehibberd.com>2026-10-06 21:24:40 +0100
commitc25cbdf6fb6d946175f4335fab77bfea601b56db (patch)
tree6f7a94b7b81f999e434f61b73d47e337dfd26bf2 /lib
parent71f5689252c9f13e70e1c24856904475b2307809 (diff)
parent0685fcada9f95fe90f70b387cd7d757da8209624 (diff)
Merge tag 'debian/3.2.0_rc1+dfsg-2' into debian/trixie-backportsdebian/trixie-backports
tagging wsjtx 3.2.0~rc1+dfsg-2
Diffstat (limited to 'lib')
-rw-r--r--lib/77bit/77bit.txt36
-rw-r--r--lib/77bit/encode77.f90103
-rw-r--r--lib/77bit/packjt77.f904496
-rw-r--r--lib/77bit/packjt77_grammar.f901530
-rw-r--r--lib/77bit/packjt77_schema.f90871
-rw-r--r--lib/EchoCallSim.f9035
-rw-r--r--lib/addit.f901
-rw-r--r--lib/afc9.f906
-rw-r--r--lib/allsim.f904
-rw-r--r--lib/astro.f9031
-rw-r--r--lib/astro0.f9097
-rw-r--r--lib/astrosub.f9019
-rw-r--r--lib/avecho.f908
-rw-r--r--lib/blanker.f901
-rw-r--r--lib/ccf2.f902
-rw-r--r--lib/cwsim.f90100
-rw-r--r--lib/decode_completion.f9090
-rw-r--r--lib/decode_echo.f902
-rw-r--r--lib/decode_msk144.f9069
-rw-r--r--lib/decoder.f901499
-rw-r--r--lib/decoder_callbacks.f90718
-rw-r--r--lib/decoder_ipc_atomic.f9049
-rw-r--r--lib/decoder_ipc_control.cpp191
-rw-r--r--lib/decoder_ipc_control.h40
-rw-r--r--lib/digi-contest.txt3
-rw-r--r--lib/echo_snr.f9010
-rw-r--r--lib/echosim.f9077
-rw-r--r--lib/emedop.f9047
-rw-r--r--lib/ephem.f90213
-rw-r--r--lib/fil4.f9019
-rw-r--r--lib/flat4.f903
-rw-r--r--lib/fst4/fastosd240_74.f901
-rw-r--r--lib/fst4/fst4sim.f9037
-rw-r--r--lib/fst4/gen_fst4wave.f9054
-rw-r--r--lib/fst4/genfst4.f9032
-rw-r--r--lib/fst4/get_fst4_bitmetrics.f902
-rw-r--r--lib/fst4/ldpcsim240_101.f9014
-rw-r--r--lib/fst4/osd240_101.f904
-rw-r--r--lib/fst4/osd240_74.f904
-rw-r--r--lib/fst4_decode.f9010
-rw-r--r--lib/ft2/ft2.f90279
-rw-r--r--lib/ft2/ft2.ini2
-rw-r--r--lib/ft2/ft2_decode.f90298
-rw-r--r--lib/ft2/ft2_gfsk_iwave.f9088
-rw-r--r--lib/ft2/ft2_iwave.f9064
-rw-r--r--lib/ft2/ft2_params.f9012
-rw-r--r--lib/ft2/g4.cmd7
-rw-r--r--lib/ft2/gcom1.f9034
-rw-r--r--lib/ft2/genft2.f9086
-rw-r--r--lib/ft2/getcandidates2a.f9064
-rw-r--r--lib/ft2/libportaudio.abin1065188 -> 0 bytes
-rw-r--r--lib/ft2/libwsjt_cxx.abin192392 -> 0 bytes
-rw-r--r--lib/ft2/libwsjt_fort.abin1699980 -> 0 bytes
-rw-r--r--lib/ft2/ptt.c58
-rw-r--r--lib/ft2/ptt_unix.c341
-rw-r--r--lib/ft4/ft4code.f9013
-rw-r--r--lib/ft4/ft4sim.f9016
-rw-r--r--lib/ft4/ft4sim_mult.f902
-rw-r--r--lib/ft4/gen_ft4wave.f904
-rw-r--r--lib/ft4/genft4.f907
-rw-r--r--lib/ft4_decode.f909
-rw-r--r--lib/ft8/compress.f901
-rw-r--r--lib/ft8/foxgen.f902
-rw-r--r--lib/ft8/ft8_a7.f9011
-rw-r--r--lib/ft8/ft8_a8_test.f902
-rw-r--r--lib/ft8/ft8_a8d.f906
-rw-r--r--lib/ft8/ft8b.f9013
-rw-r--r--lib/ft8/ft8c.f907
-rw-r--r--lib/ft8/ft8sim.f9013
-rw-r--r--lib/ft8/genft8.f908
-rw-r--r--lib/ft8/ldpcsim174_91.f902
-rw-r--r--lib/ft8/sync8.f904
-rw-r--r--lib/ft8_decode.f903
-rw-r--r--lib/ft8var/agccft8.f902
-rw-r--r--lib/ft8var/cwfilter.f9018
-rw-r--r--lib/ft8var/fillhashvar.f9065
-rw-r--r--lib/ft8var/four2avar.f9013
-rw-r--r--lib/ft8var/ft4_mod1.f903
-rw-r--r--lib/ft8var/ft8_decode_ranges.f9038
-rw-r--r--lib/ft8var/ft8_decodevar.f90135
-rw-r--r--lib/ft8var/ft8_downsamplevar.f9026
-rw-r--r--lib/ft8var/ft8_mod1.f909
-rw-r--r--lib/ft8var/ft8_mtd_residual.f90459
-rw-r--r--lib/ft8var/ft8_tsan.c30
-rw-r--r--lib/ft8var/ft8apsetvar.f9077
-rw-r--r--lib/ft8var/ft8bvar.f9094
-rw-r--r--lib/ft8var/ft8mf1var.f903
-rw-r--r--lib/ft8var/ft8mfcqvar.f907
-rw-r--r--lib/ft8var/ft8sd1var.f907
-rw-r--r--lib/ft8var/ft8sdvar.f907
-rw-r--r--lib/ft8var/ft8svar.f9030
-rw-r--r--lib/ft8var/gen_ft8wavevar.f901
-rw-r--r--lib/ft8var/genft8sdvar.f9014
-rw-r--r--lib/ft8var/genft8var.f9012
-rw-r--r--lib/ft8var/jt65_mod9.f902
-rw-r--r--lib/ft8var/osd174_91var.f9020
-rw-r--r--lib/ft8var/packjt77sdvar.f90558
-rw-r--r--lib/ft8var/subtractft8var.f9027
-rw-r--r--lib/ft8var/sync8dvar.f9020
-rw-r--r--lib/ft8var/sync8var.f9058
-rw-r--r--lib/ft8var/tone8.f9064
-rw-r--r--lib/ft8var/tonesdvar.f9037
-rw-r--r--lib/gen_cw_wave.f901
-rw-r--r--lib/genmsk_128_90.f9013
-rw-r--r--lib/get_q3list.f9099
-rw-r--r--lib/gfsk_pulse.f90 (renamed from lib/ft2/gfsk_pulse.f90)0
-rw-r--r--lib/hspec.f903
-rw-r--r--lib/jpl_ephemeris_status.f9029
-rw-r--r--lib/jplsubs.f322
-rw-r--r--lib/jt4.f903
-rw-r--r--lib/jt49sim.f902
-rw-r--r--lib/jt4_decode.f903
-rw-r--r--lib/jt4sim.f902
-rw-r--r--lib/jt65.f9025
-rw-r--r--lib/jt65_decode.f9019
-rw-r--r--lib/jt65_mod.f902
-rw-r--r--lib/jt65sim.f902
-rw-r--r--lib/jt9.f90308
-rw-r--r--lib/jt9_input_validation.f90158
-rw-r--r--lib/jt9_params_init.f90241
-rw-r--r--lib/jt9_version.c20
-rw-r--r--lib/jt9a.f90151
-rw-r--r--lib/jt9a_stub.f9012
-rw-r--r--lib/jt9com.f9022
-rw-r--r--lib/jt9sim.f902
-rw-r--r--lib/jtty/JTTY Messages.mc44
-rw-r--r--lib/jtty/ana64a.f9019
-rw-r--r--lib/jtty/c_funcs.f9013
-rw-r--r--lib/jtty/cdatetime.f90 (renamed from lib/ft2/cdatetime.f90)0
-rw-r--r--lib/jtty/decodes.txt463
-rw-r--r--lib/jtty/gen_jttywave.f90110
-rw-r--r--lib/jtty/gen_syncwave.f9026
-rw-r--r--lib/jtty/genjtty.f90161
-rw-r--r--lib/jtty/jtty.f9060
-rw-r--r--lib/jtty/jtty.ini3
-rw-r--r--lib/jtty/jtty_block_pow.f90101
-rw-r--r--lib/jtty/jtty_codewords.f9016
-rw-r--r--lib/jtty/jtty_decode.f90192
-rw-r--r--lib/jtty/jtty_design.md145
-rw-r--r--lib/jtty/jtty_design.txt231
-rw-r--r--lib/jtty/jtty_fec_mod.f9019
-rw-r--r--lib/jtty/jtty_mdecode.f901228
-rw-r--r--lib/jtty/jtty_mod.f90447
-rw-r--r--lib/jtty/jtty_msgs.txt23
-rw-r--r--lib/jtty/jtty_n1mm_integration.md140
-rw-r--r--lib/jtty/jtty_payload_correlators.f90108
-rw-r--r--lib/jtty/jtty_peakup.f90146
-rw-r--r--lib/jtty/jtty_source_codec.f90470
-rw-r--r--lib/jtty/jtty_source_encoding.txt380
-rw-r--r--lib/jtty/jtty_spec.f9040
-rw-r--r--lib/jtty/jtty_tbcc_code_profile.f90106
-rw-r--r--lib/jtty/jtty_tbcc_decoder.f90151
-rw-r--r--lib/jtty/jtty_tbcc_list_decoder.f901168
-rw-r--r--lib/jtty/jtty_tx_manual_checks.md65
-rw-r--r--lib/jtty/jttyaudio.c (renamed from lib/ft2/ft2audio.c)105
-rw-r--r--lib/jtty/jttycom.f9031
-rw-r--r--lib/jtty/portaudio.h (renamed from lib/ft2/portaudio.h)0
-rw-r--r--lib/jtty/rjtty.f9085
-rw-r--r--lib/jtty/rjtty_sub.f90102
-rw-r--r--lib/jtty/sjtty.f90258
-rw-r--r--lib/jtty/sjtty_qrm.f90238
-rw-r--r--lib/jtty/subtract_jtty.f9099
-rw-r--r--lib/jtty/tbcc.f90422
-rw-r--r--lib/jtty/transmit.f9055
-rw-r--r--lib/jtty/update.f90144
-rw-r--r--lib/jtty/wava/plot_results.py57
-rw-r--r--lib/jtty/wava/rcu_bound_4fsk.f90217
-rw-r--r--lib/jtty/wava/tbcc_4fsk_simulation.f90167
-rw-r--r--lib/jtty/wava/tbcc_performance_curves.pngbin0 -> 263436 bytes
-rw-r--r--lib/lookup3.c305
-rw-r--r--lib/lookup3.h18
-rw-r--r--lib/map65_mmdec.f90100
-rw-r--r--lib/moondopjpl.f9024
-rw-r--r--lib/morse.f9050
-rw-r--r--lib/msk144_freq_search.f9020
-rw-r--r--lib/msk144code.f9013
-rw-r--r--lib/msk144sim.f902
-rw-r--r--lib/msk144spd.f9036
-rw-r--r--lib/msk144sync.f902
-rw-r--r--lib/msk40_freq_search.f9020
-rw-r--r--lib/msk40spd.f9036
-rw-r--r--lib/msk40sync.f9012
-rw-r--r--lib/msk_spectrum.f9059
-rw-r--r--lib/options.f904
-rw-r--r--lib/osd128_90.f903
-rw-r--r--lib/packjt.f9020
-rw-r--r--lib/plotsave.f9020
-rw-r--r--lib/print_version.c16
-rw-r--r--lib/ptt.c7
-rw-r--r--lib/q65_decode.f9032
-rw-r--r--lib/qra/q65/genq65.f9020
-rw-r--r--lib/qra/q65/normrnd.c2
-rw-r--r--lib/qra/q65/q65.c10
-rw-r--r--lib/qra/q65/q65.f908
-rw-r--r--lib/qra/q65/q65.h5
-rw-r--r--lib/qra/q65/q65_ap.f9032
-rw-r--r--lib/qra/q65/q65_encoding_modules.f9031
-rw-r--r--lib/qra/q65/q65_ftn_test.f909
-rw-r--r--lib/qra/q65/q65_loops.f9024
-rw-r--r--lib/qra/q65/q65_set_list.f902
-rw-r--r--lib/qra/q65/q65_set_list2.f9036
-rw-r--r--lib/qra/q65/q65_workspace.f9043
-rw-r--r--lib/qra/q65/q65code.f9011
-rw-r--r--lib/qra/q65/q65sim.f9014
-rw-r--r--lib/qso50/g04
-rw-r--r--lib/readwav.f90142
-rw-r--r--lib/refspectrum.f9048
-rw-r--r--lib/rig_control.c7
-rw-r--r--lib/rtty_spec.f902
-rw-r--r--lib/save_dxbase.f909
-rw-r--r--lib/savec2.f9033
-rw-r--r--lib/sec_midn.f905
-rw-r--r--lib/sh65.f902
-rw-r--r--lib/shmem.cpp2
-rw-r--r--lib/shmem.f9010
-rw-r--r--lib/sleep_msec.f903
-rw-r--r--lib/spec64.f9011
-rw-r--r--lib/spec_qra65.f904
-rw-r--r--lib/stdmsg.f9034
-rw-r--r--lib/stream_setmode.c24
-rw-r--r--lib/stream_stdin.c49
-rw-r--r--lib/streaming_apply.f90328
-rw-r--r--lib/streaming_control.f901779
-rw-r--r--lib/streaming_emit.f90288
-rw-r--r--lib/streaming_io.f90466
-rw-r--r--lib/subtract65.f902
-rw-r--r--lib/sumsim.f902
-rw-r--r--lib/superfox/qpc/nhash2.c382
-rw-r--r--lib/superfox/qpc/nhash2.h7
-rw-r--r--lib/superfox/qpc/np_rnd.c2
-rw-r--r--lib/superfox/qpc_decode2.f906
-rw-r--r--lib/superfox/qpc_sync.f9023
-rw-r--r--lib/superfox/ran1.f9018
-rw-r--r--lib/superfox/sfox_pack.f90249
-rw-r--r--lib/superfox/sfox_remove_ft8.f907
-rw-r--r--lib/superfox/sfox_remove_tone.f901
-rw-r--r--lib/superfox/sfox_unpack.f9031
-rw-r--r--lib/superfox/sfoxsim.f907
-rw-r--r--lib/superfox/sfrx_sub.f905
-rw-r--r--lib/superfox/sftx.f9021
-rw-r--r--lib/superfox/sftx_sub.f9015
-rw-r--r--lib/superfox/superfox_qpc_2.txt5
-rw-r--r--lib/symspec.f901
-rw-r--r--lib/testEchoCall.f90108
-rw-r--r--lib/tweak1.f905
-rw-r--r--lib/twkfreq.f909
-rw-r--r--lib/types.f901
-rw-r--r--lib/vit213.c6
-rw-r--r--lib/wav12.f901
-rw-r--r--lib/wqencode.f904
-rw-r--r--lib/wsprcode/go.sh2
-rw-r--r--lib/wsprcode/nhash.c389
-rw-r--r--lib/wsprcode/wspr_old_subs.f9010
-rw-r--r--lib/wsprd/Makefile9
-rw-r--r--lib/wsprd/Makefile.MinGW8
-rw-r--r--lib/wsprd/Makefile.win3211
-rw-r--r--lib/wsprd/nhash.c383
-rw-r--r--lib/wsprd/osdwspr.f902
-rw-r--r--lib/wsprd/wsprd.c180
-rw-r--r--lib/wsprd/wsprd_stream.c571
-rw-r--r--lib/wsprd/wsprd_stream.h33
-rw-r--r--lib/wsprd/wsprd_utils.c156
-rw-r--r--lib/wsprd/wsprd_utils.h10
-rw-r--r--lib/wsprd/wsprsimf.f904
-rw-r--r--lib/xcor.f903
265 files changed, 21717 insertions, 8582 deletions
diff --git a/lib/77bit/77bit.txt b/lib/77bit/77bit.txt
index ae8f3dd3..1ff7c117 100644
--- a/lib/77bit/77bit.txt
+++ b/lib/77bit/77bit.txt
@@ -11,26 +11,21 @@ i3.n3 Example message Bits Total Purpose
----------------------------------------------------------------------------------
0.0 FREE TEXT MSG 71 71 Free text
0.1 K1ABC RR73; W9XYZ <KH1/KH7Z> -12 28 28 10 5 71 DXpedition Mode
-0.2 ... tbd
+0.2 (reserved)
0.3 WA9XYZ KA1ABC R 16A EMA 28 28 1 4 3 7 71 ARRL Field Day
0.4 WA9XYZ KA1ABC R 32A EMA 28 28 1 4 3 7 71 ARRL Field Day
0.5 123456789ABCDEF012 71 71 Telemetry (18 hex)
-0.6 Temporarily hijacked in packjt77 for WSPR-LF. This is not necessary!
-0.7 ... tbd
+0.6 K1ABC FN42 37 WSPR-LF (?)
+0.7 (reserved)
1 WA9XYZ/R KA1ABC/R R FN42 28 1 28 1 1 15 74 Standard msg
2 PA3XYZ/P GM4ABC/P R JO22 28 1 28 1 1 15 74 EU VHF contest
3 TU; W9XYZ K1ABC R 579 MA 1 28 28 1 3 13 74 ARRL RTTY Roundup
4 <WA9XYZ> PJ4/KA1ABC RR73 12 58 1 2 1 74 Nonstandard calls
5 <G4ABC/P> <PA9XYZ> R 570007 JO22DB 12 22 1 3 11 25 74 EU VHF Contest
-6 ... tbd
-7 ... tbd
+6 (reserved)
+7 (reserved)
----------------------------------------------------------------------------------
-NB: three 74-bit message types and two 71-bit message subtypes are still TBD.
-----------------------------------------------------------------------------------
-
-The 28-bit fields normally used for callsigns are configured rather
-differently from before.
Facts about the 28-bit integers used to encode standard callsigns:
2^28 = 268,435,456 Available values
@@ -47,17 +42,11 @@ Further details on message types:
i3.n3
-----------------------------------------------------------------------------
0.0 Free text, up to 13 characters.
-
0.1 DXpedition mode, as developed for KH1/KH7Z.
-
-0.2 Report, QSO serial number from 0001 to 4095, 6-character grid, and Roger
- for EU VHF contests.
-
0.3 ARRL Field Day exchange (1-16 transmitters).
-
0.4 ARRL Field Day exchange (17-32 transmitters).
-
0.5 Telemetry, 71 bits
+0.6 WSPR-style
1. Two callsigns, Roger, and grid or report. Each callsign may have
an appended "/R" to indicate Rover status for NA VHF contests.
@@ -70,15 +59,12 @@ i3.n3
beginning to finish a previous QSO; then two standard callsigns,
optional "R", a 3-bit report (529 to 599), and 13 bits to indicate
US state, Canadian province/territory, or DX serial number from
- 0001 to 7999.
+ 0001 to 7999. (*** Obsolete: RTTY Roundup now allows only standard
+ Baudot RTTY ***)
4. One hashed call or "CQ"; one compound or nonstandard call with up
to 11 characters; and (if not "CQ") an optional RRR, RR73, or 73.
----------------------------------------------------------------------------
-The following are tentative and not included in first release.
-
-5. CQ WW RTTY - US/Can: RST CQZ state/prov R 579 5 NJ R1 r3 z6 u7
- DX: RST + CQzone R 559 15 R1 r3 z6
-
-6. CQ WPX RTTY - RST + serial R 589 0013 R1 r3 n12
+5. Two hashed callsigns (one 12-bit and one 22-bit), optional "R", 3-bit
+ report (52 to 59), 4-digit serial number (0001 - 2047), 6-character
+ grid locator. For EU VHF contest.
diff --git a/lib/77bit/encode77.f90 b/lib/77bit/encode77.f90
index 99af70cd..f3d64b93 100644
--- a/lib/77bit/encode77.f90
+++ b/lib/77bit/encode77.f90
@@ -1,31 +1,41 @@
program encode77
use packjt77
-
+
+ implicit none
+
character*80 msg0
- character msg*37,cerr*1
+ character msg*37
character*77 c77
character*80 infile
character*13 w(19)
+ character*40 status_text
+ character*5 type_text
integer nw(19)
logical unpk77_success
+ integer nargs,iz,iline,i3,n3,nwords,j2,pack_status
+ integer nencoded,nrejected,nunpack_failed,ndifferent
nargs=iargc()
if(nargs.ne.1 .and.nargs.ne.2) then
print*,'Usage: encode77 "message"'
print*,' encode77 -f <infile>'
- go to 999
+ stop 2
endif
call getarg(1,msg0)
- call fmtmsg(msg0,iz)
if(nargs.eq.2) then
call getarg(2,infile)
open(10,file=infile,status='old')
write(*,1000)
-1000 format('i3.n3 Err Message to be encoded Decoded message' &
- /80('-'))
+1000 format('Type Result Message to be encoded Decoded message or reason' &
+ /96('-'))
endif
-
+
+ nencoded=0
+ nrejected=0
+ nunpack_failed=0
+ ndifferent=0
+
do iline=1,999
if(nargs.eq.2) read(10,1002,end=999) msg0
1002 format(a80)
@@ -34,27 +44,80 @@ program encode77
if(msg0(2:2).eq.'.' .or. msg0(3:3).eq.'.') cycle
if(msg0(1:3).eq.'---') cycle
msg0=adjustl(msg0)
- i3=-1
- n3=-1
- call pack77(msg0(1:37),i3,n3,c77)
- call unpack77(c77,1,msg,unpk77_success)
- cerr=' '
- if(msg.ne.msg0(1:37)) cerr='*'
- if(i3.eq.0 .and.n3.ne.6) write(*,1004) i3,n3,cerr,msg0(1:37),msg
-1004 format(i2,'.',i1,4x,a1,1x,a37,1x,a37)
+ call fmtmsg(msg0,iz)
+ call pack77(msg0(1:37),i3,n3,c77,status=pack_status)
+ if(pack_status.ne.PACK77_STATUS_ENCODED) then
+ nrejected=nrejected+1
+ status_text=pack77_status_text(pack_status)
+ write(*,1004) '--','REJECTED',msg0(1:37),trim(status_text)
+ if(nargs.eq.1) stop 1
+ cycle
+ endif
+
+ nencoded=nencoded+1
+ call unpack77(c77,0,msg,unpk77_success)
+ if(.not.unpk77_success) then
+ nunpack_failed=nunpack_failed+1
+ write(*,1004) '--','UNPACK FAIL',msg0(1:37),'--'
+ if(nargs.eq.1) stop 1
+ cycle
+ endif
+
+ type_text=' '
if(i3.eq.0 .and.n3.eq.6) then
call split77(msg,nwords,nw,w)
j2=0
if(nwords.eq.2 .and. len(trim(w(2))).le.2) j2=1
if(nwords.eq.2 .and. len(trim(w(2))).eq.6) j2=2
- write(*,1005) i3,n3,j2,cerr,msg0(1:37),msg
-1005 format(i2,'.',i1,'.',i1,2x,a1,1x,a37,1x,a37)
+ write(type_text,1005) i3,n3,j2
+1005 format(i1,'.',i1,'.',i1)
+ else if(i3.eq.0) then
+ write(type_text,1006) i3,n3
+1006 format(i1,'.',i1)
+ else
+ write(type_text,1007) i3
+1007 format(i1)
endif
- if(i3.ge.1) write(*,1006) i3,cerr,msg0(1:37),msg
-1006 format(i2,'.',5x,a1,1x,a37,1x,a37)
+
+ if(msg.eq.msg0(1:37)) then
+ write(*,1004) trim(type_text),'OK',msg0(1:37),msg
+ else
+ ndifferent=ndifferent+1
+ write(*,1004) trim(type_text),'DIFF',msg0(1:37),msg
+ endif
+1004 format(a5,1x,a11,1x,a37,1x,a)
if(nargs.eq.1) exit
enddo
-999 end program encode77
+999 if(nargs.eq.2) then
+ write(*,1010) nencoded,nrejected,nunpack_failed,ndifferent
+1010 format(/'Summary: ',i0,' encoded, ',i0,' rejected, ',i0, &
+ ' unpack failures, ',i0,' differences')
+ endif
+
+ if(nrejected.gt.0 .or. nunpack_failed.gt.0 .or. ndifferent.gt.0) stop 1
+
+contains
+
+ character(len=40) function pack77_status_text(status) result(text)
+ integer, intent(in) :: status
+
+ select case(status)
+ case(PACK77_STATUS_NOT_ENCODED)
+ text='not encoded'
+ case(PACK77_STATUS_FREE_TEXT_TOO_LONG)
+ text='free text too long'
+ case(PACK77_STATUS_FREE_TEXT_INVALID)
+ text='invalid free text'
+ case(PACK77_STATUS_PREFERRED_FAMILY_REJECTED)
+ text='preferred message family rejected'
+ case(PACK77_STATUS_INTERNAL_ROUNDTRIP_REJECTED)
+ text='internal round-trip check failed'
+ case default
+ write(text,'(a,i0)') 'unknown status ',status
+ end select
+ end function pack77_status_text
+
+end program encode77
include '../chkcall.f90'
diff --git a/lib/77bit/packjt77.f90 b/lib/77bit/packjt77.f90
index 35236b37..9fba9f92 100644
--- a/lib/77bit/packjt77.f90
+++ b/lib/77bit/packjt77.f90
@@ -1,48 +1,256 @@
module packjt77
-
+
+ use packjt77_schema
+ use packjt77_grammar
+
! These variables are accessible from outside via "use packjt77":
parameter (MAXHASH=1000,MAXRECENT=10)
- parameter (MAXHASHVAR=1000,MAXTXHASHVAR=5,MAXRECENTVAR=10)
- ! variables from original packjt77
+ ! Callsign hash resolution uses one session-persistent shared table. Encode,
+ ! decode, and configured/var decode stage calls at their boundaries, then
+ ! commit them through save_hash_call instead of maintaining separate TX/RX
+ ! hash stores.
character (len=13), dimension(0:1023) :: calls10=''
character (len=13), dimension(0:4095) :: calls12=''
character (len=13), dimension(1:MAXHASH) :: calls22=''
character (len=13), dimension(1:MAXRECENT) :: recent_calls=''
character (len=13) :: mycall13=''
character (len=13) :: dxcall13=''
- character (len=6) :: dxbase=''
integer, dimension(1:MAXHASH) :: ihash22=-1
integer :: nzhash=0
- integer n28a,n28b
- ! variables from packjt77var
- character (len=13), dimension(0:1023) :: calls10var=''
- character (len=13), dimension(0:4095) :: calls12var=''
- character (len=13), dimension(1:MAXHASHVAR) :: calls22var=''
- character (len=13), dimension(0:1023) :: txcalls10var=''
- character (len=13), dimension(0:4095) :: txcalls12var=''
- character (len=13), dimension(1:MAXTXHASHVAR) :: txcalls22var=''
- character (len=13), dimension(1:MAXRECENTVAR) :: recent_callsvar=''
- character (len=13), dimension(1:840) :: last_callsvar=''
- character (len=13) :: mycall13var=''
- character (len=13) :: dxcall13var=''
- character (len=13) :: mycall13_0var=''
- character (len=13) :: dxcall13_0var=''
- integer hashmy10var,hashmy12var,hashmy22var,hashdx10var
- logical :: dxcall13_setvar=.false.
- logical :: mycall13_setvar=.false.
- integer, dimension(1:MAXHASHVAR) :: ihash22var=-1
- integer, dimension(1:5) :: itxhash22var=-1
- integer, dimension(1:24) :: nlast_callsvar=0
- integer, dimension(1:25) :: nthrindexvar=(/0,200,300,370,420,460,500,530,560,590,610,630,650,670,690,710, &
+ ! Configured/var decodes queue per-thread facts until fillhashvar folds them
+ ! into the shared hash and recent-call state.
+ character (len=13), dimension(1:840) :: queued_calls_by_thread=''
+ character (len=13), dimension(1:840) :: queued_recent_calls_by_thread=''
+ character (len=13) :: mycall13_configured=''
+ character (len=13) :: dxcall13_configured=''
+ character (len=13) :: mycall13_configured_prev=''
+ character (len=13) :: dxcall13_configured_prev=''
+ integer hashmy10_configured,hashmy12_configured,hashmy22_configured,hashdx10_configured
+ logical :: dxcall13_configured_set=.false.
+ logical :: mycall13_configured_set=.false.
+ integer, dimension(1:24) :: nqueued_calls_by_thread=0
+ integer, dimension(1:24) :: nqueued_recent_calls_by_thread=0
+ ! Per-thread slice boundaries of queued_*_by_thread; earlier (busier)
+ ! decode threads get larger slots.
+ integer, dimension(1:25) :: thread_call_index=(/0,200,300,370,420,460,500,530,560,590,610,630,650,670,690,710, &
730,750,770,790,800,810,820,830,840/)
- integer :: nzhashvar=0
- integer :: nztxhashvar=0
- integer n28avar,n28bvar
- logical(1) lcommonft8b
-!$omp threadprivate(recent_callsvar,n28avar,n28bvar)
+ integer n28a_configured,n28b_configured
+!$omp threadprivate(n28a_configured,n28b_configured)
+! Everything is private unless exported here; imported grammar/schema
+! symbols therefore never re-export through "use packjt77".
+ private
+ public :: pack77,pack77_legacy_truncating_fallback
+ public :: pack77_options,unpack77_options
+ public :: PACK77_STATUS_NOT_ENCODED,PACK77_STATUS_ENCODED
+ public :: PACK77_STATUS_FREE_TEXT_TOO_LONG
+ public :: PACK77_STATUS_FREE_TEXT_INVALID
+ public :: PACK77_STATUS_PREFERRED_FAMILY_REJECTED
+ public :: PACK77_STATUS_INTERNAL_ROUNDTRIP_REJECTED
+ public :: unpack77,unpack77_configured,pack28,unpack28
+ public :: split77,packtext77,unpacktext77
+ public :: ihashcall,hash10,hash12,hash22,save_hash_call
+ public :: add_call_to_recent_calls,queue_hash_call_for_thread
+ public :: fold_queued_recent_calls,sync_configured_calls_for_decode_start
+ public :: MAXHASH,MAXRECENT
+ public :: calls10,calls12,calls22,recent_calls,ihash22,nzhash
+ public :: mycall13,dxcall13
+ public :: queued_calls_by_thread,queued_recent_calls_by_thread
+ public :: nqueued_calls_by_thread,nqueued_recent_calls_by_thread
+ public :: mycall13_configured,dxcall13_configured
+ public :: mycall13_configured_prev,dxcall13_configured_prev
+ public :: mycall13_configured_set,dxcall13_configured_set
+ public :: hashmy10_configured,hashmy12_configured,hashmy22_configured
+ public :: hashdx10_configured
+ public :: thread_call_index
+
+ integer, parameter :: PACK77_STATUS_NOT_ENCODED=0
+ integer, parameter :: PACK77_STATUS_ENCODED=1
+ integer, parameter :: PACK77_STATUS_FREE_TEXT_TOO_LONG=3
+ integer, parameter :: PACK77_STATUS_FREE_TEXT_INVALID=4
+ integer, parameter :: PACK77_STATUS_PREFERRED_FAMILY_REJECTED=5
+ integer, parameter :: PACK77_STATUS_INTERNAL_ROUNDTRIP_REJECTED=6
+
+ type pack77_result
+ logical :: encoded=.false.
+ integer :: status=PACK77_STATUS_NOT_ENCODED
+ integer :: i3=-1
+ integer :: n3=-1
+ character(len=77) :: c77=' '
+ end type pack77_result
+
+ type pack77_hash_facts
+ ! Calls that an accepted encode should make resolvable by later hash-only
+ ! decodes. pack77 commits these unless record_tx_hashes is disabled.
+ integer :: ncalls=0
+ character(len=13) :: calls(32)=''
+ end type pack77_hash_facts
+
+ type pack77_candidate
+ type(pack77_result) :: result
+ type(pack77_hash_facts) :: hash_facts
+ end type pack77_candidate
+
+ type pack77_encode_core_result
+ type(pack77_result) :: result
+ type(pack77_hash_facts) :: hash_facts
+ end type pack77_encode_core_result
+
+
+
+ type unpack77_effects
+ ! Decoders collect hash/recent-call side effects here and apply them only
+ ! after the message has decoded successfully.
+ integer :: nhash=0
+ integer :: nrecent=0
+ character(len=13) :: hash_calls(32)=''
+ character(len=13) :: recent_calls(32)=''
+ end type unpack77_effects
+
+ type unpack77_context
+ integer :: nrx=0
+ logical :: configured=.false.
+ logical :: strict_var_guards=.false.
+ logical :: mycall_set=.false.
+ logical :: dxcall_set=.false.
+ character(len=13) :: mycall=''
+ character(len=13) :: dxcall=''
+ integer :: hashmy10=-1
+ integer :: hashmy12=-1
+ integer :: hashmy22=-1
+ integer :: hashdx10=-1
+ end type unpack77_context
+
+ type configured_decode_state
+ logical :: mycall_set=.false.
+ logical :: dxcall_set=.false.
+ character(len=13) :: mycall=''
+ character(len=13) :: dxcall=''
+ integer :: hashmy10=-1
+ integer :: hashmy12=-1
+ integer :: hashmy22=-1
+ integer :: hashdx10=-1
+ end type configured_decode_state
+
+ type unpack77_core_result
+ logical :: success=.false.
+ integer :: i3=-1
+ integer :: n3=-1
+ character(len=37) :: msg=' '
+ type(unpack77_effects) :: effects
+ end type unpack77_core_result
+
+ type unpack77_effect_policy
+ logical :: record_hashes=.true.
+ logical :: record_recent_calls=.true.
+ logical :: queue_by_thread=.false.
+ ! Queued policies require valid 1-based thread indexes; disable recording
+ ! through record_hashes or record_recent_calls instead of sentinel indexes.
+ integer :: nthr_hash=1
+ integer :: nthr_recent=1
+ end type unpack77_effect_policy
+
+ type pack77_options
+ logical :: prefer_wspr_50bit=.false.
+ logical :: record_tx_hashes=.true.
+ logical :: expand_dx_macro=.false.
+ character(len=6) :: dx_macro_base=''
+ end type pack77_options
+
+ type unpack77_options
+ integer :: thread_index=1
+ logical :: record_hashes=.true.
+ logical :: record_recent_calls=.true.
+ end type unpack77_options
contains
-
+
+type(pack77_result) function pack77_no_match() result(encoded)
+ encoded=pack77_result()
+end function pack77_no_match
+
+type(pack77_result) function pack77_reject(status) result(encoded)
+ integer, intent(in) :: status
+
+ encoded=pack77_result()
+ encoded%status=status
+end function pack77_reject
+
+type(pack77_result) function pack77_accept(i3,n3,c77) result(encoded)
+ integer, intent(in) :: i3,n3
+ character(len=77), intent(in) :: c77
+
+ encoded=pack77_result()
+ encoded%encoded=.true.
+ encoded%status=PACK77_STATUS_ENCODED
+ encoded%i3=i3
+ encoded%n3=n3
+ encoded%c77=c77
+end function pack77_accept
+
+subroutine pack77_accept_candidate_encoded(candidate,i3,n3,c77,ok)
+ type(pack77_candidate), intent(inout) :: candidate
+ integer, intent(in) :: i3,n3
+ character(len=77), intent(in) :: c77
+ logical, intent(in) :: ok
+
+ candidate%result=pack77_no_match()
+ if(ok) candidate%result=pack77_accept(i3,n3,c77)
+end subroutine pack77_accept_candidate_encoded
+
+logical function take_candidate(candidate,msg,encoded) result(won)
+ type(pack77_candidate), intent(in) :: candidate
+ character(len=*), intent(in) :: msg
+ type(pack77_encode_core_result), intent(inout) :: encoded
+ type(unpack77_core_result) :: decoded
+ logical :: messages_match,resolved_render_fits
+
+! A candidate must round-trip through the neutral decoder before it wins; a
+! syntactically shaped but gated-out candidate only records its family so
+! fallback callers can report what kind of exact encoding was rejected.
+ won=candidate%result%encoded
+ if(won) then
+ decoded=pack77_decode_neutral(candidate%result%c77)
+ call pack77_gate_message_checks(msg,decoded%msg,candidate%hash_facts%calls, &
+ candidate%hash_facts%ncalls,messages_match,resolved_render_fits)
+ if(.not.(decoded%success .and. decoded%i3.eq.candidate%result%i3 .and. &
+ decoded%n3.eq.candidate%result%n3 .and. messages_match .and. &
+ resolved_render_fits)) then
+ won=.false.
+ encoded%result=pack77_reject(PACK77_STATUS_INTERNAL_ROUNDTRIP_REJECTED)
+ endif
+ endif
+ if(.not.won) return
+ encoded%result=candidate%result
+ encoded%hash_facts=candidate%hash_facts
+end function take_candidate
+
+type(unpack77_core_result) function pack77_decode_neutral(c77) result(decoded)
+ character(len=77), intent(in) :: c77
+ type(unpack77_context) :: context
+
+ context=unpack77_context()
+ decoded=unpack77_core(c77,context)
+end function pack77_decode_neutral
+
+integer function pack77_wspr_payload_type(c77) result(wspr_type)
+ character(len=77), intent(in) :: c77
+
+! Bit columns 49/50 are the j49/j50 subtype selector fields fixed by the
+! WSPR schemas in packjt77_schema; keep in sync with those field offsets.
+ wspr_type=0
+ if(c77(50:50).eq.'1') then
+ wspr_type=2
+ else if(c77(49:49).eq.'0') then
+ wspr_type=1
+ else if(c77(49:49).eq.'1') then
+ ! Invalid selector 110 reaches Type 3; the schema decoder rejects it.
+ wspr_type=3
+ endif
+end function pack77_wspr_payload_type
+
+
+
+
subroutine hash10(n10,c13)
character*13 c13
@@ -60,7 +268,7 @@ end subroutine hash10
subroutine hash12(n12,c13)
character*13 c13
-
+
c13='<...>'
if(n12.lt.0 .or. n12.gt.4095) return
if(len(trim(calls12(n12))).gt.0) then
@@ -75,7 +283,7 @@ end subroutine hash12
subroutine hash22(n22,c13)
character*13 c13
-
+
c13='<...>'
do i=1,nzhash
if(ihash22(i).eq.n22) then
@@ -90,27 +298,66 @@ end subroutine hash22
integer function ihashcall(c0,m)
+ implicit none
- integer*8 n8
- character*13 c0
- character*38 c
- data c/' 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ/'/
+ character(len=13), intent(in) :: c0
+ integer, intent(in) :: m
+ integer(kind=8) :: n8
+ integer :: i,j
- n8=0
+ n8=0_8
do i=1,11
- j=index(c,c0(i:i)) - 1
- n8=38*n8 + j
+ j=index(PACK77_BASE38,c0(i:i)) - 1
+ n8=38_8*n8 + j
enddo
- ihashcall=ishft(47055833459_8*n8,m-64)
+
+ ihashcall=ihashcall_from_n8(n8,m)
return
end function ihashcall
+integer function ihashcall_from_n8(n8,m)
+ implicit none
+
+ integer(kind=8), intent(in) :: n8
+ integer, intent(in) :: m
+ integer(kind=8), parameter :: hash_factor(0:3) = (/2419_8, 62655_8, 10_8, 0_8/)
+ integer(kind=8) :: b(0:3), p(0:3)
+ integer(kind=8) :: carry, term
+ integer(kind=8) :: x
+ integer :: i,j
+
+ x=n8
+ do i=0,3
+ b(i)=mod(x,65536_8)
+ x=x/65536_8
+ enddo
+
+ ! Return the top m bits of the low 64 bits of 47055833459*n8.
+ carry=0_8
+ do i=0,3
+ term=carry
+ do j=0,i
+ term=term+hash_factor(j)*b(i-j)
+ enddo
+ p(i)=mod(term,65536_8)
+ carry=term/65536_8
+ enddo
+
+ if(m.le.16) then
+ ihashcall_from_n8=int(p(3)/(2_8**(16-m)))
+ else
+ ihashcall_from_n8=int(p(3)*(2_8**(m-16)) + p(2)/(2_8**(32-m)))
+ endif
+
+ return
+end function ihashcall_from_n8
+
subroutine save_hash_call(c13,n10,n12,n22)
character*13 c13,cw
- cw=c13
+ cw=c13
if(cw(1:1).eq.' ' .or. cw(1:5).eq.'<...>') return
if(cw(1:1).eq.'<') cw=cw(2:)
i=index(cw,'>')
@@ -125,7 +372,7 @@ subroutine save_hash_call(c13,n10,n12,n22)
if(n12.ge.0 .and. n12 .le. 4095 .and. cw.ne.mycall13) calls12(n12)=cw
n22=ihashcall(cw,22)
- if(any(ihash22.eq.n22)) then ! If entry exists, make sure callsign is the most recently received one
+ if(any(ihash22.eq.n22)) then ! If entry exists, make sure callsign is the most recently received one
where(ihash22.eq.n22) calls22=cw
go to 900
endif
@@ -139,157 +386,444 @@ subroutine save_hash_call(c13,n10,n12,n22)
calls22(1)=cw
if(nzhash.lt.MAXHASH) nzhash=nzhash+1
900 continue
- return
+ return
end subroutine save_hash_call
-subroutine pack77(msg0,i3,n3,c77)
+subroutine normalize_hash_call(c13,cw,ok)
- use packjt
- character*37 msg,msg0
- character*18 c18
- character*13 w(19)
- character*77 c77
- integer nw(19)
- integer ntel(3)
+ character(len=*), intent(in) :: c13
+ character(len=13), intent(out) :: cw
+ logical, intent(out) :: ok
+ integer :: i
+
+ cw=c13
+ ok=.false.
+ if(cw(1:1).eq.' ' .or. cw(1:5).eq.'<...>') return
+ if(cw(1:1).eq.'<') then
+ if(.not.pack77_valid_hash_call_token(cw)) return
+ cw=cw(2:)
+ i=index(cw,'>')
+ if(i.gt.0) cw(i:)=' '
+ endif
+ if(len(trim(cw)) .lt. 3) return
+ ok=.true.
+
+ return
+end subroutine normalize_hash_call
+
+subroutine stage_hash_call(hash_facts,c13)
+
+ type(pack77_hash_facts), intent(inout) :: hash_facts
+ character(len=*), intent(in) :: c13
+ character(len=13) :: cw
+ logical :: ok
+
+! Do not update the global hash table while testing encode candidates. The
+! accepted candidate's facts are committed once by pack77.
+ call normalize_hash_call(c13,cw,ok)
+ if(.not.ok) return
+ if(hash_facts%ncalls.ge.size(hash_facts%calls)) return
+ hash_facts%ncalls=hash_facts%ncalls+1
+ hash_facts%calls(hash_facts%ncalls)=cw
+
+ return
+end subroutine stage_hash_call
+
+subroutine pack77_hash_index(hash_facts,token,nbits,n,ok)
+ type(pack77_hash_facts), intent(inout) :: hash_facts
+ character(len=*), intent(in) :: token
+ integer, intent(in) :: nbits
+ integer, intent(out) :: n
+ logical, intent(out) :: ok
+ character(len=13) :: hash_call
+
+ call normalize_hash_call(token,hash_call,ok)
+ if(.not.ok) return
+ n=ihashcall(hash_call,nbits)
+ call stage_hash_call(hash_facts,hash_call)
+
+ return
+end subroutine pack77_hash_index
+
+subroutine commit_hash_facts(hash_facts)
+
+ type(pack77_hash_facts), intent(in) :: hash_facts
+ integer :: i,n10,n12,n22
+
+! All hash-producing encode paths feed the same shared tables here.
+ do i=1,hash_facts%ncalls
+ call save_hash_call(hash_facts%calls(i),n10,n12,n22)
+ enddo
+
+ return
+end subroutine commit_hash_facts
+
+character(len=37) function pack77_expand_dx_macro(msg0,dx_base) result(msg)
+ character(len=*), intent(in) :: msg0,dx_base
+ character(len=37) :: msg1
+ integer :: i1
msg=msg0
- if(msg(1:3).eq.'$DX') then
- i1=index(msg,' ')
- msg=trim(dxbase)//' '//msg(i1+1:)
+ msg1=adjustl(msg0)
+ if(.not.pack77_first_word_is_dx_macro(msg1)) return
+ if(len_trim(dx_base).eq.0) return
+
+ i1=index(msg1,' ')
+ if(i1.gt.0) then
+ msg=trim(dx_base)//' '//adjustl(msg1(i1+1:))
+ else
+ msg=trim(dx_base)
endif
+end function pack77_expand_dx_macro
- i3_hint=i3
- n3_hint=n3
- i3=-1
- n3=-1
- if(i3_hint.eq.0 .and. n3_hint.eq.5) go to 5
+logical function pack77_first_word_is_dx_macro(msg0) result(is_macro)
+ character(len=*), intent(in) :: msg0
+ character(len=37) :: first_word,msg1
+ integer :: i,i1
+
+ msg1=adjustl(msg0)
+ if(len_trim(msg1).eq.0) then
+ is_macro=.false.
+ return
+ endif
+
+ i1=index(msg1,' ')
+ if(i1.gt.1) then
+ first_word=msg1(1:i1-1)
+ else
+ first_word=trim(msg1)
+ endif
+
+ do i=1,len_trim(first_word)
+ if(first_word(i:i).ge.'a' .and. first_word(i:i).le.'z') &
+ first_word(i:i)=char(ichar(first_word(i:i))-32)
+ enddo
+
+ is_macro=first_word.eq.'$DX' .or. first_word.eq.'$DXCALL'
+end function pack77_first_word_is_dx_macro
+
+logical function pack77_failed_preferred_wspr_shape(msg0,options) result(reject)
+
+ character(len=*), intent(in) :: msg0
+ type(pack77_options), intent(in), optional :: options
+ character(len=13) :: source_tokens(2)
+ integer :: nwords
+ logical :: split_ok
+
+! FST4W callers use this option to request a WSPR/50-bit payload, not merely
+! to try WSPR first. If the source has WSPR shape but is not valid WSPR, reject
+! instead of falling through to another pack77 family or free text.
+ reject=.false.
+ if(.not.present(options)) return
+ if(.not.options%prefer_wspr_50bit) return
+
+ call pack77_split_source_tokens(msg0,2,nwords,source_tokens,split_ok)
+ reject=split_ok .and. nwords.eq.2 .and. &
+ len_trim(source_tokens(1)).ge.5 .and. &
+ len_trim(source_tokens(1)).le.12 .and. &
+ len_trim(source_tokens(2)).le.6
+end function pack77_failed_preferred_wspr_shape
+
+type(pack77_encode_core_result) function pack77_encode_core(msg0,options) &
+ result(encoded)
+
+ character*37 msg,msg0
+ character(len=13) :: source_tokens(19)
+ type(pack77_options), intent(in), optional :: options
+ type(pack77_candidate) :: candidate
+ character(len=6) :: dx_macro_base
+ integer :: nwords
+ logical prefer_wspr_50bit
+ logical expand_dx_macro
+ logical split_ok
+ logical word_overflow
+ logical starts_with_special_token
+
+ encoded%result=pack77_no_match()
+ prefer_wspr_50bit=.false.
+ expand_dx_macro=.false.
+ dx_macro_base=''
+ if(present(options)) then
+ prefer_wspr_50bit=options%prefer_wspr_50bit
+ expand_dx_macro=options%expand_dx_macro
+ dx_macro_base=options%dx_macro_base
+ endif
+ msg=msg0
+ if(expand_dx_macro) msg=pack77_expand_dx_macro(msg,dx_macro_base)
! Convert msg to upper case; collapse multiple blanks; parse into words.
- call split77(msg,nwords,nw,w)
- if(msg(1:3).eq.'CQ ' .or. msg(1:3).eq.'DE ' .or. msg(1:4).eq.'QRZ ') go to 100
+ call pack77_split_source_tokens(msg,19,nwords,source_tokens,split_ok)
+ word_overflow=.not.split_ok
+ starts_with_special_token=msg(1:3).eq.'CQ ' .or. msg(1:3).eq.'DE ' .or. &
+ msg(1:4).eq.'QRZ '
+ if(word_overflow) then
+ if(.not.starts_with_special_token) then
+ encoded%result=pack77_05(msg)
+ if(encoded%result%encoded) return
+ endif
+ encoded%result=pack77_free_text_exact(msg)
+ return
+ endif
+ if(.not.starts_with_special_token) then
! Check 0.1 (DXpedition mode)
- call pack77_01(nwords,w,i3,n3,c77)
- if(i3.ge.0 .or. n3.ge.1) go to 900
+ candidate=pack77_01_candidate(msg)
+ if(take_candidate(candidate,msg,encoded)) return
! Check 0.2 (EU VHF contest exchange)
! call pack77_02(nwords,w,i3,n3,c77)
! if(i3.ge.0) go to 900
! Check 0.3 and 0.4 (ARRL Field Day exchange)
- call pack77_03(nwords,w,i3,n3,c77)
- if(i3.ge.0) go to 900
- if(nwords.ge.2) go to 100
+ candidate=pack77_03_candidate(msg)
+ if(take_candidate(candidate,msg,encoded)) return
+ if(nwords.lt.2) then
- ! Check 0.5 (telemetry)
-5 i0=index(msg,' ')
- c18=msg(1:i0-1)
- c18=adjustr(c18)
- ntel=-99
- read(c18,1005,err=6) ntel
-1005 format(3z6)
- if(ntel(1).ge.2**23) go to 800
-6 if(ntel(1).ge.0 .and. ntel(2).ge.0 .and. ntel(3).ge.0) then
- i3=0
- n3=5
- write(c77,1006) ntel,n3,i3
-1006 format(b23.23,2b24.24,2b3.3)
- go to 900
+! Check 0.5 (telemetry)
+ encoded%result=pack77_05(msg)
+ if(encoded%result%encoded) return
+ endif
endif
-100 call pack77_06(nwords,w,i3,n3,c77,i3_hint,n3_hint)
- if(i3.ge.0) go to 900
+ candidate=pack77_06_candidate(msg,prefer_wspr_50bit)
+ if(take_candidate(candidate,msg,encoded)) return
! Check Type 1 (Standard 77-bit message) or Type 2, with optional "/P"
- call pack77_1(nwords,w,i3,n3,c77)
- if(i3.ge.0) go to 900
+ candidate=pack77_1_candidate(msg)
+ if(take_candidate(candidate,msg,encoded)) return
! Check Type 3 (ARRL RTTY contest exchange)
- call pack77_3(nwords,w,i3,n3,c77)
- if(i3.ge.0) go to 900
+ candidate=pack77_3_candidate(msg)
+ if(take_candidate(candidate,msg,encoded)) return
! Check Type 4 (One nonstandard call and one hashed call)
- call pack77_4(nwords,w,i3,n3,c77)
- if(i3.ge.0) go to 900
+ candidate=pack77_4_candidate(msg)
+ if(take_candidate(candidate,msg,encoded)) return
! Check Type 5 (EU VHF Contest with 2 hashed calls, report, serial, and grid6)
- call pack77_5(nwords,w,i3,n3,c77)
- if(i3.ge.0) go to 900
+ candidate=pack77_5_candidate(msg)
+ if(take_candidate(candidate,msg,encoded)) return
+
+! It defaults to exactly representable free text.
+ encoded%result=pack77_free_text_exact(msg)
+end function pack77_encode_core
+
+type(pack77_result) function pack77_encode_result(msg0,options) result(encoded)
+
+ character*37 msg0
+ type(pack77_options), intent(in), optional :: options
+ type(pack77_encode_core_result) :: core
+ logical :: record_tx_hashes
+
+ record_tx_hashes=.true.
+ if(present(options)) record_tx_hashes=options%record_tx_hashes
+
+ core=pack77_encode_core(msg0,options)
+ encoded=core%result
+ if(.not.encoded%encoded .and. &
+ encoded%status.ne.PACK77_STATUS_INTERNAL_ROUNDTRIP_REJECTED .and. &
+ pack77_failed_preferred_wspr_shape(pack77_normalized_message(msg0), &
+ options)) encoded=pack77_reject(PACK77_STATUS_PREFERRED_FAMILY_REJECTED)
+ if(record_tx_hashes) call commit_hash_facts(core%hash_facts)
+end function pack77_encode_result
+
+subroutine pack77(msg0,i3,n3,c77,options,status)
+ character(len=*), intent(in) :: msg0
+ integer, intent(out) :: i3,n3
+ character(len=77), intent(out) :: c77
+ type(pack77_options), intent(in), optional :: options
+ integer, intent(out), optional :: status
+ type(pack77_result) :: packed
+
+ packed=pack77_encode_result(msg0,options)
+ i3=packed%i3
+ n3=packed%n3
+ c77=packed%c77
+ if(present(status)) status=packed%status
+end subroutine pack77
-! It defaults to free text
-800 i3=0
- n3=0
- msg(14:)=' '
- call packtext77(msg(1:13),c77(1:71))
- write(c77(72:77),'(2b3.3)') n3,i3
+subroutine pack77_legacy_truncating_fallback(msg0,i3,n3,c77,options,status)
+ character(len=*), intent(in) :: msg0
+ integer, intent(out) :: i3,n3
+ character(len=77), intent(out) :: c77
+ type(pack77_options), intent(in), optional :: options
+ integer, intent(out), optional :: status
+ type(pack77_result) :: packed
+
+ packed=pack77_legacy_truncating_result(msg0,options)
+ i3=packed%i3
+ n3=packed%n3
+ c77=packed%c77
+ if(present(status)) status=packed%status
+end subroutine pack77_legacy_truncating_fallback
+
+type(pack77_result) function pack77_legacy_truncating_result(msg0,options) &
+ result(encoded)
+ character(len=*), intent(in) :: msg0
+ type(pack77_options), intent(in), optional :: options
+ type(pack77_result) :: fallback
+ character(len=37) :: msg
+ character(len=13) :: payload
+
+ encoded=pack77_encode_result(msg0,options)
+ if(encoded%encoded) return
+ if(encoded%status.eq.PACK77_STATUS_PREFERRED_FAMILY_REJECTED) return
+ if(encoded%status.eq.PACK77_STATUS_INTERNAL_ROUNDTRIP_REJECTED) return
-900 return
-end subroutine pack77
+ msg=msg0
+ if(present(options)) then
+ if(options%expand_dx_macro) msg=pack77_expand_dx_macro(msg, &
+ options%dx_macro_base)
+ endif
+ msg=pack77_normalized_message(msg)
+ if(len_trim(msg).lt.1) return
+
+ payload=msg(1:13)
+ if(.not.pack77_free_text_alphabet_ok(payload)) return
+
+ fallback=pack77_free_text_accept(payload,PACK77_STATUS_ENCODED)
+ if(fallback%encoded) encoded=fallback
+end function pack77_legacy_truncating_result
+
+type(pack77_result) function pack77_05(msg) result(encoded)
+ character(len=*), intent(in) :: msg
+ character*77 c77
+ character*37 text
+ character*18 c18
+ character*1 ch
+ integer ntel(3)
+ logical ok
+
+ encoded=pack77_no_match()
+ text=adjustl(msg)
+ n=len_trim(text)
+ if(n.lt.1 .or. n.gt.18) return
+ do i=1,n
+ ch=text(i:i)
+ if(ch.ge.'a' .and. ch.le.'z') ch=char(ichar(ch)-32)
+ if(index('0123456789ABCDEF',ch).eq.0) return
+ text(i:i)=ch
+ enddo
+ c18=text(1:n)
+ c18=adjustr(c18)
+ ntel=-99
+ read(c18,1005,err=6) ntel
+1005 format(3z6)
+ 6 if(ntel(1).ge.0 .and. ntel(2).ge.0 .and. ntel(3).ge.0) then
+ call encode_pack77_telemetry(ntel(1),ntel(2),ntel(3),c77,ok)
+ if(ok) then
+ encoded=pack77_accept(0,5,c77)
+ endif
+ endif
+end function pack77_05
+
+type(pack77_result) function pack77_free_text_exact(msg) result(encoded)
+ character(len=*), intent(in) :: msg
+ character*37 msg0
+
+ msg0=pack77_normalized_message(msg)
+ if(.not.pack77_exact_free_text_ok(msg0)) then
+ encoded=pack77_reject(pack77_free_text_reject_status(msg0))
+ return
+ endif
+ encoded=pack77_free_text_accept(msg0,PACK77_STATUS_ENCODED)
+end function pack77_free_text_exact
+
+type(pack77_result) function pack77_free_text_accept(msg,status) result(encoded)
+ character(len=*), intent(in) :: msg
+ integer, intent(in) :: status
+ character*37 msg0
+ character*71 text_bits
+ character*77 c77
+ logical ok
+
+ msg0=msg
+ msg0(14:)=' '
+ call packtext77(msg0(1:13),text_bits)
+ call encode_pack77_free_text(text_bits,c77,ok)
+ encoded=pack77_no_match()
+ if(ok) then
+ encoded=pack77_accept(0,0,c77)
+ encoded%status=status
+ endif
+end function pack77_free_text_accept
+
+integer function pack77_free_text_reject_status(msg) result(status)
+ character(len=*), intent(in) :: msg
+
+ if(.not.pack77_free_text_alphabet_ok(msg)) then
+ status=PACK77_STATUS_FREE_TEXT_INVALID
+ else if(len_trim(msg).gt.13) then
+ status=PACK77_STATUS_FREE_TEXT_TOO_LONG
+ else
+ status=PACK77_STATUS_FREE_TEXT_INVALID
+ endif
+end function pack77_free_text_reject_status
+
+logical function pack77_exact_free_text_ok(msg) result(ok)
+ character(len=*), intent(in) :: msg
+
+ ok=.false.
+ if(len_trim(msg).gt.13) return
+ ok=pack77_free_text_alphabet_ok(msg(1:len_trim(msg)))
+end function pack77_exact_free_text_ok
+
+logical function pack77_free_text_alphabet_ok(msg) result(ok)
+ character(len=*), intent(in) :: msg
+ character(len=42), parameter :: alphabet=' 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ+-./?'
+ integer :: i
+
+ ok=.false.
+ do i=1,len_trim(msg)
+ if(index(alphabet,msg(i:i)).eq.0) return
+ enddo
+ ok=.true.
+end function pack77_free_text_alphabet_ok
+
+! Must mirror the character canonicalization of pack77_split_source_tokens
+! (NUL->space, uppercase fold, blank collapse) so free text and structured
+! parsing agree on the canonical form.
+character(len=37) function pack77_normalized_message(msg) result(normalized)
+ character(len=*), intent(in) :: msg
+ character(len=1) :: c,c0
+ integer :: i,j,iz
+
+ normalized=' '
+ c0=' '
+ j=0
+ iz=len_trim(msg)
+ do i=1,min(iz,len(normalized))
+ c=msg(i:i)
+ if(ichar(c).eq.0) c=' '
+ if(c.eq.' ' .and. c0.eq.' ') cycle
+ if(c.ge.'a' .and. c.le.'z') c=char(ichar(c)-32)
+ j=j+1
+ normalized(j:j)=c
+ c0=c
+ enddo
+end function pack77_normalized_message
subroutine unpack77(c77,nrx,msg,unpk77_success)
!
! nrx=1 when unpacking a received message
! nrx=0 when unpacking a to-be-transmitted message
-! the value of nrx is used to decide when mycall13 or dxcall13 should
-! be used in place of a callsign from the hashtable
!
- parameter (NSEC=86) !Number of ARRL Sections
- parameter (NUSCAN=171) !Number of States and Provinces
- parameter (MAXGRID4=32400)
- integer*8 n58
- integer ntel(3)
character*77 c77
character*37 msg
- character*13 call_1,call_2,call_3,call_1a
+ integer, intent(in) :: nrx
+ logical unpk77_success
character*13 mycall13_0,dxcall13_0
- character*11 c11
- character*3 crpt,cntx,cpfx
- character*3 cmult(NUSCAN)
- character*6 cexch,grid6
- character*4 grid4,cserial
- character*3 csec(NSEC)
- character*38 c
- character*36 a2
integer hashmy10,hashmy12,hashmy22,hashdx10,hashdx12,hashdx22
- logical unpk28_success,unpk77_success,unpkg4_success
logical dxcall13_set,mycall13_set
+ type(unpack77_context) :: context
+ type(unpack77_effect_policy) :: policy
- data a2/'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'/,nzzz/46656/
- data c/' 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ/'/
- data csec/ &
- "AB ","AK ","AL ","AR ","AZ ","BC ","CO ","CT ","DE ","EB ", &
- "EMA","ENY","EPA","EWA","GA ","GH ","IA ","ID ","IL ","IN ", &
- "KS ","KY ","LA ","LAX","NS ","MB ","MDC","ME ","MI ","MN ", &
- "MO ","MS ","MT ","NC ","ND ","NE ","NFL","NH ","NL ","NLI", &
- "NM ","NNJ","NNY","TER","NTX","NV ","OH ","OK ","ONE","ONN", &
- "ONS","OR ","ORG","PAC","PR ","QC ","RI ","SB ","SC ","SCV", &
- "SD ","SDG","SF ","SFL","SJV","SK ","SNJ","STX","SV ","TN ", &
- "UT ","VA ","VI ","VT ","WCF","WI ","WMA","WNY","WPA","WTX", &
- "WV ","WWA","WY ","DX ","PE ","NB "/
- data cmult/ &
- "AL ","AK ","AZ ","AR ","CA ","CO ","CT ","DE ","FL ","GA ", &
- "HI ","ID ","IL ","IN ","IA ","KS ","KY ","LA ","ME ","MD ", &
- "MA ","MI ","MN ","MS ","MO ","MT ","NE ","NV ","NH ","NJ ", &
- "NM ","NY ","NC ","ND ","OH ","OK ","OR ","PA ","RI ","SC ", &
- "SD ","TN ","TX ","UT ","VT ","VA ","WA ","WV ","WI ","WY ", &
- "NB ","NS ","QC ","ON ","MB ","SK ","AB ","BC ","NWT","NF ", &
- "LB ","NU ","YT ","PEI","DC ","DR ","FR ","GD ","GR ","OV ", &
- "ZH ","ZL ","X01","X02","X03","X04","X05","X06","X07","X08", &
- "X09","X10","X11","X12","X13","X14","X15","X16","X17","X18", &
- "X19","X20","X21","X22","X23","X24","X25","X26","X27","X28", &
- "X29","X30","X31","X32","X33","X34","X35","X36","X37","X38", &
- "X39","X40","X41","X42","X43","X44","X45","X46","X47","X48", &
- "X49","X50","X51","X52","X53","X54","X55","X56","X57","X58", &
- "X59","X60","X61","X62","X63","X64","X65","X66","X67","X68", &
- "X69","X70","X71","X72","X73","X74","X75","X76","X77","X78", &
- "X79","X80","X81","X82","X83","X84","X85","X86","X87","X88", &
- "X89","X90","X91","X92","X93","X94","X95","X96","X97","X98", &
- "X99"/
data dxcall13_set/.false./
data mycall13_set/.false./
data mycall13_0/''/
- data dxcall13_0/''/
+ data dxcall13_0/' '/
save hashmy10,hashmy12,hashmy22,hashdx10,hashdx12,hashdx22
+ save dxcall13_set,mycall13_set,mycall13_0,dxcall13_0
if(mycall13.ne.mycall13_0) then
if(len(trim(mycall13)).gt.2) then
@@ -308,365 +842,51 @@ subroutine unpack77(c77,nrx,msg,unpk77_success)
hashdx10=ihashcall(dxcall13,10)
hashdx12=ihashcall(dxcall13,12)
hashdx22=ihashcall(dxcall13,22)
+ else
+ dxcall13_set=.false.
endif
endif
- unpk77_success=.true.
-
-! Check for bad data
- do i=1,77
- if(c77(i:i).ne.'0' .and. c77(i:i).ne.'1') then
- msg='failed unpack'
- unpk77_success=.false.
- return
- endif
- enddo
-
- read(c77(72:77),'(2b3)') n3,i3
- msg=repeat(' ',37)
-
- if(i3.eq.0 .and. n3.eq.0) then
-! 0.0 Free text
- call unpacktext77(c77(1:71),msg(1:13))
- msg(14:)=' '
- msg=adjustl(msg)
- if(msg(1:1).eq.' ') then
- unpk77_success=.false.
- return
- endif
- else if(i3.eq.0 .and. n3.eq.1) then
-! 0.1 K1ABC RR73; W9XYZ <KH1/KH7Z> -11 28 28 10 5 71 DXpedition Mode
- read(c77,1010) n28a,n28b,n10,n5
-1010 format(2b28,b10,b5)
- irpt=2*n5 - 30
- write(crpt,1012) irpt
-1012 format(i3.2)
- if(irpt.ge.0) crpt(1:1)='+'
- call unpack28(n28a,call_1,unpk28_success)
- if(.not.unpk28_success .or. n28a.le.2) unpk77_success=.false.
- call unpack28(n28b,call_2,unpk28_success)
- if(.not.unpk28_success .or. n28b.le.2) unpk77_success=.false.
- call hash10(n10,call_3)
- if(call_3.eq.'<...>') then
- call hash10var(n10,call_3,1)
- endif
- if(nrx.eq.1 .and. &
- dxcall13_set .and. &
- len(trim(dxcall13)).ge.3 .and. &
- hashdx10.eq.n10) call_3='<'//trim(dxcall13)//'>'
- if(nrx.eq.0 .and. &
- mycall13_set .and. &
- n10.eq.hashmy10) call_3='<'//trim(mycall13)//'>'
- msg=trim(call_1)//' RR73; '//trim(call_2)//' '//trim(call_3)//' '//crpt
-
- else if(i3.eq.0 .and. n3.eq.2) then
- unpk77_success=.false.
-
- else if(i3.eq.0 .and. (n3.eq.3 .or. n3.eq.4)) then
-! 0.3 WA9XYZ KA1ABC R 16A EMA 28 28 1 4 3 7 71 ARRL Field Day
-! 0.4 WA9XYZ KA1ABC R 32A EMA 28 28 1 4 3 7 71 ARRL Field Day
- read(c77,1030) n28a,n28b,ir,intx,nclass,isec
-1030 format(2b28,b1,b4,b3,b7)
- if(isec.gt.NSEC .or. isec.lt.1) then
- unpk77_success=.false.
- isec=1
- endif
- call unpack28(n28a,call_1,unpk28_success)
- if(.not.unpk28_success .or. n28a.le.2) unpk77_success=.false.
- call unpack28(n28b,call_2,unpk28_success)
- if(.not.unpk28_success .or. n28b.le.2) unpk77_success=.false.
- ntx=intx+1
- if(n3.eq.4) ntx=ntx+16
- write(cntx(1:2),1032) ntx
-1032 format(i2)
- cntx(3:3)=char(ichar('A')+nclass)
- if(ir.eq.0 .and. ntx.lt.10) msg=trim(call_1)//' '//trim(call_2)// &
- cntx//' '//csec(isec)
- if(ir.eq.1 .and. ntx.lt.10) msg=trim(call_1)//' '//trim(call_2)// &
- ' R'//cntx//' '//csec(isec)
- if(ir.eq.0 .and. ntx.ge.10) msg=trim(call_1)//' '//trim(call_2)// &
- ' '//cntx//' '//csec(isec)
- if(ir.eq.1 .and. ntx.ge.10) msg=trim(call_1)//' '//trim(call_2)// &
- ' R '//cntx//' '//csec(isec)
-
- else if(i3.eq.0 .and. n3.eq.5) then
-! 0.5 0123456789abcdef01 71 71 Telemetry (18 hex)
- read(c77,1006) ntel
-1006 format(b23,2b24)
- write(msg,1007) ntel
-1007 format(3z6.6)
- do i=1,18
- if(msg(i:i).ne.'0') exit
- msg(i:i)=' '
- enddo
- msg=adjustl(msg)
-
- else if(i3.eq.0 .and. n3.eq.6) then
- read(c77(48:50),'(3b1)') j48,j49,j50
-! bits 48:50
-! itype=1: x00
-! itype=2: xx1
-! itype=3: 010
- if(j50.eq.1) then
- itype=2
- else if(j49.eq.0) then
- itype=1
- else if(j48.eq.0) then
- itype=3
- else
- itype=-1
- unpk77_success=.false.
- endif
-
- if(itype.eq.1) then
-! WSPR Type 1
- read(c77,2010) n28,igrid4,idbm
-2010 format(b28.28,b15.15,b5.5)
- idbm=nint(idbm*10.0/3.0)
- if(idbm.lt.0 .or. idbm.gt.60) unpk77_success=.false.
- call unpack28(n28,call_1,unpk28_success)
- if(.not.unpk28_success) unpk77_success=.false.
- call to_grid4(igrid4,grid4,unpkg4_success)
- if(.not.unpkg4_success) unpk77_success=.false.
- write(crpt,'(i3)') idbm
- msg=trim(call_1)//' '//grid4//' '//trim(adjustl(crpt))
- if (unpk77_success) call save_hash_call(call_1,n10,n12,n22) !### Is this OK here? ###
-
- else if(itype.eq.2) then
-! WSPR Type 2
- read(c77,2020) n28,npfx,idbm
-2020 format(b28.28,b16.16,b5.5)
- idbm=nint(idbm*10.0/3.0)
- if(idbm.lt.0 .or. idbm.gt.60) unpk77_success=.false.
- call unpack28(n28,call_1,unpk28_success)
- if(.not.unpk28_success) unpk77_success=.false.
- write(crpt,'(i3)') idbm
- cpfx=' '
- if(npfx.lt.nzzz) then
-! Prefix
- do i=3,1,-1
- j=mod(npfx,36)+1
- cpfx(i:i)=a2(j:j)
- npfx=npfx/36
- if(npfx.eq.0) exit
- enddo
- msg=trim(adjustl(cpfx))//'/'//trim(call_1)//' '//trim(adjustl(crpt))
- call_1a=trim(adjustl(cpfx))//'/'//trim(call_1)
- call save_hash_call(call_1a,n10,n12,n22) !### Is this OK here? ###
- else
-! Suffix
- npfx=npfx-nzzz
- if(npfx.le.35) then
- cpfx(1:1)=a2(npfx+1:npfx+1)
- else if(npfx.gt.35 .and. npfx.le.1295) then
- cpfx(1:1)=a2(npfx/36+1:npfx/36+1)
- cpfx(2:2)=a2(mod(npfx,36)+1:mod(npfx,36)+1)
- else if(npfx.gt.1295 .and. npfx.le.12959) then
- cpfx(1:1)=a2(npfx/360+1:npfx/360+1)
- cpfx(2:2)=a2(mod(npfx/10,36)+1:mod(npfx/10,36)+1)
- cpfx(3:3)=a2(mod(npfx,10)+1:mod(npfx,10)+1)
- else
- unpk77_success=.false.
- return
- endif
- msg=trim(call_1)//'/'//trim(adjustl(cpfx))//' '//trim(adjustl(crpt))
- call_1a=trim(call_1)//'/'//trim(adjustl(cpfx))
- call save_hash_call(call_1a,n10,n12,n22) !### Is this OK here? ###
- endif
-
- else if(itype.eq.3) then
-! WSPR Type 3
- read(c77,2030) n22,igrid6
-2030 format(b22.22,b25.25)
- n28=n22+2063592
- call unpack28(n28,call_1,unpk28_success)
- if(.not.unpk28_success) unpk77_success=.false.
- call to_grid(igrid6,grid6,unpkg4_success)
- if(.not.unpkg4_success) unpk77_success=.false.
- msg=trim(call_1)//' '//grid6
- endif
-
- else if(i3.eq.0 .and. n3.gt.6) then
- unpk77_success=.false.
-
- else if(i3.eq.1 .or. i3.eq.2) then
-! Type 1 (standard message) or Type 2 ("/P" form for EU VHF contest)
- read(c77,1000) n28a,ipa,n28b,ipb,ir,igrid4,i3
-1000 format(2(b28,b1),b1,b15,b3)
- call unpack28(n28a,call_1,unpk28_success)
- if(nrx.eq.1 .and. mycall13_set .and. hashmy22.eq.(n28a-2063592)) then
- call_1='<'//trim(mycall13)//'>'
- unpk28_success=.true.
- endif
- if(.not.unpk28_success) unpk77_success=.false.
- call unpack28(n28b,call_2,unpk28_success)
- if(.not.unpk28_success) unpk77_success=.false.
- if(call_1(1:3).eq.'CQ_') call_1(3:3)=' '
- if(index(call_1,'<').le.0) then
- i=index(call_1,' ')
- if(i.ge.4 .and. ipa.eq.1 .and. i3.eq.1) call_1(i:i+1)='/R'
- if(i.ge.4 .and. ipa.eq.1 .and. i3.eq.2) call_1(i:i+1)='/P'
- if(i.ge.4) call add_call_to_recent_calls(call_1)
- endif
- if(index(call_2,'<').le.0) then
- i=index(call_2,' ')
- if(i.ge.4 .and. ipb.eq.1 .and. i3.eq.1) call_2(i:i+1)='/R'
- if(i.ge.4 .and. ipb.eq.1 .and. i3.eq.2) call_2(i:i+1)='/P'
- if(i.ge.4) then
- call add_call_to_recent_calls(call_2)
-! only hash the "from" call
- call save_hash_call(call_2,ndum10,ndum12,ndum22)
- endif
- endif
- if(igrid4.le.MAXGRID4) then
- call to_grid4(igrid4,grid4,unpkg4_success)
- if(.not.unpkg4_success) unpk77_success=.false.
- if(ir.eq.0) msg=trim(call_1)//' '//trim(call_2)//' '//grid4
- if(ir.eq.1) msg=trim(call_1)//' '//trim(call_2)//' R '//grid4
- if(msg(1:3).eq.'CQ ' .and. ir.eq.1) unpk77_success=.false.
- else
- irpt=igrid4-MAXGRID4
- if(irpt.eq.1) msg=trim(call_1)//' '//trim(call_2)
- if(irpt.eq.2) msg=trim(call_1)//' '//trim(call_2)//' RRR'
- if(irpt.eq.3) msg=trim(call_1)//' '//trim(call_2)//' RR73'
- if(irpt.eq.4) msg=trim(call_1)//' '//trim(call_2)//' 73'
- if(irpt.ge.5) then
- isnr=irpt-35
- if(isnr.gt.50) isnr=isnr-101
- write(crpt,'(i3.2)') isnr
- if(crpt(1:1).eq.' ') crpt(1:1)='+'
- if(ir.eq.0) msg=trim(call_1)//' '//trim(call_2)//' '//crpt
- if(ir.eq.1) msg=trim(call_1)//' '//trim(call_2)//' R'//crpt
- endif
- if(msg(1:3).eq.'CQ ' .and. irpt.ge.2) unpk77_success=.false.
- endif
+ context%nrx=nrx
+ context%configured=.false.
+ context%strict_var_guards=.false.
+ context%mycall_set=mycall13_set
+ context%dxcall_set=dxcall13_set
+ context%mycall=mycall13
+ context%dxcall=dxcall13
+ context%hashmy10=hashmy10
+ context%hashmy12=hashmy12
+ context%hashmy22=hashmy22
+ context%hashdx10=hashdx10
+
+ policy=unpack77_effect_policy()
+ call run_unpack77(c77,context,policy,msg,unpk77_success)
- else if(i3.eq.3) then
-! Type 3: ARRL RTTY Contest
- read(c77,1040) itu,n28a,n28b,ir,irpt,nexch,i3
-1040 format(b1,2b28.28,b1,b3.3,b13.13,b3.3)
- write(crpt,1042) irpt+2
-1042 format('5',i1,'9')
- nserial=nexch
- imult=-1
- if(nexch.gt.8000) then
- imult=nexch-8000
- nserial=-1
- endif
- call unpack28(n28a,call_1,unpk28_success)
- if(.not.unpk28_success) unpk77_success=.false.
- call unpack28(n28b,call_2,unpk28_success)
- if(.not.unpk28_success) unpk77_success=.false.
- imult=0
- nserial=0
- if(nexch.gt.8000) imult=nexch-8000
- if(nexch.lt.8000) nserial=nexch
-
- if(imult.ge.1 .and.imult.le.NUSCAN) then
- if(itu.eq.0 .and. ir.eq.0) msg=trim(call_1)//' '//trim(call_2)// &
- ' '//crpt//' '//cmult(imult)
- if(itu.eq.1 .and. ir.eq.0) msg='TU; '//trim(call_1)//' '//trim(call_2)// &
- ' '//crpt//' '//cmult(imult)
- if(itu.eq.0 .and. ir.eq.1) msg=trim(call_1)//' '//trim(call_2)// &
- ' R '//crpt//' '//cmult(imult)
- if(itu.eq.1 .and. ir.eq.1) msg='TU; '//trim(call_1)//' '//trim(call_2)// &
- ' R '//crpt//' '//cmult(imult)
- else if(nserial.ge.1 .and. nserial.le.7999) then
- write(cserial,'(i4.4)') nserial
- if(itu.eq.0 .and. ir.eq.0) msg=trim(call_1)//' '//trim(call_2)// &
- ' '//crpt//' '//cserial
- if(itu.eq.1 .and. ir.eq.0) msg='TU; '//trim(call_1)//' '//trim(call_2)// &
- ' '//crpt//' '//cserial
- if(itu.eq.0 .and. ir.eq.1) msg=trim(call_1)//' '//trim(call_2)// &
- ' R '//crpt//' '//cserial
- if(itu.eq.1 .and. ir.eq.1) msg='TU; '//trim(call_1)//' '//trim(call_2)// &
- ' R '//crpt//' '//cserial
- endif
- else if(i3.eq.4) then
-! Type 4
- read(c77,1050) n12,n58,iflip,nrpt,icq
-1050 format(b12,b58,b1,b2,b1)
- do i=11,1,-1
- j=mod(n58,38)+1
- c11(i:i)=c(j:j)
- n58=n58/38
- enddo
- call hash12(n12,call_3)
- if(call_3.eq.'<...>') then
- call hash12var(n12,call_3,1)
- endif
- if(iflip.eq.0) then ! 12 bit hash for TO call
- call_1=call_3
- call_2=adjustl(c11)//' '
- call add_call_to_recent_calls(call_2)
- call save_hash_call(call_2,ndum10,ndum12,ndum22)
- if(nrx.eq.1 .and. &
- dxcall13_set .and. mycall13_set .and. &
- call_2.eq.dxcall13 .and. &
- n12.eq.hashmy12 ) call_1='<'//trim(mycall13)//'>'
- if(nrx.eq.1 .and. &
- mycall13_set .and. &
- index(call_1,'<...>').gt.0 .and. &
- n12.eq.hashmy12 ) call_1='<'//trim(mycall13)//'>'
- else ! 12 bit hash for DE call
- call_1=adjustl(c11)
- call_2=call_3
- call add_call_to_recent_calls(call_1)
- if(nrx.eq.0 .and. &
- mycall13_set .and. &
- n12.eq.hashmy12) call_2='<'//trim(mycall13)//'>'
- endif
- if(icq.eq.0) then
- if(nrpt.eq.0) msg=trim(call_1)//' '//trim(call_2)
- if(nrpt.eq.1) msg=trim(call_1)//' '//trim(call_2)//' RRR'
- if(nrpt.eq.2) msg=trim(call_1)//' '//trim(call_2)//' RR73'
- if(nrpt.eq.3) msg=trim(call_1)//' '//trim(call_2)//' 73'
- else
- msg='CQ '//trim(call_2)
- endif
+ return
+end subroutine unpack77
- else if(i3.eq.5) then
-
-! Type 5 <PA3XYZ> <G4ABC/P> R 590003 IO91NP h12 h22 r1 s3 S11 g25
-! EU VHF contest
- read(c77,1060) n12,n22,ir,irpt,iserial,igrid6
-1060 format(b12,b22,b1,b3,b11,b25)
- if(igrid6.lt.0 .or. igrid6.gt.18662399) then
- unpk77_success=.false.
- return
- endif
- call hash12(n12,call_1)
- if(call_1.eq.'<...>') then
- call hash12var(n12,call_1,1)
- endif
- if(n12.eq.hashmy12) call_1='<'//trim(mycall13)//'>'
- call hash22(n22,call_2)
- if(call_2.eq.'<...>') then
- call hash22var(n22,call_2,1)
- endif
- nrs=52+irpt
- write(cexch,1022) nrs,iserial
-1022 format(i2,i4.4)
- call to_grid6(igrid6,grid6,unpk77_success)
- if(ir.eq.0) msg=trim(call_1)//' '//trim(call_2)//' '//cexch//' '//grid6
- if(ir.eq.1) msg=trim(call_1)//' '//trim(call_2)//' R '//cexch//' '//grid6
+subroutine pack28(c13,n28)
+! Callers must pass a well-formed callsign or special/hash token. Malformed
+! tokens are encoded as 22-bit hashes, never coerced to standard calls, per the
+! c28 shape predicate in packjt77_grammar.
+ character*13 c13
+ integer, intent(out) :: n28
+ type(pack77_hash_facts) :: hash_facts
- else if(i3.ge.6) then ! i3 values 6 and 7 are not yet defined
- unpk77_success=.false.
- endif
- if(msg(1:4).eq.'CQ <') unpk77_success=.false.
+ call pack28_core(c13,n28,hash_facts)
+ call commit_hash_facts(hash_facts)
return
-end subroutine unpack77
+end subroutine pack28
-subroutine pack28(c13,n28)
+subroutine pack28_core(c13,n28,hash_facts)
! Pack a special token, a 22-bit hash code, or a valid base call into a 28-bit
! integer.
- parameter (NTOKENS=2063592,MAX22=4194304)
- logical is_digit,is_letter
character*13 c13
+ integer, intent(out) :: n28
+ type(pack77_hash_facts), intent(inout) :: hash_facts
character*6 callsign
character*1 c
character*4 c4
@@ -678,9 +898,6 @@ subroutine pack28(c13,n28)
data a2/'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'/
data a3/'0123456789'/
data a4/' ABCDEFGHIJKLMNOPQRSTUVWXYZ'/
-
- is_digit(c)=c.ge.'0' .and. c.le.'9'
- is_letter(c)=c.ge.'A' .and. c.le.'Z'
n28=-1
! Work-around for Swaziland prefix:
@@ -694,7 +911,7 @@ subroutine pack28(c13,n28)
n28=0
go to 900
endif
-
+
if(c13(1:4).eq.'QRZ ') then
n28=1
go to 900
@@ -707,74 +924,60 @@ subroutine pack28(c13,n28)
if(c13(1:3).eq.'CQ_') then
n=len(trim(c13))
- if(n.ge.4 .and. n.le.7) then
- nlet=0
- nnum=0
- do i=4,n
- c=c13(i:i)
- if(c.ge.'A' .and. c.le.'Z') nlet=nlet+1
- if(c.ge.'0' .and. c.le.'9') nnum=nnum+1
- enddo
- if(nnum.eq.3 .and. nlet.eq.0) then
- read(c13(4:3+nnum),*) nqsy
+! The modifier grammar (1-4 letters or exactly 3 digits) is owned by
+! pack77_valid_cq_modifier; only the number-space arithmetic lives here.
+ if(n.ge.4 .and. pack77_valid_cq_modifier(c13(4:n))) then
+ if(pack77_all_digits(c13(4:n))) then
+ nqsy=100*(iachar(c13(4:4))-iachar('0')) + &
+ 10*(iachar(c13(5:5))-iachar('0')) + &
+ iachar(c13(6:6))-iachar('0')
n28=3+nqsy
go to 900
endif
- if(nlet.ge.1 .and. nlet.le.4 .and. nnum.eq.0) then
- c4=c13(4:n)
- c4=adjustr(c4)
- m=0
- do i=1,4
- j=0
- c=c4(i:i)
- if(c.ge.'A' .and. c.le.'Z') j=ichar(c)-ichar('A')+1
- m=27*m + j
- enddo
- n28=3+1000+m
- go to 900
- endif
+ c4=c13(4:n)
+ c4=adjustr(c4)
+ m=0
+ do i=1,4
+ j=0
+ c=c4(i:i)
+ if(c.ge.'A' .and. c.le.'Z') j=ichar(c)-ichar('A')+1
+ m=27*m + j
+ enddo
+ n28=3+1000+m
+ go to 900
endif
endif
! Check for <...> callsign
if(c13(1:1).eq.'<')then
- call save_hash_call(c13,n10,n12,n22) !Save callsign in hash table
+ if(.not.pack77_valid_hash_call_token(c13)) then
+ n28=PACK77_NTOKENS
+ go to 900
+ endif
+ call stage_hash_call(hash_facts,c13)
i2=index(c13,'>')
c13=c13(2:i2-1)
n22=ihashcall(c13,22)
- n28=NTOKENS + n22
+ n28=PACK77_NTOKENS + n22
go to 900
endif
! Check for standard callsign
- iarea=-1
- n=len(trim(c13))
- do i=n,2,-1
- if(is_digit(c13(i:i))) exit
- enddo
- iarea=i !Call-area digit
- npdig=0 !Digits before call area
- nplet=0 !Letters before call area
- do i=1,iarea-1
- if(is_digit(c13(i:i))) npdig=npdig+1
- if(is_letter(c13(i:i))) nplet=nplet+1
- enddo
- nslet=0
- do i=iarea+1,n
- if(is_letter(c13(i:i))) nslet=nslet+1
- enddo
- if(iarea.lt.2 .or. iarea.gt.3 .or. nplet.eq.0 .or. &
- npdig.ge.iarea-1 .or. nslet.gt.3) then
+ if(.not.pack77_c28_standard_shape(c13)) then
! Treat this as a nonstandard callsign: compute its 22-bit hash
- call save_hash_call(c13,n10,n12,n22) !Save callsign in hash table
+ call stage_hash_call(hash_facts,c13)
n22=ihashcall(c13,22)
- n28=NTOKENS + n22
+ n28=PACK77_NTOKENS + n22
go to 900
endif
-
+
n=len(trim(c13))
+ do i=n,2,-1
+ if(pack77_is_digit_char(c13(i:i))) exit
+ enddo
+ iarea=i
! This is a standard callsign
- call save_hash_call(c13,n10,n12,n22) !Save callsign in hash table
+ call stage_hash_call(hash_facts,c13)
if(iarea.eq.2) callsign=' '//c13(1:5)
if(iarea.eq.3) callsign=c13(1:6)
i1=index(a1,callsign(1:1))-1
@@ -783,19 +986,33 @@ subroutine pack28(c13,n28)
i4=index(a4,callsign(4:4))-1
i5=index(a4,callsign(5:5))-1
i6=index(a4,callsign(6:6))-1
+ if(i1.lt.0 .or. i2.lt.0 .or. i3.lt.0 .or. i4.lt.0 .or. &
+ i5.lt.0 .or. i6.lt.0) then
+ n22=ihashcall(c13,22)
+ n28=PACK77_NTOKENS + n22
+ go to 900
+ endif
n28=36*10*27*27*27*i1 + 10*27*27*27*i2 + 27*27*27*i3 + 27*27*i4 + &
27*i5 + i6
- n28=n28 + NTOKENS + MAX22
+ n28=n28 + PACK77_NTOKENS + PACK77_MAX22
900 n28=iand(n28,ishft(1,28)-1)
return
-end subroutine pack28
-
+end subroutine pack28_core
subroutine unpack28(n28_0,c13,success)
+ integer, intent(in) :: n28_0
+ character*13 c13
+ logical success
+
+ call unpack28_core(n28_0,c13,success,.false.)
- parameter (NTOKENS=2063592,MAX22=4194304)
+ return
+end subroutine unpack28
+
+subroutine unpack28_core(n28_0,c13,success,reject_two_digit_prefix)
logical success,callok
+ logical, intent(in) :: reject_two_digit_prefix
character*13 c13
character*37 c1
character*36 c2
@@ -808,7 +1025,7 @@ subroutine unpack28(n28_0,c13,success)
success=.true.
n28=n28_0
- if(n28.lt.NTOKENS) then
+ if(n28.lt.PACK77_NTOKENS) then
! Special tokens DE, QRZ, CQ, CQ_nnn, CQ_aaaa
if(n28.eq.0) c13='DE '
if(n28.eq.1) c13='QRZ '
@@ -834,19 +1051,16 @@ subroutine unpack28(n28_0,c13,success)
go to 900
endif
endif
- n28=n28-NTOKENS
- if(n28.lt.MAX22) then
+ n28=n28-PACK77_NTOKENS
+ if(n28.lt.PACK77_MAX22) then
! This is a 22-bit hash of a callsign
n22=n28
call hash22(n22,c13) !Retrieve callsign from hash table
- if(c13.eq.'<...>') then
- call hash22var(n22,c13,1)
- endif
go to 900
endif
-
+
! Standard callsign
- n=n28 - MAX22
+ n=n28 - PACK77_MAX22
i1=n/(36*10*27*27*27)
n=n-36*10*27*27*27*i1
i2=n/(10*27*27*27)
@@ -862,18 +1076,24 @@ subroutine unpack28(n28_0,c13,success)
c13=adjustl(c13)
if(.not.callok(trim(c13))) then
+ ! Keep the legacy placeholder text for callers that still inspect c13
+ ! when success is false.
c13='QU1RK'
success=.false.
endif
900 i0=index(c13,' ')
- if(i0.ne.0 .and. i0.lt.len(trim(c13))) then
+ if((i0.ne.0 .and. i0.lt.len(trim(c13))) .or. &
+ (reject_two_digit_prefix .and. pack77_is_digit_char(c13(1:1)) .and. &
+ pack77_is_digit_char(c13(2:2)))) then
+ ! Keep the legacy placeholder text for callers that still inspect c13
+ ! when success is false.
c13='QU1RK'
success=.false.
endif
return
-end subroutine unpack28
+end subroutine unpack28_core
subroutine split77(msg,nwords,nw,w)
@@ -885,13 +1105,14 @@ subroutine split77(msg,nwords,nw,w)
character*6 bcall_1
logical ok1
integer nw(19)
-
+
iz=len(trim(msg))
j=0
k=0
n=0
c0=' '
w=' '
+ nw=0
do i=1,iz
if(ichar(msg(i:i)).eq.0) msg(i:i)=' '
c=msg(i:i) !Single character
@@ -904,584 +1125,33 @@ subroutine split77(msg,nwords,nw,w)
n=n+1 !Index in word
if(c.ge.'a' .and. c.le.'z') c=char(ichar(c)-32) !Force upper case
msg(j:j)=c
- if(n.le.13) w(k)(n:n)=c !Copy character c into word
+ if(k.le.19) then
+ nw(k)=n
+ if(n.le.13) w(k)(n:n)=c !Copy character c into word
+ endif
c0=c
enddo
iz=j !Message length
nwords=k !Number of words in msg
if(nwords.le.0) go to 900
- do i=1,nwords
- nw(i)=len(trim(w(i)))
+ do i=1,min(nwords,19)
+ if(nw(i).le.13) nw(i)=len(trim(w(i)))
enddo
msg(iz+1:)=' '
if(nwords.lt.3) go to 900
call chkcall(w(3),bcall_1,ok1)
- if(ok1 .and. w(1)(1:3).eq.'CQ ') then
+ if(ok1 .and. w(1)(1:3).eq.'CQ ' .and. &
+ pack77_valid_cq_modifier(w(2))) then
w(1)='CQ_'//w(2)(1:10) !Make "CQ " into "CQ_"
w(2:12)=w(3:13) !Move all remaining words down by one
nwords=nwords-1
- endif
-
-900 return
-end subroutine split77
-
-
-subroutine pack77_01(nwords,w,i3,n3,c77)
-
-! Pack a Type 0.1 message: DXpedition mode
-! Example message: "K1ABC RR73; W9XYZ <KH1/KH7Z> -11" 28 28 10 5
-
- character*13 w(19),c13
- character*77 c77
- character*6 bcall_1,bcall_2
- logical ok1,ok2
-
- if(nwords.ne.5) go to 900 !Must have 5 words
- if(trim(w(2)).ne.'RR73;') go to 900 !2nd word must be "RR73;"
- if(w(4)(1:1).ne.'<') go to 900 !4th word must have <...>
- if(index(w(4),'>').lt.1) go to 900
- n=-99
- read(w(5),*,err=1) n
-1 if(n.eq.-99) go to 900 !5th word must be a valid report
- n5=(n+30)/2
- if(n5.lt.0) n5=0
- if(n5.gt.31) n5=31
- call chkcall(w(1),bcall_1,ok1)
- if(.not.ok1) go to 900 !1st word must be a valid basecall
- call chkcall(w(3),bcall_2,ok2)
- if(.not.ok2) go to 900 !3rd word must be a valid basecall
-
-! Type 0.1: K1ABC RR73; W9XYZ <KH1/KH7Z> -11 28 28 10 5 71
- i3=0
- n3=1
- call pack28(w(1),n28a)
- call pack28(w(3),n28b)
- call save_hash_call(w(4),n10,n12,n22)
- i2=index(w(4),'>')
- c13=w(4)(2:i2-1)
- n10=ihashcall(c13,10)
- write(c77,1010) n28a,n28b,n10,n5,n3,i3
-1010 format(2b28.28,b10.10,b5.5,2b3.3)
-
-900 return
-end subroutine pack77_01
-
-
-subroutine pack77_03(nwords,w,i3,n3,c77)
-
-! Check 0.3 and 0.4 (ARRL Field Day exchange)
-! Example message: WA9XYZ KA1ABC R 16A EMA 28 28 1 4 3 7 71
-
- parameter (NSEC=86) !Number of ARRL Sections
- character*13 w(19)
- character*77 c77
- character*6 bcall_1,bcall_2
- character*3 csec(NSEC)
- logical ok1,ok2
- data csec/ &
- "AB ","AK ","AL ","AR ","AZ ","BC ","CO ","CT ","DE ","EB ", &
- "EMA","ENY","EPA","EWA","GA ","GH ","IA ","ID ","IL ","IN ", &
- "KS ","KY ","LA ","LAX","NS ","MB ","MDC","ME ","MI ","MN ", &
- "MO ","MS ","MT ","NC ","ND ","NE ","NFL","NH ","NL ","NLI", &
- "NM ","NNJ","NNY","TER","NTX","NV ","OH ","OK ","ONE","ONN", &
- "ONS","OR ","ORG","PAC","PR ","QC ","RI ","SB ","SC ","SCV", &
- "SD ","SDG","SF ","SFL","SJV","SK ","SNJ","STX","SV ","TN ", &
- "UT ","VA ","VI ","VT ","WCF","WI ","WMA","WNY","WPA","WTX", &
- "WV ","WWA","WY ","DX ","PE ","NB "/
-
- if(nwords.lt.4 .or. nwords.gt.5) return
- call chkcall(w(1),bcall_1,ok1)
- call chkcall(w(2),bcall_2,ok2)
- if(.not.ok1 .or. .not.ok2) return
- isec=-1
- do i=1,NSEC
- if(csec(i).eq.w(nwords)(1:3)) then
- isec=i
- exit
- endif
- enddo
- if(isec.eq.-1) return
- if(nwords.eq.5 .and. trim(w(3)).ne.'R') return
-
- ntx=-1
- j=len(trim(w(nwords-1)))-1
- read(w(nwords-1)(1:j),*,err=1,end=1) ntx !Number of transmitters
-1 if(ntx.lt.1 .or. ntx.gt.32) return
- nclass=ichar(w(nwords-1)(j+1:j+1))-ichar('A')
-
- m=len(trim(w(nwords))) !Length of section abbreviation
- if(m.lt.2 .or. m.gt.3) return
-
-! 0.3 WA9XYZ KA1ABC R 16A EMA 28 28 1 4 3 7 71 ARRL Field Day
-! 0.4 WA9XYZ KA1ABC R 32A EMA 28 28 1 4 3 7 71 ARRL Field Day
-
- i3=0
- n3=3 !Type 0.3 ARRL Field Day
- intx=ntx-1
- if(intx.ge.16) then
- n3=4 !Type 0.4 ARRL Field Day
- intx=ntx-17
- endif
- call pack28(w(1),n28a)
- call pack28(w(2),n28b)
- ir=0
- if(w(3)(1:2).eq.'R ') ir=1
- write(c77,1010) n28a,n28b,ir,intx,nclass,isec,n3,i3
-1010 format(2b28.28,b1,b4.4,b3.3,b7.7,2b3.3)
-
- return
-end subroutine pack77_03
-
-
-subroutine pack77_06(nwords,w,i3,n3,c77,i3_hint,n3_hint)
-
- character*13 w(19)
- character*77 c77
- character*6 bcall,grid6
- character*4 grid4
- character*1 c
- character*36 a2
- data a2/'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'/,nzzz/46656/
-
- logical is_grid4,is_grid6,is_digit,ok
- is_grid4(grid4)=len(trim(grid4)).eq.4 .and. &
- grid4(1:1).ge.'A' .and. grid4(1:1).le.'R' .and. &
- grid4(2:2).ge.'A' .and. grid4(2:2).le.'R' .and. &
- grid4(3:3).ge.'0' .and. grid4(3:3).le.'9' .and. &
- grid4(4:4).ge.'0' .and. grid4(4:4).le.'9'
-
- is_grid6(grid6)=(len(trim(grid6)).eq.6.or.len(trim(grid6)).eq.4).and. &
- grid6(1:1).ge.'A' .and. grid6(1:1).le.'R' .and. &
- grid6(2:2).ge.'A' .and. grid6(2:2).le.'R' .and. &
- grid6(3:3).ge.'0' .and. grid6(3:3).le.'9' .and. &
- grid6(4:4).ge.'0' .and. grid6(4:4).le.'9' .and. &
- (len(trim(grid6)).eq.4.or. &
- (grid6(5:5).ge.'A' .and. grid6(5:5).le.'X' .and. &
- grid6(6:6).ge.'A' .and. grid6(6:6).le.'X'))
-
- is_digit(c)=c.ge.'0' .and. c.le.'9'
-
- m1=len(trim(w(1)))
- m2=len(trim(w(2)))
- m3=len(trim(w(3)))
- if(nwords.eq.3 .and. m1.ge.3 .and. m1.le.6 .and. m2.eq.4 .and. m3.le.2) then
-! WSPR Type 1
- if(.not.is_grid4(w(2)(1:4))) go to 900
- if(.not.is_digit(w(3)(1:1))) go to 900
- if(m3.eq.2) then
- if(.not.is_digit(w(3)(2:2))) go to 900
- endif
- i3=0
- n3=6
- call pack28(w(1),n28)
- grid4=w(2)(1:4)
- k1=(ichar(grid4(1:1))-ichar('A'))*18*10*10
- k2=(ichar(grid4(2:2))-ichar('A'))*10*10
- k3=(ichar(grid4(3:3))-ichar('0'))*10
- k4=(ichar(grid4(4:4))-ichar('0'))
- igrid4=k1+k2+k3+k4
- read(w(3),*) idbm
- if(idbm.lt.0) idbm=0
- if(idbm.gt.60) idbm=60
- idbm=nint(0.3*idbm)
- write(c77,1010) n28,igrid4,idbm,0,0,0,n3,i3
-1010 format(b28.28,b15.15,b5.5,2i1,b21.21,2b3.3)
- go to 900
- endif
- if(nwords.eq.2 .and. m1.ge.5 .and. m1.le.10 .and. m2.le.2) then
-! WSPR Type 2
- i1=index(w(1),'/')
- if(i1.lt.2 .or. i1.eq.m1) go to 900
- if(.not.is_digit(w(2)(1:1))) go to 900
- if(i1.eq.(m1-3) .and. .not.is_digit(w(1)(m1:m1))) go to 900
- if(m2.eq.2) then
- if(.not.is_digit(w(2)(2:2))) go to 900
- endif
- call chkcall(w(1),bcall,ok)
- if(.not.ok) go to 900
- if(i1.le.4) then
-! We have a prefix
- npfx=index(a2,w(1)(1:1))-1
- if(i1.ge.3) npfx=36*npfx + index(a2,w(1)(2:2))-1
- if(i1.eq.4) npfx=36*npfx + index(a2,w(1)(3:3))-1
- else
-! We have a suffix
- if((m1-i1).eq.1) npfx=index(a2,w(1)(i1+1:i1+1))-1
- if((m1-i1).eq.2) npfx=36*(index(a2,w(1)(i1+1:i1+1))-1) + &
- index(a2,w(1)(i1+2:i1+2))-1
- if((m1-i1).eq.3) then
-! Third character of a suffix must be a digit
- if(.not.is_digit(w(1)(i1+3:i1+3))) go to 900
- npfx=36*10*(index(a2,w(1)(i1+1:i1+1))-1) + &
- 10*(index(a2,w(1)(i1+2:i1+2))-1) + index(a2,w(1)(i1+3:i1+3))-1
- endif
- npfx=npfx + nzzz
- endif
- i3=0
- n3=6
- call pack28(bcall//' ',n28)
- read(w(2),*) idbm
- if(idbm.lt.0) idbm=0
- if(idbm.gt.60) idbm=60
- idbm=nint(0.3*idbm)
- write(c77,1020) n28,npfx,idbm,1,0,n3,i3
-1020 format(b28.28,b16.16,b5.5,i1,b21.21,2b3.3)
- go to 900
- endif
-
- if(i3_hint.eq.0.and.n3_hint.eq.6.and.nwords.eq.2 .and. m1.ge.5 &
- .and. m1.le.12 .and. m2.le.6) then
-! WSPR Type 3
-
- !n3_hint=6 and i3_hint=0 is a hint that the caller wanted a
- !50-bit encoding rather than the possible alternative n3=4 77-bit
- !encoding
- if(index(w(1),'<').lt.1 .or. index(w(1),'>').lt.1) go to 900
- grid6=w(2)(1:6)
- if(.not.is_grid6(grid6)) go to 900
- i3=0
- n3=6
- call pack28(w(1),n28)
- n22=n28-2063592
- k1=(ichar(grid6(1:1))-ichar('A'))*18*10*10*25*25
- k2=(ichar(grid6(2:2))-ichar('A'))*10*10*25*25
- k3=(ichar(grid6(3:3))-ichar('0'))*10*25*25
- k4=(ichar(grid6(4:4))-ichar('0'))*25*25
- if (grid6(5:6).eq.' ') then
- igrid6=k1+k2+k3+k4+24*25+24
- else
- k5=(ichar(grid6(5:5))-ichar('A'))*25
- k6=(ichar(grid6(6:6))-ichar('A'))
- igrid6=k1+k2+k3+k4+k5+k6
- endif
- write(c77,1030) n22,igrid6,2,0,n3,i3
-1030 format(b22.22,b25.25,b3.3,b21.21,2b3.3)
- endif
-
-900 return
-end subroutine pack77_06
-
-
-subroutine pack77_1(nwords,w,i3,n3,c77)
-
-! Check Type 1 (Standard 77-bit message) and Type 2 (ditto, with a "/P" call)
-! Example message: WA9XYZ/R KA1ABC/R R FN42 28 1 28 1 1 15 74
-
- parameter (MAXGRID4=32400)
- character*13 w(19),c13
- character*77 c77
- character*6 bcall_1,bcall_2
- character*4 grid4
- character c1*1,c2*2
- logical is_grid4
- logical ok1,ok2
- is_grid4(grid4)=len(trim(grid4)).eq.4 .and. &
- grid4(1:1).ge.'A' .and. grid4(1:1).le.'R' .and. &
- grid4(2:2).ge.'A' .and. grid4(2:2).le.'R' .and. &
- grid4(3:3).ge.'0' .and. grid4(3:3).le.'9' .and. &
- grid4(4:4).ge.'0' .and. grid4(4:4).le.'9'
-
- if(nwords.lt.2 .or. nwords.gt.4) return
- call chkcall(w(1),bcall_1,ok1)
- call chkcall(w(2),bcall_2,ok2)
- if(w(1)(1:3).eq.'DE ' .or. w(1)(1:3).eq.'CQ_' .or. w(1)(1:3).eq.'CQ ' .or. &
- w(1)(1:4).eq.'QRZ ') ok1=.true.
- if(w(1)(1:1).eq.'<' .and. index(w(1),'>').ge.5) ok1=.true.
- if(w(2)(1:1).eq.'<' .and. index(w(2),'>').ge.5) ok2=.true.
- if(.not.ok1 .or. .not.ok2) return
- if(w(1)(1:1).eq.'<' .and. index(w(2),'/').gt.0) return
- if(w(2)(1:1).eq.'<' .and. index(w(1),'/').gt.0) return
- if(nwords.eq.2 .and. (.not.ok2 .or. index(w(2),'/').ge.2)) return
- if(nwords.eq.2) go to 10
-
- c1=w(nwords)(1:1)
- c2=w(nwords)(1:2)
- if(.not.is_grid4(w(nwords)(1:4)) .and. c1.ne.'+' .and. c1.ne.'-' &
- .and. c2.ne.'R+' .and. c2.ne.'R-' .and. trim(w(nwords)).ne.'RRR' .and. &
- trim(w(nwords)).ne.'RR73' .and. trim(w(nwords)).ne.'73') return
- if(c1.eq.'+' .or. c1.eq.'-') then
- ir=0
- read(w(nwords),*,err=900) irpt
- if(irpt.ge.-50 .and. irpt.le.-31) irpt=irpt+101
- irpt=irpt+35
- else if(c2.eq.'R+' .or. c2.eq.'R-') then
- ir=1
- read(w(nwords)(2:),*,err=900) irpt
- if(irpt.ge.-50 .and. irpt.le.-31) irpt=irpt+101
- irpt=irpt+35
- else if(trim(w(nwords)).eq.'RRR') then
- ir=0
- irpt=2
- else if(trim(w(nwords)).eq.'RR73') then
- ir=0
- irpt=3
- else if(trim(w(nwords)).eq.'73') then
- ir=0
- irpt=4
- endif
-
-! 1 WA9XYZ/R KA1ABC/R R FN42 28 1 28 1 1 15 74 Standard msg
-! 2 PA3XYZ/P GM4ABC/P R JO22 28 1 28 1 1 15 74 EU VHF contest
-
-10 i1psuffix=index(w(1)//' ' ,'/P ')
- i2psuffix=index(w(2)//' ','/P ')
- if(nwords.eq.2 .or. nwords.eq.3 .or. (nwords.eq.4 .and. &
- w(3)(1:2).eq.'R ')) then
- n3=0
- i3=1 !Type 1: Standard message, possibly with "/R"
- if (i1psuffix.ge.4.or.i2psuffix.ge.4) i3=2 !Type 2, with "/P"
- endif
- c13=bcall_1
- if(c13(1:3).eq.'CQ_' .or. w(1)(1:1).eq.'<') c13=w(1)
- call pack28(c13,n28a)
- c13=bcall_2
- if(w(2)(1:1).eq.'<') c13=w(2)
- call pack28(c13,n28b)
- ipa=0
- ipb=0
- if(i1psuffix.ge.4.or.index(w(1)//' ','/R ').ge.4) ipa=1
- if(i2psuffix.ge.4.or.index(w(2)//' ','/R ').ge.4) ipb=1
-
- grid4=w(nwords)(1:4)
- if(is_grid4(grid4)) then
- ir=0
- if(w(3).eq.'R ') ir=1
- j1=(ichar(grid4(1:1))-ichar('A'))*18*10*10
- j2=(ichar(grid4(2:2))-ichar('A'))*10*10
- j3=(ichar(grid4(3:3))-ichar('0'))*10
- j4=(ichar(grid4(4:4))-ichar('0'))
- igrid4=j1+j2+j3+j4
- else
- igrid4=MAXGRID4 + irpt
- endif
- if(nwords.eq.2) then
- ir=0
- irpt=1
- igrid4=MAXGRID4+irpt
- endif
- write(c77,1000) n28a,ipa,n28b,ipb,ir,igrid4,i3
-1000 format(2(b28.28,b1),b1,b15.15,b3.3)
- return
-
-900 return
-end subroutine pack77_1
-
-
-subroutine pack77_3(nwords,w,i3,n3,c77)
-
-! Check Type 3 (ARRL RTTY contest exchange)
-! ARRL RTTY - US/Can: rpt state/prov R 579 MA
-! - DX: rpt serial R 559 0013
-! Example message: TU; W9XYZ K1ABC R 579 MA 1 28 28 1 3 13 74
-
- parameter (NUSCAN=171) !Number of US states and Canadian provinces/territories
- character*13 w(19)
- character*77 c77
- character*6 bcall_1,bcall_2
- character*3 cmult(NUSCAN),mult
- character crpt*3
- logical ok1,ok2
- data cmult/ &
- "AL ","AK ","AZ ","AR ","CA ","CO ","CT ","DE ","FL ","GA ", &
- "HI ","ID ","IL ","IN ","IA ","KS ","KY ","LA ","ME ","MD ", &
- "MA ","MI ","MN ","MS ","MO ","MT ","NE ","NV ","NH ","NJ ", &
- "NM ","NY ","NC ","ND ","OH ","OK ","OR ","PA ","RI ","SC ", &
- "SD ","TN ","TX ","UT ","VT ","VA ","WA ","WV ","WI ","WY ", &
- "NB ","NS ","QC ","ON ","MB ","SK ","AB ","BC ","NWT","NF ", &
- "LB ","NU ","YT ","PEI","DC ","DR ","FR ","GD ","GR ","OV ", &
- "ZH ","ZL ","X01","X02","X03","X04","X05","X06","X07","X08", &
- "X09","X10","X11","X12","X13","X14","X15","X16","X17","X18", &
- "X19","X20","X21","X22","X23","X24","X25","X26","X27","X28", &
- "X29","X30","X31","X32","X33","X34","X35","X36","X37","X38", &
- "X39","X40","X41","X42","X43","X44","X45","X46","X47","X48", &
- "X49","X50","X51","X52","X53","X54","X55","X56","X57","X58", &
- "X59","X60","X61","X62","X63","X64","X65","X66","X67","X68", &
- "X69","X70","X71","X72","X73","X74","X75","X76","X77","X78", &
- "X79","X80","X81","X82","X83","X84","X85","X86","X87","X88", &
- "X89","X90","X91","X92","X93","X94","X95","X96","X97","X98", &
- "X99"/
-
- if(w(1)(1:1).eq.'<' .and. w(2)(1:1).eq.'<') go to 900
- if(nwords.eq.4 .or. nwords.eq.5 .or. nwords.eq.6) then
- i1=1
- if(trim(w(1)).eq.'TU;') i1=2
- call chkcall(w(i1),bcall_1,ok1)
- call chkcall(w(i1+1),bcall_2,ok2)
- if(.not.ok1 .or. .not.ok2) go to 900
- crpt=w(nwords-1)(1:3)
- if(index(crpt,'-').ge.1 .or. index(crpt,'+').ge.1) go to 900
- if(crpt(1:1).eq.'5' .and. crpt(2:2).ge.'2' .and. crpt(2:2).le.'9' .and. &
- crpt(3:3).eq.'9') then
- nserial=0
- read(w(nwords),*,err=1) nserial
- endif
-1 mult=' '
- imult=-1
- do i=1,NUSCAN
- if(cmult(i).eq.w(nwords)) then
- imult=i
- mult=cmult(i)
- exit
- endif
+ do i=1,nwords
+ nw(i)=len(trim(w(i)))
enddo
- nexch=0
- if(nserial.gt.0) nexch=nserial
- if(imult.gt.0) nexch=8000+imult
- if(mult.ne.' ' .or. nserial.gt.0) then
- i3=3
- n3=0
- itu=0
- if(trim(w(1)).eq.'TU;') itu=1
- call pack28(w(1+itu),n28a)
- call pack28(w(2+itu),n28b)
- ir=0
- if(w(3+itu)(1:2).eq.'R ') ir=1
- read(w(3+itu+ir),*,err=900) irpt
- irpt=(irpt-509)/10 - 2
- if(irpt.lt.0) irpt=0
- if(irpt.gt.7) irpt=7
-! 3 TU; W9XYZ K1ABC R 579 MA 1 28 28 1 3 13 74 ARRL RTTY contest
-! 3 TU; W9XYZ G8ABC R 559 0013 1 28 28 1 3 13 74 ARRL RTTY (DX)
- write(c77,1010) itu,n28a,n28b,ir,irpt,nexch,i3
-1010 format(b1,2b28.28,b1,b3.3,b13.13,b3.3)
- endif
endif
900 return
-end subroutine pack77_3
-
-
-subroutine pack77_4(nwords,w,i3,n3,c77)
-
-! Check Type 4 (One nonstandard call and one hashed call)
-! Example message: <WA9XYZ> PJ4/KA1ABC RR73 12 58 1 2 1 74
-
- integer*8 n58
- logical ok1,ok2
- character*13 w(19)
- character*77 c77
- character*13 call_1,call_2
- character*11 c11
- character*6 bcall_1,bcall_2
- character*38 c
- data c/' 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ/'/
-
- iflip=0
- i3=-1
- if(nwords.eq.2 .or. nwords.eq.3) then
- call_1=w(1)
- if(call_1(1:1).eq.'<') call_1=w(1)(2:len(trim(w(1)))-1)
- call_2=w(2)
- if(call_2(1:1).eq.'<') call_2=w(2)(2:len(trim(w(2)))-1)
- call chkcall(call_1,bcall_1,ok1)
- call chkcall(call_2,bcall_2,ok2)
- if(call_1.eq.bcall_1 .and. call_2.eq.bcall_2 .and. ok1 .and. ok2) go to 900
- icq=0
- if(trim(w(1)).eq.'CQ' .or. (ok1.and.ok2)) then
- if(trim(w(1)).eq.'CQ' .and. len(trim(w(2))).le.4) go to 900
- i3=4
- n3=0
- if(trim(w(1)).eq.'CQ') icq=1
- endif
-
- if(icq.eq.1) then
- iflip=0
- n12=0
- c11=adjustr(call_2(1:11))
- call save_hash_call(w(2),n10,n12,n22)
- else if(w(1)(1:1).eq.'<') then
- iflip=0
- i3=4
- call save_hash_call(w(1),n10,n12,n22)
- c11=adjustr(call_2(1:11))
- else if(w(2)(1:1).eq.'<') then
- iflip=1
- i3=4
- call save_hash_call(w(2),n10,n12,n22)
- c11=adjustr(call_1(1:11))
- endif
- n58=0
- do i=1,11
- n58=n58*38 + index(c,c11(i:i)) - 1
- enddo
- nrpt=0
- if(trim(w(3)).eq.'RRR') nrpt=1
- if(trim(w(3)).eq.'RR73') nrpt=2
- if(trim(w(3)).eq.'73') nrpt=3
- if(icq.eq.1) then
- iflip=0
- nrpt=0
- endif
- write(c77,1010) n12,n58,iflip,nrpt,icq,i3
-1010 format(b12.12,b58.58,b1,b2.2,b1,b3.3)
- do i=1,77
- if(c77(i:i).eq.'*') c77(i:i)='0' !### Clean up any illegal chars ###
- enddo
- endif
-
-900 return
-end subroutine pack77_4
-
-subroutine pack77_5(nwords,w,i3,n3,c77)
-
-! Pack a Type 0.2 message: EU VHF Contest mode
-! Example message: PA3XYZ/P R 590003 IO91NP 28 1 1 3 12 25
-! <PA3XYZ> <G4ABC/P> R 590003 IO91NP h10 h20 r1 s3 s12 g25
-
- character*13 w(19),c13
- character*77 c77
- character*6 grid6
- logical is_grid6
-
- is_grid6(grid6)=len(trim(grid6)).eq.6 .and. &
- grid6(1:1).ge.'A' .and. grid6(1:1).le.'R' .and. &
- grid6(2:2).ge.'A' .and. grid6(2:2).le.'R' .and. &
- grid6(3:3).ge.'0' .and. grid6(3:3).le.'9' .and. &
- grid6(4:4).ge.'0' .and. grid6(4:4).le.'9' .and. &
- grid6(5:5).ge.'A' .and. grid6(5:5).le.'X' .and. &
- grid6(6:6).ge.'A' .and. grid6(6:6).le.'X'
-
- if(nwords.lt.4 .or. nwords.gt.5) return !nwords must be 4 or 5
- if(w(1)(1:1).ne.'<' .or. w(2)(1:1).ne.'<') return !Both calls must be hashed
- nx=-1
- read(w(nwords-1),*,err=2) nx
-2 if(nx.lt.520001 .or. nx.gt.594095) return !Exchange between 520001 - 594095
- if(.not.is_grid6(w(nwords)(1:6))) return !Last word must be a valid grid6
-
-! Type 0.2: <PA3XYZ> <G4ABC/P> R 590003 IO91NP h10 h20 r1 s3 s12 g25
-
- i3=5
- n3=0
-
- call save_hash_call(w(1),n10,n12,n22)
- i2=index(w(1),'>')
- c13=w(1)(2:i2-1)
- n12=ihashcall(c13,12)
-
- call save_hash_call(w(2),n10a,n12a,n22)
- i2=index(w(2),'>')
- c13=w(2)(2:i2-1)
- n22=ihashcall(c13,22)
-
- ir=0
- if(w(3)(1:2).eq.'R ') ir=1
- irpt=nx/10000 - 52
- iserial=mod(nx,10000)
- if(iserial.gt.2047) iserial=2047
- grid6=w(nwords)(1:6)
- j1=(ichar(grid6(1:1))-ichar('A'))*18*10*10*24*24
- j2=(ichar(grid6(2:2))-ichar('A'))*10*10*24*24
- j3=(ichar(grid6(3:3))-ichar('0'))*10*24*24
- j4=(ichar(grid6(4:4))-ichar('0'))*24*24
- j5=(ichar(grid6(5:5))-ichar('A'))*24
- j6=(ichar(grid6(6:6))-ichar('A'))
- igrid6=j1+j2+j3+j4+j5+j6
-
- write(c77,1010) n12,n22,ir,irpt,iserial,igrid6,i3
-1010 format(b12.12,b22.22,b1,b3.3,b11.11,b25.25,b3.3)
-
- return
-end subroutine pack77_5
+end subroutine split77
subroutine packtext77(c13,c71)
@@ -1531,14 +1201,13 @@ subroutine unpacktext77(c71,c13)
return
end subroutine unpacktext77
-subroutine mp_short_ops(w,u)
+subroutine mp_short_init
character*1 w(*),u(*)
integer i,ireg,j,n,ir,iv,ii1,ii2
character*1 creg(4)
save ii1,ii2
equivalence (ireg,creg)
- entry mp_short_init
ireg=256*ichar('2')+ichar('1')
do j=1,4
if (creg(j).eq.'1') ii1=j
@@ -1572,9 +1241,9 @@ subroutine mp_short_ops(w,u)
ir=mod(i,iv)
enddo
return
-
+
return
-end subroutine mp_short_ops
+end subroutine mp_short_init
subroutine add_call_to_recent_calls(callsign)
@@ -1594,1814 +1263,1175 @@ subroutine add_call_to_recent_calls(callsign)
recent_calls(1)=callsign
endif
-! Make sure that callsign is hashed
-! call save_hash_call(callsign,n10,n12,n22) ! commented out - do this in the calling routine:
+! Recent-call ordering is separate from hash storage; decode paths stage both
+! effects explicitly when a call should become recent and hash-resolvable.
return
end subroutine add_call_to_recent_calls
-subroutine to_grid4(n,grid4,ok)
- character*4 grid4
- logical ok
- ok=.false.
- j1=n/(18*10*10)
- if (j1.lt.0.or.j1.gt.17) goto 900
- n=n-j1*18*10*10
- j2=n/(10*10)
- if (j2.lt.0.or.j2.gt.17) goto 900
- n=n-j2*10*10
- j3=n/10
- if (j3.lt.0.or.j3.gt.9) goto 900
- j4=n-j3*10
- if (j4.lt.0.or.j4.gt.9) goto 900
- grid4(1:1)=char(j1+ichar('A'))
- grid4(2:2)=char(j2+ichar('A'))
- grid4(3:3)=char(j3+ichar('0'))
- grid4(4:4)=char(j4+ichar('0'))
- ok=.true.
-
-900 return
-end subroutine to_grid4
-
-subroutine to_grid6(n,grid6,ok)
- character*6 grid6
- logical ok
-
- ok=.false.
- j1=n/(18*10*10*24*24)
- if (j1.lt.0.or.j1.gt.17) goto 900
- n=n-j1*18*10*10*24*24
- j2=n/(10*10*24*24)
- if (j2.lt.0.or.j2.gt.17) goto 900
- n=n-j2*10*10*24*24
- j3=n/(10*24*24)
- if (j3.lt.0.or.j3.gt.9) goto 900
- n=n-j3*10*24*24
- j4=n/(24*24)
- if (j4.lt.0.or.j4.gt.9) goto 900
- n=n-j4*24*24
- j5=n/24
- if (j5.lt.0.or.j5.gt.23) goto 900
- j6=n-j5*24
- if (j6.lt.0.or.j6.gt.23) goto 900
- grid6(1:1)=char(j1+ichar('A'))
- grid6(2:2)=char(j2+ichar('A'))
- grid6(3:3)=char(j3+ichar('0'))
- grid6(4:4)=char(j4+ichar('0'))
- grid6(5:5)=char(j5+ichar('A'))
- grid6(6:6)=char(j6+ichar('A'))
- ok=.true.
-
-900 return
-end subroutine to_grid6
-
-subroutine to_grid(n,grid6,ok)
- ! 4-, or 6-character grid
- character*6 grid6
- logical ok
-
- ok=.false.
- j1=n/(18*10*10*25*25)
- if (j1.lt.0.or.j1.gt.17) goto 900
- n=n-j1*18*10*10*25*25
- j2=n/(10*10*25*25)
- if (j2.lt.0.or.j2.gt.17) goto 900
- n=n-j2*10*10*25*25
- j3=n/(10*25*25)
- if (j3.lt.0.or.j3.gt.9) goto 900
- n=n-j3*10*25*25
- j4=n/(25*25)
- if (j4.lt.0.or.j4.gt.9) goto 900
- n=n-j4*25*25
- j5=n/25
- if (j5.lt.0.or.j5.gt.24) goto 900
- j6=n-j5*25
- if (j6.lt.0.or.j6.gt.24) goto 900
- grid6=''
- grid6(1:1)=char(j1+ichar('A'))
- grid6(2:2)=char(j2+ichar('A'))
- grid6(3:3)=char(j3+ichar('0'))
- grid6(4:4)=char(j4+ichar('0'))
- if (j5.ne.24.or.j6.ne.24) then
- grid6(5:5)=char(j5+ichar('A'))
- grid6(6:6)=char(j6+ichar('A'))
- endif
- ok=.true.
-
-900 return
-end subroutine to_grid
-
-
-subroutine hash10var(n10,c13,nthr)
+subroutine queue_hash_call_for_thread(c13,nthr)
character*13 c13
integer, intent(in) :: nthr
- c13='<...>'
- if(n10.lt.0 .or. n10.gt.1023) return
- if(nthr.gt.25) then ! TX message
- if(len(trim(txcalls10var(n10))).gt.0) then
- c13=txcalls10var(n10)
- c13='<'//trim(c13)//'>'
- endif
- else
- if(len(trim(calls10var(n10))).gt.0) then
- c13=calls10var(n10)
- c13='<'//trim(c13)//'>'
- endif
- endif
- return
-
-end subroutine hash10var
+! Configured/var decode workers queue hash facts; fillhashvar later folds them
+! into the shared calls10/calls12/calls22 tables.
+ call queue_call_for_thread(c13,nthr,queued_calls_by_thread, &
+ nqueued_calls_by_thread)
-subroutine hash12var(n12,c13,nthr)
-
- character*13 c13
- integer, intent(in) :: nthr
-
- c13='<...>'
- if(n12.lt.0 .or. n12.gt.4095) return
- if(nthr.gt.25) then ! TX message
- if(len(trim(txcalls12var(n12))).gt.0) then
- c13=txcalls12var(n12)
- c13='<'//trim(c13)//'>'
- endif
- else
- if(len(trim(calls12var(n12))).gt.0) then
- c13=calls12var(n12)
- c13='<'//trim(c13)//'>'
- endif
- endif
return
+end subroutine queue_hash_call_for_thread
-end subroutine hash12var
-
-subroutine hash22var(n22,c13,nthr)
-
+subroutine queue_recent_call_for_thread(c13,nthr)
character*13 c13
integer, intent(in) :: nthr
-
- c13='<...>'
- if(nthr.gt.25) then ! TX message
- do i=1,nztxhashvar
- if(itxhash22var(i).eq.n22) then
- c13=txcalls22var(i)
- c13='<'//trim(c13)//'>'
- go to 900
- endif
- enddo
- else
- do i=1,nzhashvar
- if(ihash22var(i).eq.n22) then
- c13=calls22var(i)
- c13='<'//trim(c13)//'>'
- go to 900
- endif
- enddo
- endif
-
-900 return
-end subroutine hash22var
-integer function ihashcallvar(c0,m)
-
- integer*8 n8
- character*13 c0
- character*38 c
- data c/' 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ/'/
-
- n8=0
- do i=1,11
- j=index(c,c0(i:i)) - 1
- n8=38*n8 + j
- enddo
- ihashcallvar=ishft(47055833459_8*n8,m-64)
+ call queue_call_for_thread(c13,nthr,queued_recent_calls_by_thread, &
+ nqueued_recent_calls_by_thread)
return
-end function ihashcallvar
-
-subroutine save_hash_mycallvar(c13,n10,n12,n22)
+end subroutine queue_recent_call_for_thread
- character*13 c13,cw
+subroutine queue_call_for_thread(c13,nthr,queued_calls,nqueued_calls)
+ character(len=*), intent(in) :: c13
+ integer, intent(in) :: nthr
+ character(len=13), intent(inout) :: queued_calls(:)
+ integer, intent(inout) :: nqueued_calls(:)
+ character*13 cw
- cw=c13
+ if(nthr.lt.1 .or. nthr.gt.24) return
+ cw=c13
if(cw(1:1).eq.' ' .or. cw(1:5).eq.'<...>') return
if(cw(1:1).eq.'<') cw=cw(2:)
i=index(cw,'>')
if(i.gt.0) cw(i:)=' '
if(len(trim(cw)) .lt. 3) return
- n12=ihashcallvar(cw,12)
- if(n12.ge.0 .and. n12 .le. 4095 .and. cw.ne.mycall13var) calls12var(n12)=cw
+ nposition=thread_call_index(nthr)+nqueued_calls(nthr)
+ if(nposition.lt.thread_call_index(nthr+1)) then
+ nqueued_calls(nthr)=nqueued_calls(nthr)+1
+ queued_calls(nposition+1)=cw
+ endif
- n10=ihashcallvar(cw,10)
- if(n10.ge.0 .and. n10 .le. 1023 .and. cw.ne.mycall13var) calls10var(n10)=cw
+ return
+end subroutine queue_call_for_thread
- n22=ihashcallvar(cw,22)
- if(any(ihash22var.eq.n22)) then ! If entry exists, make sure callsign is the most recently received one
- where(ihash22var.eq.n22) calls22var=cw
- go to 1900
- endif
+subroutine fold_queued_recent_calls(numthreads)
-! New entry: move table down, making room for new one at the top
- ihash22var(nzhashvar:2:-1)=ihash22var(nzhashvar-1:1:-1)
+ integer, intent(in) :: numthreads
+ character*13 cw
-! Add the new entry
- calls22var(nzhashvar:2:-1)=calls22var(nzhashvar-1:1:-1)
- ihash22var(1)=n22
- calls22var(1)=cw
- if(nzhashvar.lt.MAXHASHvar) nzhashvar=nzhashvar+1
+ do i=1,numthreads
+ do m=1,nqueued_recent_calls_by_thread(i)
+ nposition=thread_call_index(i)+m
+ cw=queued_recent_calls_by_thread(nposition)
+ call add_call_to_recent_calls(cw)
+ enddo
+ enddo
-1900 continue
+ return
+end subroutine fold_queued_recent_calls
- return
-end subroutine save_hash_mycallvar
+subroutine sync_configured_calls_for_decode_start()
-subroutine save_hash_txcallvar(c13,n10,n12,n22,lhashit)
+! Capture the operator-configured calls at decode-cycle boundaries. These
+! hashes let configured decodes resolve hash-only messages without a separate
+! var hash table.
+ if(mycall13.ne.mycall13_configured_prev) then
+ if(len(trim(mycall13)).gt.2) then
+ call set_configured_mycall_from_current()
+ else
+ call clear_configured_mycall()
+ endif
+ endif
+ call sync_configured_mycall_value_from_current()
- character*13 c13,cw
- logical, intent(in) :: lhashit
+ if(dxcall13.ne.dxcall13_configured_prev) then
+ if(len(trim(dxcall13)).gt.2) then
+ call set_configured_dxcall_from_current()
+ else
+ call clear_configured_dxcall()
+ endif
+ endif
+ call sync_configured_dxcall_value_from_current()
- cw=c13
- if(cw(1:1).eq.' ' .or. cw(1:5).eq.'<...>') return
- if(cw(1:1).eq.'<') cw=cw(2:)
- i=index(cw,'>')
- if(i.gt.0) cw(i:)=' '
-
- if(len(trim(cw)) .lt. 3) return
+ return
+end subroutine sync_configured_calls_for_decode_start
- n12=ihashcallvar(cw,12)
+subroutine set_configured_mycall_from_current()
- if(lhashit) then
- if(n12.ge.0 .and. n12 .le. 4095 .and. cw.ne.mycall13var) txcalls12var(n12)=cw
+ mycall13_configured_set=.true.
+ mycall13_configured=mycall13
+ mycall13_configured_prev=mycall13
+ hashmy10_configured=ihashcall(mycall13,10)
+ hashmy12_configured=ihashcall(mycall13,12)
+ hashmy22_configured=ihashcall(mycall13,22)
+ call save_hash_call(mycall13,ndum10,ndum12,ndum22)
- n10=ihashcallvar(cw,10)
- if(n10.ge.0 .and. n10 .le. 1023 .and. cw.ne.mycall13var) txcalls10var(n10)=cw
+ return
+end subroutine set_configured_mycall_from_current
- n22=ihashcallvar(cw,22)
- if(any(itxhash22var.eq.n22)) then ! If entry exists, make sure callsign is the most recently received one
- where(itxhash22var.eq.n22) txcalls22var=cw
- go to 1900
- endif
+subroutine clear_configured_mycall()
-! New entry: move table down, making room for new one at the top
- itxhash22var(nztxhashvar:2:-1)=itxhash22var(nztxhashvar-1:1:-1)
+ mycall13_configured_set=.false.
+ mycall13_configured=' '
+ mycall13_configured_prev=' '
+ hashmy10_configured=-1
+ hashmy12_configured=-1
+ hashmy22_configured=-1
-! Add the new entry
- txcalls22var(nztxhashvar:2:-1)=txcalls22var(nztxhashvar-1:1:-1)
- itxhash22var(1)=n22
- txcalls22var(1)=cw
- if(nztxhashvar.lt.MAXTXHASHvar) nztxhashvar=nztxhashvar+1
+ return
+end subroutine clear_configured_mycall
-1900 continue
- endif
+subroutine sync_configured_mycall_value_from_current()
- return
-end subroutine save_hash_txcallvar
+ if(mycall13_configured_set) mycall13_configured=mycall13
-subroutine save_hash_callvar(c13,nthr)
+ return
+end subroutine sync_configured_mycall_value_from_current
- character*13 c13,cw
- integer, intent(in) :: nthr
+subroutine set_configured_dxcall_from_current()
- if(nthr.gt.24) return
- cw=c13
- if(cw(1:1).eq.' ' .or. cw(1:5).eq.'<...>') return
- if(cw(1:1).eq.'<') cw=cw(2:)
- i=index(cw,'>')
- if(i.gt.0) cw(i:)=' '
- if(len(trim(cw)) .lt. 3) return
+ dxcall13_configured_set=.true.
+ dxcall13_configured=dxcall13
+ dxcall13_configured_prev=dxcall13
+ hashdx10_configured=ihashcall(dxcall13,10)
+ ! Seed the manual DX Call before decode so first-cycle hash references to it
+ ! can resolve even if the call has not yet been decoded over the air.
+ call queue_hash_call_for_thread(dxcall13,1)
- nposition=nthrindexvar(nthr)+nlast_callsvar(nthr)
- if(nposition.lt.nthrindexvar(nthr+1)) then
- nlast_callsvar(nthr)=nlast_callsvar(nthr)+1
- last_callsvar(nposition+1)=cw
- endif
+ return
+end subroutine set_configured_dxcall_from_current
- return
-end subroutine save_hash_callvar
+subroutine clear_configured_dxcall()
-subroutine pack77var(msg0,i3,n3,c77,ntxhash)
+ dxcall13_configured_set=.false.
+ dxcall13_configured=' '
+ dxcall13_configured_prev=' '
+ hashdx10_configured=-1
- use packjt
- character*37 msg,msg0
- character*18 c18
- character*13 w(19)
- character*77 c77
- integer nw(19)
- integer ntel(3)
- integer, intent(in) :: ntxhash
+ return
+end subroutine clear_configured_dxcall
- msg=msg0
- i3_hint=i3
- n3_hint=n3
- i3=-1
- n3=-1
- if(i3_hint.eq.0 .and. n3_hint.eq.5) go to 5
+subroutine sync_configured_dxcall_value_from_current()
-! Convert msg to upper case; collapse multiple blanks; parse into words.
- call split77var(msg,nwords,nw,w)
- if(msg(1:3).eq.'CQ ' .or. msg(1:3).eq.'DE ' .or. msg(1:4).eq.'QRZ ') go to 100
+ if(dxcall13_configured_set) dxcall13_configured=dxcall13
-! Check 0.1 (DXpedition mode)
- call pack77_01var(nwords,w,i3,n3,c77,ntxhash)
- if(i3.ge.0 .or. n3.ge.1) go to 900
-! Check 0.2 (EU VHF contest exchange)
-! call pack77_02(nwords,w,i3,n3,c77)
-! if(i3.ge.0) go to 900
+ return
+end subroutine sync_configured_dxcall_value_from_current
-! Check 0.3 and 0.4 (ARRL Field Day exchange)
- call pack77_03var(nwords,w,i3,n3,c77,ntxhash)
- if(i3.ge.0) go to 900
- if(nwords.ge.2) go to 100
+type(configured_decode_state) function current_configured_decode_state() &
+ result(state)
- ! Check 0.5 (telemetry)
-5 i0=index(msg,' ')
- c18=msg(1:i0-1)
- c18=adjustr(c18)
- ntel=-99
- read(c18,1005,err=6) ntel
-1005 format(3z6)
- if(ntel(1).ge.2**23) go to 800
-6 if(ntel(1).ge.0 .and. ntel(2).ge.0 .and. ntel(3).ge.0) then
- i3=0
- n3=5
- write(c77,1006) ntel,n3,i3
-1006 format(b23.23,2b24.24,2b3.3)
- go to 900
- endif
+ state%mycall_set=mycall13_configured_set
+ state%dxcall_set=dxcall13_configured_set
+ state%mycall=mycall13_configured
+ state%dxcall=dxcall13_configured
+ state%hashmy10=hashmy10_configured
+ state%hashmy12=hashmy12_configured
+ state%hashmy22=hashmy22_configured
+ state%hashdx10=hashdx10_configured
+
+ return
+end function current_configured_decode_state
+
+type(unpack77_context) function configured_unpack77_context(nrx) result(context)
+ integer, intent(in) :: nrx
+ type(configured_decode_state) :: state
+
+ state=current_configured_decode_state()
+ context%nrx=nrx
+ context%configured=.true.
+ context%strict_var_guards=.true.
+ context%mycall_set=state%mycall_set
+ context%dxcall_set=state%dxcall_set
+ context%mycall=state%mycall
+ context%dxcall=state%dxcall
+ context%hashmy10=state%hashmy10
+ context%hashmy12=state%hashmy12
+ context%hashmy22=state%hashmy22
+ context%hashdx10=state%hashdx10
+end function configured_unpack77_context
+
+type(unpack77_effect_policy) function configured_unpack77_effect_policy(options) &
+ result(policy)
+ type(unpack77_options), intent(in) :: options
+
+ policy=unpack77_effect_policy(queue_by_thread=.true., &
+ nthr_hash=options%thread_index,nthr_recent=options%thread_index)
+ policy%record_hashes=options%record_hashes
+ policy%record_recent_calls=options%record_recent_calls
+end function configured_unpack77_effect_policy
+
+subroutine unpack77_configured(c77,nrx,msg,unpk77_successvar,options)
+ character*77 c77
+ character*37 msg
+ integer, intent(in) :: nrx
+ logical unpk77_successvar
+ type(unpack77_options), intent(in) :: options
+ type(unpack77_context) :: context
+ type(unpack77_effect_policy) :: policy
-100 call pack77_06var(nwords,w,i3,n3,c77,i3_hint,n3_hint,ntxhash)
- if(i3.ge.0) go to 900
+ context=configured_unpack77_context(nrx)
+ policy=configured_unpack77_effect_policy(options)
+ call run_unpack77(c77,context,policy,msg,unpk77_successvar)
-! Check Type 1 (Standard 77-bit message) or Type 2, with optional "/P"
- call pack77_1var(nwords,w,i3,n3,c77,ntxhash)
- if(i3.ge.0) go to 900
+ return
+end subroutine unpack77_configured
-! Check Type 3 (ARRL RTTY contest exchange)
- call pack77_3var(nwords,w,i3,n3,c77,ntxhash)
- if(i3.ge.0) go to 900
+subroutine run_unpack77(c77,context,policy,msg,unpk77_success)
+ character*77 c77
+ type(unpack77_context), intent(in) :: context
+ type(unpack77_effect_policy), intent(in) :: policy
+ character*37 msg
+ logical unpk77_success
+ type(unpack77_core_result) :: decoded
-! Check Type 4 (One nonstandard call and one hashed call)
- call pack77_4var(nwords,w,i3,n3,c77,ntxhash)
- if(i3.ge.0) go to 900
+ decoded=unpack77_core(c77,context)
+ msg=decoded%msg
+ unpk77_success=decoded%success
+ if(unpk77_success) call apply_unpack77_effects(decoded%effects,policy)
-! Check Type 5 (EU VHF Contest with 2 hashed calls, report, serial, and grid6)
- call pack77_5var(nwords,w,i3,n3,c77,ntxhash)
- if(i3.ge.0) go to 900
+ return
+end subroutine run_unpack77
-! It defaults to free text
-800 i3=0
- n3=0
- msg(14:)=' '
- call packtext77var(msg(1:13),c77(1:71))
- write(c77(72:77),'(2b3.3)') n3,i3
+type(unpack77_core_result) function unpack77_core(c77,context) result(decoded)
-900 return
-end subroutine pack77var
+ character*77 c77
+ type(unpack77_context), intent(in) :: context
+ logical ok
-subroutine unpack77var(c77,nrx,msg,unpk77_successvar,nthr)
-!
-! nrx=1 when unpacking a received message
-! nrx=0 when unpacking a to-be-transmitted message
-! the value of nrx is used to decide when mycall13var or dxcall13var should
-! be used in place of a callsign from the hashtable
-!
- parameter (NSEC=86) !Number of ARRL Sections
- parameter (NUSCAN=171) !Number of States and Provinces
- parameter (MAXGRID4=32400)
- integer*8 n58
- integer ntel(3)
+ decoded=unpack77_core_result()
+ decoded%msg=repeat(' ',37)
+ call decode_pack77_tag(c77,decoded%i3,decoded%n3,ok)
+ if(.not.ok) then
+ decoded%msg='failed unpack'
+ return
+ endif
+ decoded%success=.true.
+
+ if(decoded%i3.eq.0) then
+ call unpack77_decode_i3_0(c77,context,decoded)
+ else if(decoded%i3.eq.1 .or. decoded%i3.eq.2) then
+ call unpack77_decode_type12(c77,context,decoded)
+ else if(decoded%i3.eq.3) then
+ call unpack77_decode_type3(c77,context,decoded)
+ else if(decoded%i3.eq.4) then
+ call unpack77_decode_type4(c77,context,decoded)
+ else if(decoded%i3.eq.5) then
+ call unpack77_decode_type5(c77,context,decoded)
+ else if(decoded%i3.ge.6) then
+ decoded%success=.false.
+ endif
+! CQ addressed to a hashed/nonstandard call is not a legal message form in
+! any type; preserved verbatim from the legacy decoder.
+ if(decoded%msg(1:4).eq.'CQ <') decoded%success=.false.
+
+ return
+end function unpack77_core
+
+subroutine unpack77_decode_i3_0(c77,context,decoded)
character*77 c77
- character*37 msg
+ type(unpack77_context), intent(in) :: context
+ type(unpack77_core_result), intent(inout) :: decoded
+ integer ntel(3)
character*13 call_1,call_2,call_3,call_1a
- character*11 c11
character*3 crpt,cntx,cpfx
- character*3 cmult(NUSCAN)
- character*6 cexch,grid6
- character*4 grid4,cserial
- character*3 csec(NSEC)
- character*38 c
- character*36 a2
- logical unpk28_success,unpk77_successvar,unpkg4_success
- integer, intent(in) :: nthr
-
- data a2/'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'/,nzzz/46656/
- data c/' 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ/'/
- data csec/ &
- "AB ","AK ","AL ","AR ","AZ ","BC ","CO ","CT ","DE ","EB ", &
- "EMA","ENY","EPA","EWA","GA ","GH ","IA ","ID ","IL ","IN ", &
- "KS ","KY ","LA ","LAX","NS ","MB ","MDC","ME ","MI ","MN ", &
- "MO ","MS ","MT ","NC ","ND ","NE ","NFL","NH ","NL ","NLI", &
- "NM ","NNJ","NNY","TER","NTX","NV ","OH ","OK ","ONE","ONN", &
- "ONS","OR ","ORG","PAC","PR ","QC ","RI ","SB ","SC ","SCV", &
- "SD ","SDG","SF ","SFL","SJV","SK ","SNJ","STX","SV ","TN ", &
- "UT ","VA ","VI ","VT ","WCF","WI ","WMA","WNY","WPA","WTX", &
- "WV ","WWA","WY ","DX ","PE ","NB "/
- data cmult/ &
- "AL ","AK ","AZ ","AR ","CA ","CO ","CT ","DE ","FL ","GA ", &
- "HI ","ID ","IL ","IN ","IA ","KS ","KY ","LA ","ME ","MD ", &
- "MA ","MI ","MN ","MS ","MO ","MT ","NE ","NV ","NH ","NJ ", &
- "NM ","NY ","NC ","ND ","OH ","OK ","OR ","PA ","RI ","SC ", &
- "SD ","TN ","TX ","UT ","VT ","VA ","WA ","WV ","WI ","WY ", &
- "NB ","NS ","QC ","ON ","MB ","SK ","AB ","BC ","NWT","NF ", &
- "LB ","NU ","YT ","PEI","DC ","DR ","FR ","GD ","GR ","OV ", &
- "ZH ","ZL ","X01","X02","X03","X04","X05","X06","X07","X08", &
- "X09","X10","X11","X12","X13","X14","X15","X16","X17","X18", &
- "X19","X20","X21","X22","X23","X24","X25","X26","X27","X28", &
- "X29","X30","X31","X32","X33","X34","X35","X36","X37","X38", &
- "X39","X40","X41","X42","X43","X44","X45","X46","X47","X48", &
- "X49","X50","X51","X52","X53","X54","X55","X56","X57","X58", &
- "X59","X60","X61","X62","X63","X64","X65","X66","X67","X68", &
- "X69","X70","X71","X72","X73","X74","X75","X76","X77","X78", &
- "X79","X80","X81","X82","X83","X84","X85","X86","X87","X88", &
- "X89","X90","X91","X92","X93","X94","X95","X96","X97","X98", &
- "X99"/
-
- unpk77_successvar=.true.
-
-! Check for bad data
- do i=1,77
- if(c77(i:i).ne.'0' .and. c77(i:i).ne.'1') then
- msg='failed unpack'
- unpk77_successvar=.false.
+ character*6 grid6
+ character*4 grid4
+ logical unpk28_success,unpkg4_success,ok,is_prefix
+ type(pack77_free_text_fields) :: free_text_fields
+ type(pack77_telemetry_fields) :: telemetry_fields
+ type(pack77_dxpedition_fields) :: dxpedition_fields
+ type(pack77_field_day_fields) :: field_day_fields
+ type(pack77_wspr_type1_fields) :: wspr1_fields
+ type(pack77_wspr_type2_fields) :: wspr2_fields
+ type(pack77_wspr_type3_fields) :: wspr3_fields
+ integer :: n28a,n28b
+
+ if(decoded%n3.eq.0) then
+! 0.0 Free text
+ call decode_pack77_free_text(c77,free_text_fields,ok,.true.)
+ if(.not.ok) then
+ decoded%success=.false.
return
endif
- enddo
+ call unpacktext77(free_text_fields%text_bits,decoded%msg(1:13))
+ decoded%msg(14:)=' '
+ decoded%msg=adjustl(decoded%msg)
+ if(decoded%msg(1:1).eq.' ') decoded%success=.false.
- read(c77(72:77),'(2b3)') n3,i3
- msg=repeat(' ',37)
- if(i3.eq.0 .and. n3.eq.0) then
-! 0.0 Free text
- call unpacktext77var(c77(1:71),msg(1:13))
- msg(14:)=' '
- msg=adjustl(msg)
- if(msg(1:1).eq.' ') then
- unpk77_successvar=.false.
+ else if(decoded%n3.eq.1) then
+! 0.1 K1ABC RR73; W9XYZ <KH1/KH7Z> -11 28 28 10 5 71 DXpedition Mode
+ call decode_pack77_dxpedition(c77,dxpedition_fields,ok,.true.)
+ if(.not.ok) then
+ decoded%success=.false.
return
endif
- else if(i3.eq.0 .and. n3.eq.1) then
-! 0.1 K1ABC RR73; W9XYZ <KH1/KH7Z> -11 28 28 10 5 71 DXpedition Mode
- read(c77,1010) n28avar,n28bvar,n10,n5
-1010 format(2b28,b10,b5)
+ n28a=dxpedition_fields%n28a
+ n28b=dxpedition_fields%n28b
+ n10=dxpedition_fields%n10
+ n5=dxpedition_fields%n5
+ call record_configured_n28_pair(context,n28a,n28b)
irpt=2*n5 - 30
- write(crpt,1012) irpt
-1012 format(i3.2)
- if(irpt.ge.0) crpt(1:1)='+'
- call unpack28var(n28avar,call_1,unpk28_success,nthr)
- if(.not.unpk28_success .or. n28avar.le.2) unpk77_successvar=.false.
- call unpack28var(n28bvar,call_2,unpk28_success,nthr)
- if(.not.unpk28_success .or. n28bvar.le.2) unpk77_successvar=.false.
- call hash10var(n10,call_3,nthr)
- if(call_3.eq.'<...>') then
- call hash10(n10,call_3)
- endif
-
- if(nrx.eq.1) then
- if(dxcall13_setvar .and. len(trim(dxcall13var)).ge.3 .and. hashdx10var.eq.n10) then; call_3='<'//trim(dxcall13var)//'>'
- elseif(.not.dxcall13_setvar .and. len(trim(dxcall13var)).ge.3 .and. .not.lcommonft8b .and. hashdx10var.eq.n10) then
- call_3='<'//trim(dxcall13_0var)//'>'
- elseif(.not.dxcall13_setvar .and. len(trim(dxcall13var)).ge.3 .and. .not.lcommonft8b .and. hashdx10var.ne.n10) then
- call_3=trim(call_3)
- elseif(.not.dxcall13_setvar .and. len(trim(dxcall13var)).ge.3 .and. lcommonft8b .and. hashdx10var.eq.n10) then
- call_3='<'//trim(dxcall13_0var)//'>'
- elseif(.not.dxcall13_setvar .and. len(trim(dxcall13var)).ge.3 .and. lcommonft8b .and. hashdx10var.ne.n10) then
- call_3='<...>'
- endif
+ crpt=pack77_format_snr_report(irpt)
+ call unpack28_for_context(context,n28a,call_1,unpk28_success)
+ if(.not.unpk28_success .or. n28a.le.2) decoded%success=.false.
+ call unpack28_for_context(context,n28b,call_2,unpk28_success)
+ if(.not.unpk28_success .or. n28b.le.2) decoded%success=.false.
+ call hash10(n10,call_3)
+ if(context%nrx.eq.1) then
+ if(context%dxcall_set .and. len(trim(context%dxcall)).ge.3 .and. &
+ context%hashdx10.eq.n10) then
+ call_3='<'//trim(context%dxcall)//'>'
+ endif
endif
- if(nrx.eq.0 .and. mycall13_setvar .and. n10.eq.hashmy10var) call_3='<'//trim(mycall13var)//'>'
- msg=trim(call_1)//' RR73; '//trim(call_2)//' '//trim(call_3)//' '//crpt
+ if(context%nrx.eq.0 .and. context%mycall_set .and. &
+ n10.eq.context%hashmy10) call_3='<'//trim(context%mycall)//'>'
+ decoded%msg=trim(call_1)//' RR73; '//trim(call_2)//' '//trim(call_3)//' '//crpt
+
+ else if(decoded%n3.eq.2) then
+ decoded%success=.false.
- else if(i3.eq.0 .and. n3.eq.2) then
- unpk77_successvar=.false.
-
- else if(i3.eq.0 .and. (n3.eq.3 .or. n3.eq.4)) then
+ else if(decoded%n3.eq.3 .or. decoded%n3.eq.4) then
! 0.3 WA9XYZ KA1ABC R 16A EMA 28 28 1 4 3 7 71 ARRL Field Day
! 0.4 WA9XYZ KA1ABC R 32A EMA 28 28 1 4 3 7 71 ARRL Field Day
- read(c77,1030) n28avar,n28bvar,ir,intx,nclass,isec
-1030 format(2b28,b1,b4,b3,b7)
- if(isec.gt.NSEC .or. isec.lt.1) then
- unpk77_successvar=.false.
+ if(decoded%n3.eq.3) then
+ call decode_pack77_field_day_low(c77,field_day_fields,ok,.true.)
+ else
+ call decode_pack77_field_day_high(c77,field_day_fields,ok,.true.)
+ endif
+ if(.not.ok) then
+ decoded%success=.false.
+ return
+ endif
+ n28a=field_day_fields%n28a
+ n28b=field_day_fields%n28b
+ ir=field_day_fields%ir
+ intx=field_day_fields%intx
+ nclass=field_day_fields%nclass
+ isec=field_day_fields%isec
+ call record_configured_n28_pair(context,n28a,n28b)
+ if(isec.gt.PACK77_NSEC .or. isec.lt.1) then
+ decoded%success=.false.
isec=1
endif
- call unpack28var(n28avar,call_1,unpk28_success,nthr)
- if(.not.unpk28_success .or. n28avar.le.2) unpk77_successvar=.false.
- call unpack28var(n28bvar,call_2,unpk28_success,nthr)
- if(.not.unpk28_success .or. n28bvar.le.2) unpk77_successvar=.false.
+ call unpack28_for_context(context,n28a,call_1,unpk28_success)
+ if(.not.unpk28_success .or. n28a.le.2) decoded%success=.false.
+ call unpack28_for_context(context,n28b,call_2,unpk28_success)
+ if(.not.unpk28_success .or. n28b.le.2) decoded%success=.false.
ntx=intx+1
- if(n3.eq.4) ntx=ntx+16
- write(cntx(1:2),1032) ntx
-1032 format(i2)
+ if(decoded%n3.eq.4) ntx=ntx+16
+ write(cntx(1:2),'(i2)') ntx
cntx(3:3)=char(ichar('A')+nclass)
- if(ir.eq.0 .and. ntx.lt.10) msg=trim(call_1)//' '//trim(call_2)// &
- cntx//' '//csec(isec)
- if(ir.eq.1 .and. ntx.lt.10) msg=trim(call_1)//' '//trim(call_2)// &
- ' R'//cntx//' '//csec(isec)
- if(ir.eq.0 .and. ntx.ge.10) msg=trim(call_1)//' '//trim(call_2)// &
- ' '//cntx//' '//csec(isec)
- if(ir.eq.1 .and. ntx.ge.10) msg=trim(call_1)//' '//trim(call_2)// &
- ' R '//cntx//' '//csec(isec)
-
- else if(i3.eq.0 .and. n3.eq.5) then
+ decoded%msg=pack77_format_exchange_message(call_1,call_2,ir, &
+ trim(adjustl(cntx))//' '//pack77_arrl_section_name(isec),.true.)
+
+ else if(decoded%n3.eq.5) then
! 0.5 0123456789abcdef01 71 71 Telemetry (18 hex)
- read(c77,1006) ntel
-1006 format(b23,2b24)
- write(msg,1007) ntel
+ call decode_pack77_telemetry(c77,telemetry_fields,ok,.true.)
+ if(.not.ok) then
+ decoded%success=.false.
+ return
+ endif
+ ntel=(/telemetry_fields%ntel1,telemetry_fields%ntel2,telemetry_fields%ntel3/)
+ write(decoded%msg,1007) ntel
1007 format(3z6.6)
- do i=1,18
- if(msg(i:i).ne.'0') exit
- msg(i:i)=' '
- enddo
- msg=adjustl(msg)
-
- else if(i3.eq.0 .and. n3.eq.6) then
- read(c77(49:50),'(2b1)') j2a,j2b
- itype=2
- if(j2b.eq.0 .and. j2a.eq.0) itype=1
- if(j2b.eq.0 .and. j2a.eq.1) itype=3
- if(itype.eq.1) then
-! WSPR Type 1
- read(c77,2010) n28,igrid4,idbm
-2010 format(b28.28,b15.15,b5.5)
- idbm=nint(idbm*10.0/3.0)
- call unpack28var(n28,call_1,unpk28_success,nthr)
- if(.not.unpk28_success) unpk77_successvar=.false.
- call to_grid4var(igrid4,grid4,unpkg4_success)
- if(.not.unpkg4_success) unpk77_successvar=.false.
- write(crpt,'(i3)') idbm
- msg=trim(call_1)//' '//grid4//' '//trim(adjustl(crpt))
- if (unpk77_successvar) call save_hash_callvar(call_1,nthr) !### Is this OK here? ###
- else if(itype.eq.2) then
+ else if(decoded%n3.eq.6) then
+ select case(pack77_wspr_payload_type(c77))
+ case(2)
+ call decode_pack77_wspr_type2(c77,wspr2_fields,ok,.true.)
+ if(.not.ok) then
+ decoded%success=.false.
+ return
+ endif
! WSPR Type 2
- read(c77,2020) n28,npfx,idbm
-2020 format(b28.28,b16.16,b5.5)
- idbm=nint(idbm*10.0/3.0)
- call unpack28var(n28,call_1,unpk28_success,nthr)
- if(.not.unpk28_success) unpk77_successvar=.false.
+ n28=wspr2_fields%n28
+ npfx=wspr2_fields%npfx
+ idbm=nint(wspr2_fields%idbm*10.0/3.0)
+ call unpack28_for_context(context,n28,call_1,unpk28_success)
+ if(.not.unpk28_success) decoded%success=.false.
write(crpt,'(i3)') idbm
- cpfx=' '
- if(npfx.lt.nzzz) then
-! Prefix
- do i=3,1,-1
- j=mod(npfx,36)+1
- cpfx(i:i)=a2(j:j)
- npfx=npfx/36
- if(npfx.eq.0) exit
- enddo
- msg=trim(adjustl(cpfx))//'/'//trim(call_1)//' '//trim(adjustl(crpt))
+ call pack77_wspr_affix_text(npfx,cpfx,is_prefix,ok)
+ if(.not.ok) then
+ decoded%success=.false.
+ return
+ endif
+ if(is_prefix) then
call_1a=trim(adjustl(cpfx))//'/'//trim(call_1)
- call save_hash_callvar(call_1a,nthr) !### Is this OK here? ###
else
-! Suffix
- npfx=npfx-nzzz
- if(npfx.le.35) then
- cpfx(1:1)=a2(npfx+1:npfx+1)
- else if(npfx.gt.35 .and. npfx.le.1295) then
- cpfx(1:1)=a2(npfx/36+1:npfx/36+1)
- cpfx(2:2)=a2(mod(npfx,36)+1:mod(npfx,36)+1)
- else if(npfx.gt.1295 .and. npfx.le.12959) then
- cpfx(1:1)=a2(npfx/360+1:npfx/360+1)
- cpfx(2:2)=a2(mod(npfx/10,36)+1:mod(npfx/10,36)+1)
- cpfx(3:3)=a2(mod(npfx,10)+1:mod(npfx,10)+1)
- else
- unpk77_successvar=.false.
- return
- endif
- msg=trim(call_1)//'/'//trim(adjustl(cpfx))//' '//trim(adjustl(crpt))
call_1a=trim(call_1)//'/'//trim(adjustl(cpfx))
- call save_hash_callvar(call_1a,nthr) !### Is this OK here? ###
endif
-
- else if(itype.eq.3) then
-! WSPR Type 3
- read(c77,2030) n22,igrid6
-2030 format(b22.22,b25.25)
- n28=n22+2063592
- call unpack28var(n28,call_1,unpk28_success,nthr)
- if(.not.unpk28_success) unpk77_successvar=.false.
- call to_gridvar(igrid6,grid6,unpkg4_success)
- if(.not.unpkg4_success) unpk77_successvar=.false.
- msg=trim(call_1)//' '//grid6
- endif
-
- else if(i3.eq.0 .and. n3.gt.6) then
- unpk77_successvar=.false.
-
- else if(i3.eq.1 .or. i3.eq.2) then
-! Type 1 (standard message) or Type 2 ("/P" form for EU VHF contest)
- read(c77,1000) n28avar,ipa,n28bvar,ipb,ir,igrid4,i3
-1000 format(2(b28,b1),b1,b15,b3)
- call unpack28var(n28avar,call_1,unpk28_success,nthr)
- if(nrx.eq.1 .and. mycall13_setvar .and. hashmy22var.eq.(n28avar-2063592)) then
- call_1='<'//trim(mycall13var)//'>'
- unpk28_success=.true.
- endif
- if(.not.unpk28_success) unpk77_successvar=.false.
- call unpack28var(n28bvar,call_2,unpk28_success,nthr)
- if(.not.unpk28_success) unpk77_successvar=.false.
- if(call_1(1:3).eq.'CQ_') call_1(3:3)=' '
- if(index(call_1,'<').le.0) then
- i=index(call_1,' ')
- if(i.ge.4 .and. ipa.eq.1 .and. i3.eq.1) call_1(i:i+1)='/R'
- if(i.ge.4 .and. ipa.eq.1 .and. i3.eq.2) call_1(i:i+1)='/P'
- if(i.ge.4) call add_call_to_recent_callsvar(call_1,nthr)
- endif
- if(index(call_2,'<').le.0) then
- i=index(call_2,' ')
- if(i.ge.4 .and. ipb.eq.1 .and. i3.eq.1) call_2(i:i+1)='/R'
- if(i.ge.4 .and. ipb.eq.1 .and. i3.eq.2) call_2(i:i+1)='/P'
- if(i.ge.4) then
- call add_call_to_recent_callsvar(call_2,nthr)
-! only hash the "from" call
- call save_hash_callvar(call_2,nthr)
- endif
- endif
- if(igrid4.le.MAXGRID4) then
- call to_grid4var(igrid4,grid4,unpkg4_success)
- if(.not.unpkg4_success) unpk77_successvar=.false.
- if(ir.eq.0) msg=trim(call_1)//' '//trim(call_2)//' '//grid4
- if(ir.eq.1) msg=trim(call_1)//' '//trim(call_2)//' R '//grid4
- if(msg(1:3).eq.'CQ ' .and. ir.eq.1) unpk77_successvar=.false.
-!out of current realisation of protocol: GRID is always dropped at WSJT-X/JTDX transmission of the messages below
-! i3 n3
-! 1 0
-!110015 -23 0.5 1450 ~ <...> Y96IHQ/R GL12
-!112215 -23 0.0 1606 ~ <...> 3U1TBM/R CC65
-!000102 -23 0.5 801 ~ <...> NV3QHV/R JF62
- if(ir.eq.0 .and. call_1(1:1).eq.'<' .and. grid4.ne.'RR73') then ! hash value can also be associated with a valid callsign
- nlencall2=len_trim(call_2)
- if(nlencall2.gt.1) then
- if(call_2(nlencall2-1:nlencall2).eq.'/R') unpk77_successvar=.false.
- endif
+ decoded%msg=trim(call_1a)//' '//trim(adjustl(crpt))
+ call stage_unpack_hash_call(decoded%effects,call_1a)
+
+ case(1)
+ call decode_pack77_wspr_type1(c77,wspr1_fields,ok,.true.)
+ if(.not.ok) then
+ decoded%success=.false.
+ return
endif
- else
- irpt=igrid4-MAXGRID4
- if(irpt.eq.1) msg=trim(call_1)//' '//trim(call_2)
- if(irpt.eq.2) msg=trim(call_1)//' '//trim(call_2)//' RRR'
- if(irpt.eq.3) msg=trim(call_1)//' '//trim(call_2)//' RR73'
- if(irpt.eq.4) msg=trim(call_1)//' '//trim(call_2)//' 73'
- if(irpt.ge.5) then
- isnr=irpt-35
- if(isnr.gt.50) isnr=isnr-101
- write(crpt,'(i3.2)') isnr
- if(crpt(1:1).eq.' ') crpt(1:1)='+'
- if(ir.eq.0) msg=trim(call_1)//' '//trim(call_2)//' '//crpt
- if(ir.eq.1) msg=trim(call_1)//' '//trim(call_2)//' R'//crpt
+! WSPR Type 1
+ n28=wspr1_fields%n28
+ igrid4=wspr1_fields%igrid4
+ idbm=nint(wspr1_fields%idbm*10.0/3.0)
+ call unpack28_for_context(context,n28,call_1,unpk28_success)
+ if(.not.unpk28_success) decoded%success=.false.
+ call to_grid4(igrid4,grid4,unpkg4_success)
+ if(.not.unpkg4_success) decoded%success=.false.
+ write(crpt,'(i3)') idbm
+ decoded%msg=trim(call_1)//' '//grid4//' '//trim(adjustl(crpt))
+ call stage_unpack_hash_call(decoded%effects,call_1)
+
+ case(3)
+ call decode_pack77_wspr_type3(c77,wspr3_fields,ok,.true.)
+ if(.not.ok) then
+ decoded%success=.false.
+ return
endif
- if(msg(1:3).eq.'CQ ' .and. irpt.ge.2) unpk77_successvar=.false.
- endif
+! WSPR Type 3
+ n22=wspr3_fields%n22
+ igrid6=wspr3_fields%igrid6
+ n28=n22+PACK77_NTOKENS
+ call unpack28_for_context(context,n28,call_1,unpk28_success)
+ if(.not.unpk28_success) decoded%success=.false.
+ call to_grid(igrid6,grid6,unpkg4_success)
+ if(.not.unpkg4_success) decoded%success=.false.
+ decoded%msg=trim(call_1)//' '//grid6
- else if(i3.eq.3) then
-! Type 3: ARRL RTTY Contest
- read(c77,1040) itu,n28avar,n28bvar,ir,irpt,nexch,i3
-1040 format(b1,2b28.28,b1,b3.3,b13.13,b3.3)
- write(crpt,1042) irpt+2
-1042 format('5',i1,'9')
- nserial=nexch
- imult=-1
- if(nexch.gt.8000) then
- imult=nexch-8000
- nserial=-1
- endif
- call unpack28var(n28avar,call_1,unpk28_success,nthr)
- if(.not.unpk28_success) unpk77_successvar=.false.
- call unpack28var(n28bvar,call_2,unpk28_success,nthr)
- if(.not.unpk28_success) unpk77_successvar=.false.
- imult=0
- nserial=0
- if(nexch.gt.8000) imult=nexch-8000
- if(nexch.lt.8000) nserial=nexch
-
- if(imult.ge.1 .and.imult.le.NUSCAN) then
- if(itu.eq.0 .and. ir.eq.0) msg=trim(call_1)//' '//trim(call_2)// &
- ' '//crpt//' '//cmult(imult)
- if(itu.eq.1 .and. ir.eq.0) msg='TU; '//trim(call_1)//' '//trim(call_2)// &
- ' '//crpt//' '//cmult(imult)
- if(itu.eq.0 .and. ir.eq.1) msg=trim(call_1)//' '//trim(call_2)// &
- ' R '//crpt//' '//cmult(imult)
- if(itu.eq.1 .and. ir.eq.1) msg='TU; '//trim(call_1)//' '//trim(call_2)// &
- ' R '//crpt//' '//cmult(imult)
- else if(nserial.ge.1 .and. nserial.le.7999) then
- write(cserial,'(i4.4)') nserial
- if(itu.eq.0 .and. ir.eq.0) msg=trim(call_1)//' '//trim(call_2)// &
- ' '//crpt//' '//cserial
- if(itu.eq.1 .and. ir.eq.0) msg='TU; '//trim(call_1)//' '//trim(call_2)// &
- ' '//crpt//' '//cserial
- if(itu.eq.0 .and. ir.eq.1) msg=trim(call_1)//' '//trim(call_2)// &
- ' R '//crpt//' '//cserial
- if(itu.eq.1 .and. ir.eq.1) msg='TU; '//trim(call_1)//' '//trim(call_2)// &
- ' R '//crpt//' '//cserial
- endif
+ case default
+ decoded%success=.false.
+ return
+ end select
- else if(i3.eq.4) then
-! Type 4
- read(c77,1050) n12,n58,iflip,nrpt,icq
-1050 format(b12,b58,b1,b2,b1)
- do i=11,1,-1
- j=mod(n58,38)+1
- c11(i:i)=c(j:j)
- n58=n58/38
- enddo
- call hash12var(n12,call_3,nthr)
- if(call_3.eq.'<...>') then
- call hash12(n12,call_3)
- endif
- if(iflip.eq.0) then ! 12 bit hash for TO call
- call_1=call_3
- call_2=adjustl(c11)//' '
- call add_call_to_recent_callsvar(call_2,nthr)
- if(nrx.eq.1 .and. &
- dxcall13_setvar .and. mycall13_setvar .and. &
- call_2.eq.dxcall13var .and. &
- n12.eq.hashmy12var ) call_1='<'//trim(mycall13var)//'>'
- if(nrx.eq.1 .and. &
- mycall13_setvar .and. &
- index(call_1,'<...>').gt.0 .and. &
- n12.eq.hashmy12var ) call_1='<'//trim(mycall13var)//'>'
- else ! 12 bit hash for DE call
- call_1=adjustl(c11)
- call_2=call_3
- call add_call_to_recent_callsvar(call_1,nthr)
- if(nrx.eq.0 .and. &
- mycall13_setvar .and. &
- n12.eq.hashmy12var) call_2='<'//trim(mycall13var)//'>'
- endif
- if(icq.eq.0) then
- if(nrpt.eq.0) msg=trim(call_1)//' '//trim(call_2)
- if(nrpt.eq.1) msg=trim(call_1)//' '//trim(call_2)//' RRR'
- if(nrpt.eq.2) msg=trim(call_1)//' '//trim(call_2)//' RR73'
- if(nrpt.eq.3) msg=trim(call_1)//' '//trim(call_2)//' 73'
- else
- msg='CQ '//trim(call_2)
- endif
- if(call_2(1:1).lt.':' .and. call_2(1:1).gt.'/' .and. call_2(2:2).lt.':' .and. call_2(2:2).gt.'/') unpk77_successvar=.false.
- if(len_trim(call_2).eq.11) then
- ispace=index(call_2,' '); if(ispace.gt.0 .and. ispace.lt.12) unpk77_successvar=.false.
- islash=index(call_2,'/'); if(islash.eq.1 .or. islash.eq.2 .or. islash.eq.11 .or. (islash.eq.10 .and. &
- call_2(11:11).gt.'@' .and. call_2(11:11).lt.'[' .and. call_2(11:11).ne.'P')) unpk77_successvar=.false.
- if(islash.lt.6 .and. call_2(11:11).lt.':' .and. call_2(11:11).gt.'/') unpk77_successvar=.false.
- endif
- if(msg(1:3).ne.'CQ ') then
- if(call_1(1:1).lt.':' .and. call_1(1:1).gt.'/' .and. call_1(2:2).lt.':' .and.call_1(2:2).gt.'/') unpk77_successvar=.false.
- if(len_trim(call_1).eq.11) then
- ispace=index(call_1,' '); if(ispace.gt.0 .and. ispace.lt.12) unpk77_successvar=.false.
- islash=index(call_1,'/'); if(islash.eq.1 .or. islash.eq.2 .or. islash.eq.11 .or. (islash.eq.10 .and. &
- call_1(11:11).gt.'@' .and. call_1(11:11).lt.'[' .and. call_1(11:11).ne.'P')) unpk77_successvar=.false.
- if(islash.lt.6 .and. call_1(11:11).lt.':' .and. call_1(11:11).gt.'/') unpk77_successvar=.false.
- endif
- endif
- nmsglen=len_trim(msg)
-! protocol violations, also reported at wrong TX message packing
-! prevent broken message transmission
- if(unpk77_successvar .and. nmsglen.gt.0) then
- indxp=index(msg,'/P ')
- if((icq.eq.0 .and. nrpt.eq.0 .and. (indxp.lt.1 .or. indxp.gt.7)) .or. icq.eq.1) then
-! -23 -3.3 N0S/W45ETOE <...>
-!071445 -14 0.1 779 ~ <...>
-!071445 -14 0.1 779 ~ W5JZ ! hash was associated
-! CQ <...>
-! with exception to broken by packing message 'JQ1AHT/P <JL1LOF/1> -15' wrongly being transmitted as type 4 message 'JQ1AHT/P <JL1LOF/1>'
- if(msg(nmsglen:nmsglen).eq.'>') unpk77_successvar=.false.
- endif
+ else if(decoded%n3.gt.6) then
+ decoded%success=.false.
+ endif
+
+ return
+end subroutine unpack77_decode_i3_0
+
+subroutine unpack77_decode_type12(c77,context,decoded)
+ character*77 c77
+ type(unpack77_context), intent(in) :: context
+ type(unpack77_core_result), intent(inout) :: decoded
+ character*13 call_1,call_2
+ character*3 crpt
+ character*4 grid4
+ logical unpk28_success,unpkg4_success,ok
+ type(pack77_type12_fields) :: type12_fields
+ integer :: n28a,n28b
+ ! Type 1 (standard message) or Type 2 ("/P" form for EU VHF contest)
+ if(decoded%i3.eq.1) then
+ call decode_pack77_type1(c77,type12_fields,ok,.true.)
+ else
+ call decode_pack77_type2(c77,type12_fields,ok,.true.)
+ endif
+ if(.not.ok) then
+ decoded%success=.false.
+ return
+ endif
+ n28a=type12_fields%n28a
+ n28b=type12_fields%n28b
+ ipa=type12_fields%ipa
+ ipb=type12_fields%ipb
+ ir=type12_fields%ir
+ igrid4=type12_fields%igrid4
+ call record_configured_n28_pair(context,n28a,n28b)
+ call unpack28_for_context(context,n28a,call_1,unpk28_success)
+ if(context%nrx.eq.1 .and. context%mycall_set .and. &
+ context%hashmy22.eq.(n28a-PACK77_NTOKENS)) then
+ call_1='<'//trim(context%mycall)//'>'
+ unpk28_success=.true.
+ endif
+ if(.not.unpk28_success) decoded%success=.false.
+ call unpack28_for_context(context,n28b,call_2,unpk28_success)
+ if(.not.unpk28_success) decoded%success=.false.
+ if(call_1(1:3).eq.'CQ_') call_1(3:3)=' '
+ if(index(call_1,'<').le.0) then
+ i=index(call_1,' ')
+ if(i.ge.4 .and. ipa.eq.1 .and. decoded%i3.eq.1) call_1(i:i+1)='/R'
+ if(i.ge.4 .and. ipa.eq.1 .and. decoded%i3.eq.2) call_1(i:i+1)='/P'
+ if(i.ge.4) then
+ call stage_unpack_recent_call(decoded%effects,call_1)
+ if(context%configured) call stage_unpack_hash_call(decoded%effects,call_1)
endif
-! <...> /BZZ/0ZZ/C
-! <...> ZZZZ/0Z/Z/
-! <...> OZZZZ/0ZZZ/
-! <...> 0I/IZZZ/O K
-! <...> J/IZZZ/O K
- if(unpk77_successvar .and. iflip.eq.0 .and. icq.eq.0 .and. nrpt.eq.0) then
- nlencall2=len_trim(call_2)
- if(nlencall2.gt.9) then
- if(call_2(1:1).eq.'/' .or. call_2(nlencall2:nlencall2).eq.'/') unpk77_successvar=.false.
- nindxspace=index(call_2,' ')
- if(nindxspace.gt.0 .and. nindxspace.lt.nlencall2) unpk77_successvar=.false.
- endif
+ endif
+ if(index(call_2,'<').le.0) then
+ i=index(call_2,' ')
+ if(i.ge.4 .and. ipb.eq.1 .and. decoded%i3.eq.1) call_2(i:i+1)='/R'
+ if(i.ge.4 .and. ipb.eq.1 .and. decoded%i3.eq.2) call_2(i:i+1)='/P'
+ if(i.ge.4) then
+ call stage_unpack_recent_call(decoded%effects,call_2)
+ call stage_unpack_hash_call(decoded%effects,call_2)
endif
+ endif
+ if(igrid4.le.PACK77_MAXGRID4) then
+ call to_grid4(igrid4,grid4,unpkg4_success)
+ if(.not.unpkg4_success) decoded%success=.false.
+ decoded%msg=pack77_format_exchange_message(call_1,call_2,ir,grid4,.true.)
+ if(decoded%msg(1:3).eq.'CQ ' .and. ir.eq.1) decoded%success=.false.
+ if(context%strict_var_guards .and. .not.unpack77_type12_var_guard_ok( &
+ call_1,call_2,grid4,ir)) decoded%success=.false.
+ else
+ irpt=igrid4-PACK77_MAXGRID4
+ if(irpt.ge.1 .and. irpt.le.4) &
+ decoded%msg=pack77_format_qso_tail(call_1,call_2, &
+ pack77_tail_from_type12_irpt(irpt))
+ if(irpt.ge.5) then
+ crpt=pack77_format_snr_report(pack77_snr_from_report_index(irpt))
+ decoded%msg=pack77_format_exchange_message(call_1,call_2,ir,crpt,.false.)
+ endif
+ if(decoded%msg(1:3).eq.'CQ ' .and. irpt.ge.2) decoded%success=.false.
+ endif
+
+ return
+end subroutine unpack77_decode_type12
- else if(i3.eq.5) then
-
-! Type 5 <PA3XYZ> <G4ABC/P> R 590003 IO91NP h12 h22 r1 s3 S11 g25
-! EU VHF contest
- read(c77,1060) n12,n22,ir,irpt,iserial,igrid6
-1060 format(b12,b22,b1,b3,b11,b25)
- if(igrid6.lt.0 .or. igrid6.gt.18662399) then
- unpk77_successvar=.false.
+subroutine unpack77_decode_type3(c77,context,decoded)
+ character*77 c77
+ type(unpack77_context), intent(in) :: context
+ type(unpack77_core_result), intent(inout) :: decoded
+ character*13 call_1,call_2
+ character*4 exchange
+ character crpt*3
+ logical unpk28_success,ok
+ type(pack77_type3_fields) :: type3_fields
+ integer :: n28a,n28b
+ ! Type 3: ARRL RTTY Contest
+ call decode_pack77_type3(c77,type3_fields,ok,.true.)
+ if(.not.ok) then
+ decoded%success=.false.
+ return
+ endif
+ itu=type3_fields%itu
+ n28a=type3_fields%n28a
+ n28b=type3_fields%n28b
+ ir=type3_fields%ir
+ irpt=type3_fields%irpt
+ nexch=type3_fields%nexch
+ call record_configured_n28_pair(context,n28a,n28b)
+ crpt=pack77_format_rtty_report(irpt)
+ call unpack28_for_context(context,n28a,call_1,unpk28_success)
+ if(.not.unpk28_success) decoded%success=.false.
+ call unpack28_for_context(context,n28b,call_2,unpk28_success)
+ if(.not.unpk28_success) decoded%success=.false.
+ if(nexch.gt.8000 .and. nexch-8000.le.PACK77_NUSCAN) then
+ exchange=pack77_rtty_multiplier_name(nexch-8000)
+ if(.not.pack77_type3_render_fits(itu,ir,call_1,call_2,exchange)) then
+ decoded%success=.false.
return
endif
- call hash12var(n12,call_1,nthr)
- if(call_1.eq.'<...>') then
- call hash12(n12,call_1)
- endif
- if(n12.eq.hashmy12var) call_1='<'//trim(mycall13var)//'>'
- call hash22var(n22,call_2,nthr)
- if(call_2.eq.'<...>') then
- call hash22(n22,call_2)
+ decoded%msg=pack77_format_type3_message(itu,ir,call_1,call_2,crpt, &
+ exchange)
+ else if(nexch.ge.1 .and. nexch.le.7999) then
+ write(exchange,'(i4.4)') nexch
+ if(.not.pack77_type3_render_fits(itu,ir,call_1,call_2,exchange)) then
+ decoded%success=.false.
+ return
endif
- nrs=52+irpt
- write(cexch,1022) nrs,iserial
-1022 format(i2,i4.4)
- call to_grid6var(igrid6,grid6,unpk77_successvar)
- if(ir.eq.0) msg=trim(call_1)//' '//trim(call_2)//' '//cexch//' '//grid6
- if(ir.eq.1) msg=trim(call_1)//' '//trim(call_2)//' R '//cexch//' '//grid6
+ decoded%msg=pack77_format_type3_message(itu,ir,call_1,call_2,crpt,exchange)
+ else
+ decoded%success=.false.
+ endif
- else if(i3.ge.6) then ! i3 values 6 and 7 are not yet defined
- unpk77_successvar=.false.
+ return
+end subroutine unpack77_decode_type3
+
+subroutine unpack77_decode_type4(c77,context,decoded)
+ character*77 c77
+ type(unpack77_context), intent(in) :: context
+ type(unpack77_core_result), intent(inout) :: decoded
+ character*13 call_1,call_2,call_3
+ character*11 c11
+ logical ok
+ type(pack77_type4_fields) :: type4_fields
+ ! Type 4
+ call decode_pack77_type4(c77,type4_fields,ok,.true.)
+ if(.not.ok) then
+ decoded%success=.false.
+ return
endif
- if(msg(1:4).eq.'CQ <') unpk77_successvar=.false.
+ n12=type4_fields%n12
+ c11=pack77_type4_call_text_from_n58(type4_fields%n58)
+ iflip=type4_fields%iflip
+ nrpt=type4_fields%nrpt
+ icq=type4_fields%icq
+ call hash12(n12,call_3)
+ if(iflip.eq.0) then ! 12 bit hash for TO call
+ call_1=call_3
+ call_2=adjustl(c11)//' '
+ call stage_unpack_recent_call(decoded%effects,call_2)
+ call stage_unpack_hash_call(decoded%effects,call_2)
+ if(context%nrx.eq.1 .and. context%dxcall_set .and. &
+ context%mycall_set .and. call_2.eq.context%dxcall .and. &
+ n12.eq.context%hashmy12) call_1='<'//trim(context%mycall)//'>'
+ if(context%nrx.eq.1 .and. context%mycall_set .and. &
+ index(call_1,'<...>').gt.0 .and. &
+ n12.eq.context%hashmy12) call_1='<'//trim(context%mycall)//'>'
+ else ! 12 bit hash for DE call
+ call_1=adjustl(c11)
+ call_2=call_3
+ call stage_unpack_recent_call(decoded%effects,call_1)
+ if(context%configured) call stage_unpack_hash_call(decoded%effects,call_1)
+ if(context%nrx.eq.0 .and. context%mycall_set .and. &
+ n12.eq.context%hashmy12) call_2='<'//trim(context%mycall)//'>'
+ endif
+ if(icq.eq.0) then
+ decoded%msg=pack77_format_qso_tail(call_1,call_2, &
+ pack77_tail_from_type4_nrpt(nrpt))
+ else
+ decoded%msg='CQ '//trim(call_2)
+ endif
+ if(context%strict_var_guards .and. .not.unpack77_type4_var_guard_ok( &
+ call_1,call_2,decoded%msg,iflip,icq,nrpt)) decoded%success=.false.
+
return
-end subroutine unpack77var
+end subroutine unpack77_decode_type4
-subroutine pack28var(c13,n28,ntxhash)
+subroutine unpack77_decode_type5(c77,context,decoded)
+ character*77 c77
+ type(unpack77_context), intent(in) :: context
+ type(unpack77_core_result), intent(inout) :: decoded
+ character*13 call_1,call_2
+ character*6 cexch,grid6
+ logical ok
+ type(pack77_type5_fields) :: type5_fields
+ ! Type 5 <PA3XYZ> <G4ABC/P> R 590003 IO91NP h12 h22 r1 s3 S11 g25
+ ! EU VHF contest
+ call decode_pack77_type5(c77,type5_fields,ok,.true.)
+ if(.not.ok) then
+ decoded%success=.false.
+ return
+ endif
+ n12=type5_fields%n12
+ n22=type5_fields%n22
+ ir=type5_fields%ir
+ irpt=type5_fields%irpt
+ iserial=type5_fields%iserial
+ igrid6=type5_fields%igrid6
+ call hash12(n12,call_1)
+ if(n12.eq.context%hashmy12) call_1='<'//trim(context%mycall)//'>'
+ call hash22(n22,call_2)
+ cexch=pack77_format_vhf_exchange(irpt,iserial)
+ call to_grid6(igrid6,grid6,decoded%success)
+ decoded%msg=pack77_format_exchange_message(call_1,call_2,ir,cexch//' '//grid6,.true.)
-! Pack a special token, a 22-bit hash code, or a valid base call into a 28-bit
-! integer.
+ return
+end subroutine unpack77_decode_type5
- parameter (NTOKENS=2063592,MAX22=4194304)
- logical is_digit,is_letter,lhashit
- character*13 c13
- character*6 callsign
- character*1 c
- character*4 c4
- character*37 a1
- character*36 a2
- character*10 a3
- character*27 a4
- integer, intent(in) :: ntxhash
- data a1/' 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'/
- data a2/'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'/
- data a3/'0123456789'/
- data a4/' ABCDEFGHIJKLMNOPQRSTUVWXYZ'/
-
- is_digit(c)=c.ge.'0' .and. c.le.'9'
- is_letter(c)=c.ge.'A' .and. c.le.'Z'
+subroutine stage_unpack_hash_call(effects,c13)
+ type(unpack77_effects), intent(inout) :: effects
+ character(len=*), intent(in) :: c13
- n28=-1
-! Work-around for Swaziland prefix:
- if(c13(1:4).eq.'3DA0') callsign='3D0'//c13(5:7)
-! Work-around for Guinea prefixes:
- if(c13(1:2).eq.'3X' .and. c13(3:3).ge.'A' .and. &
- c13(3:3).le.'Z') callsign='Q'//c13(3:6)
+ call stage_unpack_call(effects%hash_calls,effects%nhash,c13)
-! Check for special tokens first
- if(c13(1:3).eq.'DE ') then
- n28=0
- go to 900
- endif
-
- if(c13(1:4).eq.'QRZ ') then
- n28=1
- go to 900
- endif
+ return
+end subroutine stage_unpack_hash_call
- if(c13(1:3).eq.'CQ ') then
- n28=2
- go to 900
- endif
+subroutine stage_unpack_recent_call(effects,c13)
+ type(unpack77_effects), intent(inout) :: effects
+ character(len=*), intent(in) :: c13
- if(c13(1:3).eq.'CQ_') then
- n=len(trim(c13))
- if(n.ge.4 .and. n.le.7) then
- nlet=0
- nnum=0
- do i=4,n
- c=c13(i:i)
- if(c.ge.'A' .and. c.le.'Z') nlet=nlet+1
- if(c.ge.'0' .and. c.le.'9') nnum=nnum+1
- enddo
- if(nnum.eq.3 .and. nlet.eq.0) then
- read(c13(4:3+nnum),*) nqsy
- n28=3+nqsy
- go to 900
+ call stage_unpack_call(effects%recent_calls,effects%nrecent,c13)
+
+ return
+end subroutine stage_unpack_recent_call
+
+subroutine stage_unpack_call(calls,ncalls,c13)
+ character(len=13), intent(inout) :: calls(:)
+ integer, intent(inout) :: ncalls
+ character(len=*), intent(in) :: c13
+ character(len=13) :: cw
+ logical :: ok
+
+! Keep unpack77_core side-effect free; callers decide whether staged calls are
+! written immediately or queued for fillhashvar.
+ call normalize_hash_call(c13,cw,ok)
+ if(.not.ok) return
+ if(ncalls.ge.size(calls)) return
+ ncalls=ncalls+1
+ calls(ncalls)=cw
+
+ return
+end subroutine stage_unpack_call
+
+subroutine apply_unpack77_effects(effects,policy)
+ type(unpack77_effects), intent(in) :: effects
+ type(unpack77_effect_policy), intent(in) :: policy
+ integer :: i,n10,n12,n22
+
+! Non-configured decodes write directly to shared state. Configured/var decodes
+! queue by RX thread and let fillhashvar merge the successful decode effects.
+ if(policy%record_hashes) then
+ do i=1,effects%nhash
+ if(policy%queue_by_thread) then
+ call queue_hash_call_for_thread(effects%hash_calls(i),policy%nthr_hash)
+ else
+ call save_hash_call(effects%hash_calls(i),n10,n12,n22)
endif
- if(nlet.ge.1 .and. nlet.le.4 .and. nnum.eq.0) then
- c4=c13(4:n)
- c4=adjustr(c4)
- m=0
- do i=1,4
- j=0
- c=c4(i:i)
- if(c.ge.'A' .and. c.le.'Z') j=ichar(c)-ichar('A')+1
- m=27*m + j
- enddo
- n28=3+1000+m
- go to 900
+ enddo
+ endif
+ if(policy%record_recent_calls) then
+ do i=1,effects%nrecent
+ if(policy%queue_by_thread) then
+ call queue_recent_call_for_thread(effects%recent_calls(i), &
+ policy%nthr_recent)
+ else
+ call add_call_to_recent_calls(effects%recent_calls(i))
endif
- endif
+ enddo
endif
- lhashit=.false.; if(ntxhash.eq.1) lhashit=.true.
-! Check for <...> callsign
- if(c13(1:1).eq.'<')then
- call save_hash_txcallvar(c13,n10,n12,n22,lhashit) !Save callsign in hash table
- i2=index(c13,'>')
- c13=c13(2:i2-1)
- n22=ihashcall(c13,22)
- n28=NTOKENS + n22
- go to 900
- endif
+ return
+end subroutine apply_unpack77_effects
-! Check for standard callsign
- iarea=-1
- n=len(trim(c13))
- do i=n,2,-1
- if(is_digit(c13(i:i))) exit
- enddo
- iarea=i !Call-area digit
- npdig=0 !Digits before call area
- nplet=0 !Letters before call area
- do i=1,iarea-1
- if(is_digit(c13(i:i))) npdig=npdig+1
- if(is_letter(c13(i:i))) nplet=nplet+1
- enddo
- nslet=0
- do i=iarea+1,n
- if(is_letter(c13(i:i))) nslet=nslet+1
- enddo
- if(iarea.lt.2 .or. iarea.gt.3 .or. nplet.eq.0 .or. &
- npdig.ge.iarea-1 .or. nslet.gt.3) then
-! Treat this as a nonstandard callsign: compute its 22-bit hash
- call save_hash_txcallvar(c13,n10,n12,n22,lhashit) !Save callsign in hash table
- n22=ihashcall(c13,22)
- n28=NTOKENS + n22
- go to 900
+subroutine unpack28_for_context(context,n28,c13,success)
+ type(unpack77_context), intent(in) :: context
+ integer, intent(in) :: n28
+ character*13 c13
+ logical success
+
+ if(context%configured) then
+ call unpack28_configured(n28,c13,success)
+ else
+ call unpack28(n28,c13,success)
endif
-
- n=len(trim(c13))
-! This is a standard callsign
- call save_hash_txcallvar(c13,n10,n12,n22,lhashit) !Save callsign in hash table
- if(iarea.eq.2) callsign=' '//c13(1:5)
- if(iarea.eq.3) callsign=c13(1:6)
- i1=index(a1,callsign(1:1))-1
- i2=index(a2,callsign(2:2))-1
- i3=index(a3,callsign(3:3))-1
- i4=index(a4,callsign(4:4))-1
- i5=index(a4,callsign(5:5))-1
- i6=index(a4,callsign(6:6))-1
- n28=36*10*27*27*27*i1 + 10*27*27*27*i2 + 27*27*27*i3 + 27*27*i4 + &
- 27*i5 + i6
- n28=n28 + NTOKENS + MAX22
-900 n28=iand(n28,ishft(1,28)-1)
return
-end subroutine pack28var
+end subroutine unpack28_for_context
+subroutine record_configured_n28_pair(context,n28a,n28b)
+ type(unpack77_context), intent(in) :: context
+ integer, intent(in) :: n28a,n28b
-subroutine unpack28var(n28_0,c13,success,nthr)
+ if(.not.context%configured) return
+ n28a_configured=n28a
+ n28b_configured=n28b
- parameter (NTOKENS=2063592,MAX22=4194304)
- logical success
- character*13 c13
- character*37 c1
- character*36 c2
- character*10 c3
- character*27 c4
- integer, intent(in) :: nthr
- data c1/' 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'/
- data c2/'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'/
- data c3/'0123456789'/
- data c4/' ABCDEFGHIJKLMNOPQRSTUVWXYZ'/
+ return
+end subroutine record_configured_n28_pair
- success=.true.
- n28=n28_0
- if(n28.lt.NTOKENS) then
-! Special tokens DE, QRZ, CQ, CQ_nnn, CQ_aaaa
- if(n28.eq.0) c13='DE '
- if(n28.eq.1) c13='QRZ '
- if(n28.eq.2) c13='CQ '
- if(n28.le.2) go to 900
- if(n28.le.1002) then
- write(c13,1002) n28-3
-1002 format('CQ_',i3.3)
- go to 900
- endif
- if(n28.le.532443) then
- n=n28-1003
- n0=n
- i1=n/(27*27*27)
- n=n-27*27*27*i1
- i2=n/(27*27)
- n=n-27*27*i2
- i3=n/27
- i4=n-27*i3
- c13=c4(i1+1:i1+1)//c4(i2+1:i2+1)//c4(i3+1:i3+1)//c4(i4+1:i4+1)
- c13=adjustl(c13)
- c13='CQ_'//c13(1:10)
- go to 900
+logical function unpack77_type12_var_guard_ok(call_1,call_2,grid4,ir) result(ok)
+! Configured decode rejects a few hash-collision renders that parse as valid
+! source messages but cannot round-trip through the configured var encoder.
+ character(len=*), intent(in) :: call_1,call_2,grid4
+ integer, intent(in) :: ir
+ type(pack77_type12_call_source) :: source
+ logical :: source_ok
+
+ ok=.true.
+ if(ir.eq.0 .and. call_1(1:1).eq.'<' .and. grid4.ne.'RR73') then
+ call pack77_parse_type12_call(call_2,.false.,source,source_ok)
+ if(source_ok .and. source%suffix.eq.PACK77_TYPE12_SUFFIX_R) ok=.false.
+ endif
+
+ return
+end function unpack77_type12_var_guard_ok
+
+logical function unpack77_type4_var_guard_ok(call_1,call_2,msg,iflip,icq,nrpt) result(ok)
+! Type 4 can decode arbitrary 58-bit text as plausible calls; configured var
+! mode keeps only renders that also satisfy the source-side Type 4 grammar.
+ character(len=*), intent(in) :: call_1,call_2,msg
+ integer, intent(in) :: iflip,icq,nrpt
+ integer :: nmsglen,indxp,nlencall2,nindxspace
+ type(pack77_type4_source) :: source
+ logical :: source_ok
+
+ ok=.true.
+ call pack77_parse_type4_source(msg,source,source_ok)
+ if(.not.source_ok) ok=.false.
+ if(.not.unpack77_type4_call_guard_ok(call_2)) ok=.false.
+ if(msg(1:3).ne.'CQ ' .and. .not.unpack77_type4_call_guard_ok(call_1)) &
+ ok=.false.
+ nmsglen=len_trim(msg)
+ if(ok .and. nmsglen.gt.0) then
+ indxp=index(msg,'/P ')
+ if((icq.eq.0 .and. nrpt.eq.0 .and. (indxp.lt.1 .or. indxp.gt.7)) .or. &
+ icq.eq.1) then
+ if(msg(nmsglen:nmsglen).eq.'>') ok=.false.
endif
endif
- n28=n28-NTOKENS
- if(n28.lt.MAX22) then
-! This is a 22-bit hash of a callsign
- n22=n28
- call hash22var(n22,c13,nthr) !Retrieve callsign from hash table
- if(c13.eq.'<...>') then
- call hash22(n22,c13)
+ if(ok .and. iflip.eq.0 .and. icq.eq.0 .and. nrpt.eq.0) then
+ nlencall2=len_trim(call_2)
+ if(nlencall2.gt.9) then
+ if(call_2(1:1).eq.'/' .or. call_2(nlencall2:nlencall2).eq.'/') &
+ ok=.false.
+ nindxspace=index(call_2,' ')
+ if(nindxspace.gt.0 .and. nindxspace.lt.nlencall2) ok=.false.
endif
- go to 900
endif
-
-! Standard callsign
- n=n28 - MAX22
- i1=n/(36*10*27*27*27)
- n=n-36*10*27*27*27*i1
- i2=n/(10*27*27*27)
- n=n-10*27*27*27*i2
- i3=n/(27*27*27)
- n=n-27*27*27*i3
- i4=n/(27*27)
- n=n-27*27*i4
- i5=n/27
- i6=n-27*i5
- c13=c1(i1+1:i1+1)//c2(i2+1:i2+1)//c3(i3+1:i3+1)//c4(i4+1:i4+1)// &
- c4(i5+1:i5+1)//c4(i6+1:i6+1)
- c13=adjustl(c13)
-900 i0=index(c13,' ')
+ return
+end function unpack77_type4_var_guard_ok
+
+logical function unpack77_type4_call_guard_ok(call_text) result(ok)
+ character(len=*), intent(in) :: call_text
+ integer :: ispace,islash
+
+ ok=pack77_valid_hash_call_token(call_text) .or. &
+ pack77_valid_type4_c11(call_text)
+ if(.not.ok) return
+ if(pack77_valid_hash_call_token(call_text)) return
+ if(pack77_is_digit_char(call_text(1:1)) .and. &
+ pack77_is_digit_char(call_text(2:2))) ok=.false.
+ if(len_trim(call_text).eq.11) then
+ ispace=index(call_text,' ')
+ if(ispace.gt.0 .and. ispace.lt.12) ok=.false.
+ islash=index(call_text,'/')
+ if(islash.eq.1 .or. islash.eq.2 .or. islash.eq.11 .or. &
+ (islash.eq.10 .and. pack77_is_letter_char(call_text(11:11)) .and. &
+ call_text(11:11).ne.'P')) ok=.false.
+ if(islash.lt.6 .and. pack77_is_digit_char(call_text(11:11))) ok=.false.
+ endif
- if((i0.ne.0 .and. i0.lt.len(trim(c13))) .or. (c13(1:1).lt.':' .and. c13(1:1).gt.'/' .and. &
- c13(2:2).lt.':' .and. c13(2:2).gt.'/')) then
- c13='QU1RK'
- success=.false.
+ return
+end function unpack77_type4_call_guard_ok
+
+subroutine lower_c28_slot(token,allow_auto_hash,n28,hash_facts,ok)
+ character(len=*), intent(in) :: token
+ logical, intent(in) :: allow_auto_hash
+ integer, intent(out) :: n28
+ character*13 cw
+ type(pack77_hash_facts), intent(inout) :: hash_facts
+ type(pack77_hash_facts) :: trial_facts
+ logical, intent(out) :: ok
+
+! Some c28 fields may auto-hash nonstandard calls; stricter fields require an
+! explicit <CALL> hash token so source text cannot choose a different family.
+ ok=.true.
+ n28=-1
+ cw=token
+ if(cw(1:3).eq.'DE ' .or. cw(1:4).eq.'QRZ ' .or. &
+ cw(1:3).eq.'CQ ' .or. cw(1:3).eq.'CQ_') then
+ trial_facts=hash_facts
+ call pack28_core(cw,n28,trial_facts)
+ if(n28.lt.PACK77_NTOKENS) return
+ endif
+
+ cw=token
+ if(pack77_valid_hash_call_token(cw) .or. pack77_c28_standard_shape(cw)) then
+ call pack28_core(cw,n28,hash_facts)
+ return
+ endif
+
+ if(.not.allow_auto_hash) then
+ ok=.false.
+ return
endif
+ call pack28_core(cw,n28,hash_facts)
+
return
-end subroutine unpack28var
+end subroutine lower_c28_slot
-subroutine split77var(msg,nwords,nw,w)
-! Convert msg to upper case; collapse multiple blanks; parse into words.
+integer function pack77_c28_render_len(token) result(n)
+ character(len=*), intent(in) :: token
+ integer :: m
- character*37 msg
- character*13 w(19)
- character*1 c,c0
- character*6 bcall_1
- logical ok1
- integer nw(19)
-
- iz=len(trim(msg))
- j=0
- k=0
- n=0
- c0=' '
- w=' '
- do i=1,iz
- if(ichar(msg(i:i)).eq.0) msg(i:i)=' '
- c=msg(i:i) !Single character
- if(c.eq.' ' .and. c0.eq.' ') cycle !Skip leading/repeated blanks
- if(c.ne.' ' .and. c0.eq.' ') then
- k=k+1 !New word
- n=0
+ m=len_trim(token)
+ n=m
+ if(pack77_valid_hash_call_token(token)) return
+ if(.not.pack77_c28_standard_shape(token)) then
+ if(m.gt.11) then
+ n=-1
+ else
+ n=m+2
endif
- j=j+1 !Index in msg
- n=n+1 !Index in word
- if(c.ge.'a' .and. c.le.'z') c=char(ichar(c)-32) !Force upper case
- msg(j:j)=c
- if(n.le.13) w(k)(n:n)=c !Copy character c into word
- c0=c
- enddo
- iz=j !Message length
- nwords=k !Number of words in msg
- if(nwords.le.0) go to 900
- nw(k)=len(trim(w(k)))
- msg(iz+1:)=' '
- if(nwords.lt.3) go to 900
- call chkcall(w(3),bcall_1,ok1)
- if(ok1 .and. w(1)(1:3).eq.'CQ ') then
- w(1)='CQ_'//w(2)(1:10) !Make "CQ " into "CQ_"
- w(2:12)=w(3:13) !Move all remeining words down by one
- nwords=nwords-1
endif
-
-900 return
-end subroutine split77var
+end function pack77_c28_render_len
-subroutine pack77_01var(nwords,w,i3,n3,c77,ntxhash)
+logical function pack77_dxpedition_render_fits(source) result(ok)
+ type(pack77_dxpedition_source), intent(in) :: source
+ integer :: n,ncall
+
+ ok=.false.
+ n=pack77_c28_render_len(source%call_1)
+ if(n.lt.0) return
+ ncall=pack77_c28_render_len(source%call_2)
+ if(ncall.lt.0) return
+ n=n+1+5+1+ncall+1+len_trim(source%hash_token)+1+3
+ ok=n.le.37
+end function pack77_dxpedition_render_fits
+
+
+logical function pack77_field_day_render_fits(source) result(ok)
+ type(pack77_field_day_source), intent(in) :: source
+ character(len=3) :: section
+ integer :: n,ncall,nexch
+
+ ok=.false.
+ section=pack77_arrl_section_name(source%isec)
+ nexch=2
+ if(source%ntx.ge.10) nexch=3
+ n=pack77_c28_render_len(source%call_1)
+ if(n.lt.0) return
+ ncall=pack77_c28_render_len(source%call_2)
+ if(ncall.lt.0) return
+ n=n+1+ncall+1+nexch+1+len_trim(section)
+ if(source%ir.eq.1) n=n+2
+ ok=n.le.37
+end function pack77_field_day_render_fits
+
+
+subroutine unpack28_configured(n28_0,c13,success)
+ integer, intent(in) :: n28_0
+ character*13 c13
+ logical success
+
+ call unpack28_core(n28_0,c13,success,.true.)
+
+ return
+end subroutine unpack28_configured
+
+type(pack77_candidate) function pack77_01_candidate(msg) result(candidate)
! Pack a Type 0.1 message: DXpedition mode
! Example message: "K1ABC RR73; W9XYZ <KH1/KH7Z> -11" 28 28 10 5
- character*13 w(19),c13
+ character(len=*), intent(in) :: msg
character*77 c77
- character*6 bcall_1,bcall_2
- logical ok1,ok2,lhashit
- integer, intent(in) :: ntxhash
-
- if(nwords.ne.5) go to 900 !Must have 5 words
- if(trim(w(2)).ne.'RR73;') go to 900 !2nd word must be "RR73;"
- if(w(4)(1:1).ne.'<') go to 900 !4th word must have <...>
- if(index(w(4),'>').lt.1) go to 900
- n=-99
- read(w(5),*,err=1) n
-1 if(n.eq.-99) go to 900 !5th word must be a valid report
- n5=(n+30)/2
- if(n5.lt.0) n5=0
- if(n5.gt.31) n5=31
- call chkcall(w(1),bcall_1,ok1)
- if(.not.ok1) go to 900 !1st word must be a valid basecall
- call chkcall(w(3),bcall_2,ok2)
- if(.not.ok2) go to 900 !3rd word must be a valid basecall
+ type(pack77_dxpedition_source) :: source
+ integer :: n28a,n28b
+ logical ok,matched_shape
-! Type 0.1: K1ABC RR73; W9XYZ <KH1/KH7Z> -11 28 28 10 5 71 DXpedition special msg
- i3=0
- n3=1
- call pack28var(w(1),n28avar,ntxhash)
- call pack28var(w(3),n28bvar,ntxhash)
- lhashit=.false.; if(ntxhash.eq.1) lhashit=.true.
- call save_hash_txcallvar(w(4),n10,n12,n22,lhashit)
- i2=index(w(4),'>')
- c13=w(4)(2:i2-1)
- n10=ihashcall(c13,10)
- write(c77,1010) n28avar,n28bvar,n10,n5,n3,i3
-1010 format(2b28.28,b10.10,b5.5,2b3.3)
-
-900 return
-end subroutine pack77_01var
+ candidate%result=pack77_no_match()
+ call pack77_parse_dxpedition_source(msg,source,ok,matched_shape)
+ if(.not.ok) return
+ if(.not.pack77_dxpedition_render_fits(source)) return
-subroutine pack77_03var(nwords,w,i3,n3,c77,ntxhash)
+! Type 0.1: K1ABC RR73; W9XYZ <KH1/KH7Z> -11 28 28 10 5 71 DXpedition special msg
+ call lower_c28_slot(source%call_1,.true.,n28a,candidate%hash_facts,ok)
+ if(.not.ok) return
+ call lower_c28_slot(source%call_2,.true.,n28b,candidate%hash_facts,ok)
+ if(.not.ok) return
+ call pack77_hash_index(candidate%hash_facts,source%hash_token,10,n10,ok)
+ if(.not.ok) return
+ call encode_pack77_dxpedition(n28a,n28b,n10,source%n5,c77,ok)
+ call pack77_accept_candidate_encoded(candidate,0,1,c77,ok)
+end function pack77_01_candidate
+
+type(pack77_candidate) function pack77_03_candidate(msg) result(candidate)
! Check 0.3 and 0.4 (ARRL Field Day exchange)
-! Example message: WA9XYZ KA1ABC R 16A EMA 28 28 1 4 3 7 71
+! Example message: WA9XYZ KA1ABC R 16A EMA 28 28 1 4 3 7 71
- parameter (NSEC=86) !Number of ARRL Sections
- character*13 w(19)
+ character(len=*), intent(in) :: msg
character*77 c77
- character*6 bcall_1,bcall_2
- character*3 csec(NSEC)
- logical ok1,ok2
- integer, intent(in) :: ntxhash
- data csec/ &
- "AB ","AK ","AL ","AR ","AZ ","BC ","CO ","CT ","DE ","EB ", &
- "EMA","ENY","EPA","EWA","GA ","GH ","IA ","ID ","IL ","IN ", &
- "KS ","KY ","LA ","LAX","NS ","MB ","MDC","ME ","MI ","MN ", &
- "MO ","MS ","MT ","NC ","ND ","NE ","NFL","NH ","NL ","NLI", &
- "NM ","NNJ","NNY","TER","NTX","NV ","OH ","OK ","ONE","ONN", &
- "ONS","OR ","ORG","PAC","PR ","QC ","RI ","SB ","SC ","SCV", &
- "SD ","SDG","SF ","SFL","SJV","SK ","SNJ","STX","SV ","TN ", &
- "UT ","VA ","VI ","VT ","WCF","WI ","WMA","WNY","WPA","WTX", &
- "WV ","WWA","WY ","DX ","PE ","NB "/
-
- if(nwords.lt.4 .or. nwords.gt.5) return
- call chkcall(w(1),bcall_1,ok1)
- call chkcall(w(2),bcall_2,ok2)
- if(.not.ok1 .or. .not.ok2) return
- isec=-1
- do i=1,NSEC
- if(csec(i).eq.w(nwords)(1:3)) then
- isec=i
- exit
- endif
- enddo
- if(isec.eq.-1) return
- if(nwords.eq.5 .and. trim(w(3)).ne.'R') return
-
- ntx=-1
- j=len(trim(w(nwords-1)))-1
- read(w(nwords-1)(1:j),*,err=1,end=1) ntx !Number of transmitters
-1 if(ntx.lt.1 .or. ntx.gt.32) return
- nclass=ichar(w(nwords-1)(j+1:j+1))-ichar('A')
-
- m=len(trim(w(nwords))) !Length of section abbreviation
- if(m.lt.2 .or. m.gt.3) return
+ type(pack77_field_day_source) :: source
+ integer :: n28a,n28b
+ logical ok,matched_shape
+
+ candidate%result=pack77_no_match()
+ call pack77_parse_field_day_source(msg,source,ok,matched_shape)
+ if(.not.ok) return
+ if(.not.pack77_field_day_render_fits(source)) return
! 0.3 WA9XYZ KA1ABC R 16A EMA 28 28 1 4 3 7 71 ARRL Field Day
! 0.4 WA9XYZ KA1ABC R 32A EMA 28 28 1 4 3 7 71 ARRL Field Day
-
- i3=0
+
n3=3 !Type 0.3 ARRL Field Day
- intx=ntx-1
+ intx=source%ntx-1
if(intx.ge.16) then
n3=4 !Type 0.4 ARRL Field Day
- intx=ntx-17
+ intx=source%ntx-17
endif
- call pack28var(w(1),n28avar,ntxhash)
- call pack28var(w(2),n28bvar,ntxhash)
- ir=0
- if(w(3)(1:2).eq.'R ') ir=1
- write(c77,1010) n28avar,n28bvar,ir,intx,nclass,isec,n3,i3
-1010 format(2b28.28,b1,b4.4,b3.3,b7.7,2b3.3)
+ call lower_c28_slot(source%call_1,.true.,n28a,candidate%hash_facts,ok)
+ if(.not.ok) return
+ call lower_c28_slot(source%call_2,.true.,n28b,candidate%hash_facts,ok)
+ if(.not.ok) return
+ if(n3.eq.3) then
+ call encode_pack77_field_day_low(n28a,n28b,source%ir,intx, &
+ source%nclass,source%isec,c77,ok)
+ else
+ call encode_pack77_field_day_high(n28a,n28b,source%ir,intx, &
+ source%nclass,source%isec,c77,ok)
+ endif
+ call pack77_accept_candidate_encoded(candidate,0,n3,c77,ok)
return
-end subroutine pack77_03var
+end function pack77_03_candidate
-subroutine pack77_06var(nwords,w,i3,n3,c77,i3_hint,n3_hint,ntxhash)
+type(pack77_candidate) function pack77_06_candidate(msg,prefer_wspr_50bit) result(candidate)
- character*13 w(19)
+ character(len=*), intent(in) :: msg
character*77 c77
- character*6 bcall,grid6
- character*4 grid4
- character*1 c
- character*36 a2
- integer, intent(in) :: ntxhash
- data a2/'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'/,nzzz/46656/
-
- logical is_grid4,is_grid6,is_digit,ok
- is_grid4(grid4)=len(trim(grid4)).eq.4 .and. &
- grid4(1:1).ge.'A' .and. grid4(1:1).le.'R' .and. &
- grid4(2:2).ge.'A' .and. grid4(2:2).le.'R' .and. &
- grid4(3:3).ge.'0' .and. grid4(3:3).le.'9' .and. &
- grid4(4:4).ge.'0' .and. grid4(4:4).le.'9'
-
- is_grid6(grid6)=(len(trim(grid6)).eq.6.or.len(trim(grid6)).eq.4).and. &
- grid6(1:1).ge.'A' .and. grid6(1:1).le.'R' .and. &
- grid6(2:2).ge.'A' .and. grid6(2:2).le.'R' .and. &
- grid6(3:3).ge.'0' .and. grid6(3:3).le.'9' .and. &
- grid6(4:4).ge.'0' .and. grid6(4:4).le.'9' .and. &
- (len(trim(grid6)).eq.4.or. &
- (grid6(5:5).ge.'A' .and. grid6(5:5).le.'X' .and. &
- grid6(6:6).ge.'A' .and. grid6(6:6).le.'X'))
-
- is_digit(c)=c.ge.'0' .and. c.le.'9'
-
- m1=len(trim(w(1)))
- m2=len(trim(w(2)))
- m3=len(trim(w(3)))
- if(nwords.eq.3 .and. m1.ge.3 .and. m1.le.6 .and. m2.eq.4 .and. m3.le.2) then
+ type(pack77_wspr_source) :: source
+ logical, intent(in) :: prefer_wspr_50bit
+ logical ok,matched_shape
+
+ candidate%result=pack77_no_match()
+ call pack77_parse_wspr_source(msg,source,ok,matched_shape)
+ if(.not.ok) return
+
+ if(source%subtype.eq.1) then
! WSPR Type 1
- if(.not.is_grid4(w(2)(1:4))) go to 900
- if(.not.is_digit(w(3)(1:1))) go to 900
- if(m3.eq.2) then
- if(.not.is_digit(w(3)(2:2))) go to 900
- endif
- i3=0
- n3=6
- call pack28var(w(1),n28,ntxhash)
- grid4=w(2)(1:4)
- k1=(ichar(grid4(1:1))-ichar('A'))*18*10*10
- k2=(ichar(grid4(2:2))-ichar('A'))*10*10
- k3=(ichar(grid4(3:3))-ichar('0'))*10
- k4=(ichar(grid4(4:4))-ichar('0'))
- igrid4=k1+k2+k3+k4
- read(w(3),*) idbm
- if(idbm.lt.0) idbm=0
- if(idbm.gt.60) idbm=60
- idbm=nint(0.3*idbm)
- write(c77,1010) n28,igrid4,idbm,0,0,0,n3,i3
-1010 format(b28.28,b15.15,b5.5,2i1,b21.21,2b3.3)
- go to 900
+ call lower_c28_slot(source%call_token,.false.,n28,candidate%hash_facts,ok)
+ if(.not.ok) return
+ igrid4=pack77_grid4_index(source%grid4)
+ call encode_pack77_wspr_type1(n28,igrid4,source%idbm,c77,ok)
+ call pack77_accept_candidate_encoded(candidate,0,6,c77,ok)
+ return
endif
- if(nwords.eq.2 .and. m1.ge.5 .and. m1.le.10 .and. m2.le.2) then
+
+ if(source%subtype.eq.2) then
! WSPR Type 2
- i1=index(w(1),'/')
- if(i1.lt.2 .or. i1.eq.m1) go to 900
- if(.not.is_digit(w(2)(1:1))) go to 900
- if(i1.eq.(m1-3) .and. .not.is_digit(w(1)(m1:m1))) go to 900
- if(m2.eq.2) then
- if(.not.is_digit(w(2)(2:2))) go to 900
- endif
- call chkcall(w(1),bcall,ok)
- if(.not.ok) go to 900
- if(i1.le.4) then
-! We have a prefix
- npfx=index(a2,w(1)(1:1))-1
- if(i1.ge.3) npfx=36*npfx + index(a2,w(1)(2:2))-1
- if(i1.eq.4) npfx=36*npfx + index(a2,w(1)(3:3))-1
- else
-! We have a suffix
- if((m1-i1).eq.1) npfx=index(a2,w(1)(i1+1:i1+1))-1
- if((m1-i1).eq.2) npfx=36*(index(a2,w(1)(i1+1:i1+1))-1) + &
- index(a2,w(1)(i1+2:i1+2))-1
- if((m1-i1).eq.3) then
-! Third character of a suffix must be a digit
- if(.not.is_digit(w(1)(i1+3:i1+3))) go to 900
- npfx=36*10*(index(a2,w(1)(i1+1:i1+1))-1) + &
- 10*(index(a2,w(1)(i1+2:i1+2))-1) + index(a2,w(1)(i1+3:i1+3))-1
- endif
- npfx=npfx + nzzz
- endif
- i3=0
- n3=6
- call pack28var(bcall//' ',n28,ntxhash)
- read(w(2),*) idbm
- if(idbm.lt.0) idbm=0
- if(idbm.gt.60) idbm=60
- idbm=nint(0.3*idbm)
- write(c77,1020) n28,npfx,idbm,1,0,n3,i3
-1020 format(b28.28,b16.16,b5.5,i1,b21.21,2b3.3)
- go to 900
+ call lower_c28_slot(source%base_call//' ',.false.,n28, &
+ candidate%hash_facts,ok)
+ if(.not.ok) return
+ call encode_pack77_wspr_type2(n28,source%npfx,source%idbm,c77,ok)
+ call pack77_accept_candidate_encoded(candidate,0,6,c77,ok)
+ return
endif
- if(i3_hint.eq.0.and.n3_hint.eq.6.and.nwords.eq.2 .and. m1.ge.5 &
- .and. m1.le.12 .and. m2.le.6) then
+ if(source%subtype.eq.3 .and. prefer_wspr_50bit) then
! WSPR Type 3
- !n3_hint=6 and i3_hint=0 is a hint that the caller wanted a
- !50-bit encoding rather than the possible alternative n3=4 77-bit
- !encoding
- if(index(w(1),'<').lt.1 .or. index(w(1),'>').lt.1) go to 900
- grid6=w(2)(1:6)
- if(.not.is_grid6(grid6)) go to 900
- i3=0
- n3=6
- call pack28var(w(1),n28,ntxhash)
- n22=n28-2063592
- k1=(ichar(grid6(1:1))-ichar('A'))*18*10*10*25*25
- k2=(ichar(grid6(2:2))-ichar('A'))*10*10*25*25
- k3=(ichar(grid6(3:3))-ichar('0'))*10*25*25
- k4=(ichar(grid6(4:4))-ichar('0'))*25*25
- if (grid6(5:6).eq.' ') then
- igrid6=k1+k2+k3+k4+24*25+24
- else
- k5=(ichar(grid6(5:5))-ichar('A'))*25
- k6=(ichar(grid6(6:6))-ichar('A'))
- igrid6=k1+k2+k3+k4+k5+k6
- endif
- write(c77,1030) n22,igrid6,2,0,n3,i3
-1030 format(b22.22,b25.25,b3.3,b21.21,2b3.3)
+ ! n3=6 and i3=0 are an advisory preference for the caller's
+ ! 50-bit encoding over the possible alternative n3=4 77-bit
+ ! encoding.
+ call pack77_hash_index(candidate%hash_facts,source%hash_token,22,n22,ok)
+ if(.not.ok) return
+ igrid6=pack77_grid6_wspr_index(source%grid6)
+ call encode_pack77_wspr_type3(n22,igrid6,c77,ok)
+ call pack77_accept_candidate_encoded(candidate,0,6,c77,ok)
endif
+end function pack77_06_candidate
-900 return
-end subroutine pack77_06var
+type(pack77_candidate) function pack77_1_candidate(msg) result(candidate)
-subroutine pack77_1var(nwords,w,i3,n3,c77,ntxhash)
+! Type 1/2 source grammar lowers only exact c28 call-slot forms.
-! Check Type 1 (Standard 77-bit message) and Type 2 (ditto, with a "/P" call)
-! Example message: WA9XYZ/R KA1ABC/R R FN42 28 1 28 1 1 15 74
-
- parameter (MAXGRID4=32400)
- character*13 w(19),c13
+ character(len=*), intent(in) :: msg
character*77 c77
- character*6 bcall_1,bcall_2
- character*4 grid4
- character c1*1,c2*2
- logical is_grid4
- logical ok1,ok2
- integer, intent(in) :: ntxhash
- is_grid4(grid4)=len(trim(grid4)).eq.4 .and. &
- grid4(1:1).ge.'A' .and. grid4(1:1).le.'R' .and. &
- grid4(2:2).ge.'A' .and. grid4(2:2).le.'R' .and. &
- grid4(3:3).ge.'0' .and. grid4(3:3).le.'9' .and. &
- grid4(4:4).ge.'0' .and. grid4(4:4).le.'9'
-
- if(nwords.lt.2 .or. nwords.gt.4) return
- call chkcall(w(1),bcall_1,ok1)
- call chkcall(w(2),bcall_2,ok2)
- if(w(1)(1:3).eq.'DE ' .or. w(1)(1:3).eq.'CQ_' .or. w(1)(1:3).eq.'CQ ' .or. &
- w(1)(1:4).eq.'QRZ ') ok1=.true.
- if(w(1)(1:1).eq.'<' .and. index(w(1),'>').ge.5) ok1=.true.
- if(w(2)(1:1).eq.'<' .and. index(w(2),'>').ge.5) ok2=.true.
- if(.not.ok1 .or. .not.ok2) return
- if(w(1)(1:1).eq.'<' .and. index(w(2),'/').gt.0) return
- if(w(2)(1:1).eq.'<' .and. index(w(1),'/').gt.0) return
- if(nwords.eq.2 .and. (.not.ok2 .or. index(w(2),'/').ge.2)) return
- if(nwords.eq.2) go to 10
-
- c1=w(nwords)(1:1)
- c2=w(nwords)(1:2)
- if(.not.is_grid4(w(nwords)(1:4)) .and. c1.ne.'+' .and. c1.ne.'-' &
- .and. c2.ne.'R+' .and. c2.ne.'R-' .and. trim(w(nwords)).ne.'RRR' .and. &
- trim(w(nwords)).ne.'RR73' .and. trim(w(nwords)).ne.'73') return
- if(c1.eq.'+' .or. c1.eq.'-') then
- ir=0
- read(w(nwords),*,err=900) irpt
- if(irpt.ge.-50 .and. irpt.le.-31) irpt=irpt+101
- irpt=irpt+35
- else if(c2.eq.'R+' .or. c2.eq.'R-') then
- ir=1
- read(w(nwords)(2:),*,err=900) irpt
- if(irpt.ge.-50 .and. irpt.le.-31) irpt=irpt+101
- irpt=irpt+35
- else if(trim(w(nwords)).eq.'RRR') then
- ir=0
- irpt=2
- else if(trim(w(nwords)).eq.'RR73') then
- ir=0
- irpt=3
- else if(trim(w(nwords)).eq.'73') then
- ir=0
- irpt=4
- endif
-
-! 1 WA9XYZ/R KA1ABC/R R FN42 28 1 28 1 1 15 74 Standard msg
-! 2 PA3XYZ/P GM4ABC/P R JO22 28 1 28 1 1 15 74 EU VHF contest
-
-10 i1psuffix=index(w(1)//' ' ,'/P ')
- i2psuffix=index(w(2)//' ','/P ')
- if(nwords.eq.2 .or. nwords.eq.3 .or. (nwords.eq.4 .and. &
- w(3)(1:2).eq.'R ')) then
- n3=0
- i3=1 !Type 1: Standard message, possibly with "/R"
- if (i1psuffix.ge.4.or.i2psuffix.ge.4) i3=2 !Type 2, with "/P"
- endif
- c13=bcall_1
- if(c13(1:3).eq.'CQ_' .or. w(1)(1:1).eq.'<') c13=w(1)
- call pack28var(c13,n28avar,ntxhash)
- c13=bcall_2
- if(w(2)(1:1).eq.'<') c13=w(2)
- call pack28var(c13,n28bvar,ntxhash)
+ type(pack77_type12_source) :: source
+ integer :: n28a,n28b
+ logical ok
+
+ candidate%result=pack77_no_match()
+ call pack77_parse_type12_source(msg,source,ok)
+ if(.not.ok) return
+
+ call lower_c28_slot(source%call_1%c28_token,.false.,n28a, &
+ candidate%hash_facts,ok)
+ if(.not.ok) return
+ call lower_c28_slot(source%call_2%c28_token,.false.,n28b, &
+ candidate%hash_facts,ok)
+ if(.not.ok) return
+
ipa=0
ipb=0
- if(i1psuffix.ge.4.or.index(w(1)//' ','/R ').ge.4) ipa=1
- if(i2psuffix.ge.4.or.index(w(2)//' ','/R ').ge.4) ipb=1
-
- grid4=w(nwords)(1:4)
- if(is_grid4(grid4)) then
- ir=0
- if(w(3).eq.'R ') ir=1
- j1=(ichar(grid4(1:1))-ichar('A'))*18*10*10
- j2=(ichar(grid4(2:2))-ichar('A'))*10*10
- j3=(ichar(grid4(3:3))-ichar('0'))*10
- j4=(ichar(grid4(4:4))-ichar('0'))
- igrid4=j1+j2+j3+j4
+ if(pack77_type12_call_has_suffix(source%call_1)) ipa=1
+ if(pack77_type12_call_has_suffix(source%call_2)) ipb=1
+
+ if(source%i3.eq.1) then
+ call encode_pack77_type1(n28a,ipa,n28b,ipb, &
+ source%ir,source%igrid4,c77,ok)
else
- igrid4=MAXGRID4 + irpt
+ call encode_pack77_type2(n28a,ipa,n28b,ipb, &
+ source%ir,source%igrid4,c77,ok)
endif
- if(nwords.eq.2) then
- ir=0
- irpt=1
- igrid4=MAXGRID4+irpt
- endif
- write(c77,1000) n28avar,ipa,n28bvar,ipb,ir,igrid4,i3
-1000 format(2(b28.28,b1),b1,b15.15,b3.3)
- return
-
-900 return
-end subroutine pack77_1var
+ call pack77_accept_candidate_encoded(candidate,source%i3,0,c77,ok)
+end function pack77_1_candidate
-subroutine pack77_3var(nwords,w,i3,n3,c77,ntxhash)
+type(pack77_candidate) function pack77_3_candidate(msg) result(candidate)
! Check Type 3 (ARRL RTTY contest exchange)
!ARRL RTTY - US/Can: rpt state/prov R 579 MA
! - DX: rpt serial R 559 0013
! Example message: TU; W9XYZ K1ABC R 579 MA 1 28 28 1 3 13 74
- parameter (NUSCAN=171) !Number of US states and Canadian provinces/territories
- character*13 w(19)
+ character(len=*), intent(in) :: msg
character*77 c77
- character*6 bcall_1,bcall_2
- character*3 cmult(NUSCAN),mult
- character crpt*3
- integer, intent(in) :: ntxhash
- logical ok1,ok2
- data cmult/ &
- "AL ","AK ","AZ ","AR ","CA ","CO ","CT ","DE ","FL ","GA ", &
- "HI ","ID ","IL ","IN ","IA ","KS ","KY ","LA ","ME ","MD ", &
- "MA ","MI ","MN ","MS ","MO ","MT ","NE ","NV ","NH ","NJ ", &
- "NM ","NY ","NC ","ND ","OH ","OK ","OR ","PA ","RI ","SC ", &
- "SD ","TN ","TX ","UT ","VT ","VA ","WA ","WV ","WI ","WY ", &
- "NB ","NS ","QC ","ON ","MB ","SK ","AB ","BC ","NWT","NF ", &
- "LB ","NU ","YT ","PEI","DC ","DR ","FR ","GD ","GR ","OV ", &
- "ZH ","ZL ","X01","X02","X03","X04","X05","X06","X07","X08", &
- "X09","X10","X11","X12","X13","X14","X15","X16","X17","X18", &
- "X19","X20","X21","X22","X23","X24","X25","X26","X27","X28", &
- "X29","X30","X31","X32","X33","X34","X35","X36","X37","X38", &
- "X39","X40","X41","X42","X43","X44","X45","X46","X47","X48", &
- "X49","X50","X51","X52","X53","X54","X55","X56","X57","X58", &
- "X59","X60","X61","X62","X63","X64","X65","X66","X67","X68", &
- "X69","X70","X71","X72","X73","X74","X75","X76","X77","X78", &
- "X79","X80","X81","X82","X83","X84","X85","X86","X87","X88", &
- "X89","X90","X91","X92","X93","X94","X95","X96","X97","X98", &
- "X99"/
-
- if(w(1)(1:1).eq.'<' .and. w(2)(1:1).eq.'<') go to 900
- if(nwords.eq.4 .or. nwords.eq.5 .or. nwords.eq.6) then
- i1=1
- if(trim(w(1)).eq.'TU;') i1=2
- call chkcall(w(i1),bcall_1,ok1)
- call chkcall(w(i1+1),bcall_2,ok2)
- if(.not.ok1 .or. .not.ok2) go to 900
- crpt=w(nwords-1)(1:3)
- if(index(crpt,'-').ge.1 .or. index(crpt,'+').ge.1) go to 900
- if(crpt(1:1).eq.'5' .and. crpt(2:2).ge.'2' .and. crpt(2:2).le.'9' .and. &
- crpt(3:3).eq.'9') then
- nserial=0
- read(w(nwords),*,err=1) nserial
- endif
-1 mult=' '
- imult=-1
- do i=1,NUSCAN
- if(cmult(i).eq.w(nwords)) then
- imult=i
- mult=cmult(i)
- exit
- endif
- enddo
- nexch=0
- if(nserial.gt.0) nexch=nserial
- if(imult.gt.0) nexch=8000+imult
- if(mult.ne.' ' .or. nserial.gt.0) then
- i3=3
- n3=0
- itu=0
- if(trim(w(1)).eq.'TU;') itu=1
- call pack28var(w(1+itu),n28avar,ntxhash)
- call pack28var(w(2+itu),n28bvar,ntxhash)
- ir=0
- if(w(3+itu)(1:2).eq.'R ') ir=1
- read(w(3+itu+ir),*,err=900) irpt
- irpt=(irpt-509)/10 - 2
- if(irpt.lt.0) irpt=0
- if(irpt.gt.7) irpt=7
+ character*4 exchange
+ type(pack77_type3_source) :: source
+ integer :: n28a,n28b
+ logical ok,matched_shape
+
+ candidate%result=pack77_no_match()
+ call pack77_parse_type3_source(msg,source,ok,matched_shape)
+ if(.not.ok) return
+
+ call lower_c28_slot(source%call_1,.true.,n28a,candidate%hash_facts,ok)
+ if(.not.ok) return
+ call lower_c28_slot(source%call_2,.true.,n28b,candidate%hash_facts,ok)
+ if(.not.ok) return
+ exchange=' '
+ if(source%nexch.gt.0 .and. source%nexch.lt.8000) &
+ write(exchange,'(i4.4)') source%nexch
+ if(source%nexch.gt.8000) &
+ exchange=pack77_rtty_multiplier_name(source%nexch-8000)
+ if(.not.pack77_type3_display_fits(source%itu,source%ir,n28a, &
+ n28b,source%call_1,source%call_2,exchange)) return
! 3 TU; W9XYZ K1ABC R 579 MA 1 28 28 1 3 13 74 ARRL RTTY contest
! 3 TU; W9XYZ G8ABC R 559 0013 1 28 28 1 3 13 74 ARRL RTTY (DX)
- write(c77,1010) itu,n28avar,n28bvar,ir,irpt,nexch,i3
-1010 format(b1,2b28.28,b1,b3.3,b13.13,b3.3)
- endif
- endif
-
-900 return
-end subroutine pack77_3var
+ call encode_pack77_type3(source%itu,n28a,n28b,source%ir,source%irpt, &
+ source%nexch,c77,ok)
+ call pack77_accept_candidate_encoded(candidate,3,0,c77,ok)
+end function pack77_3_candidate
-subroutine pack77_4var(nwords,w,i3,n3,c77,ntxhash)
+type(pack77_candidate) function pack77_4_candidate(msg) result(candidate)
! Check Type 4 (One nonstandard call and one hashed call)
! Example message: <WA9XYZ> PJ4/KA1ABC RR73 12 58 1 2 1 74
+ character(len=*), intent(in) :: msg
integer*8 n58
- logical ok1,ok2,lhashit
- character*13 w(19)
character*77 c77
- character*13 call_1,call_2
character*11 c11
- character*6 bcall_1,bcall_2
- character*38 c
- integer, intent(in) :: ntxhash
- data c/' 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ/'/
-
- iflip=0
- i3=-1
- if(nwords.eq.2 .or. nwords.eq.3) then
- call_1=w(1)
- if(call_1(1:1).eq.'<') call_1=w(1)(2:len(trim(w(1)))-1)
- call_2=w(2)
- if(call_2(1:1).eq.'<') call_2=w(2)(2:len(trim(w(2)))-1)
- call chkcall(call_1,bcall_1,ok1)
- call chkcall(call_2,bcall_2,ok2)
- if(call_1.eq.bcall_1 .and. call_2.eq.bcall_2 .and. ok1 .and. ok2) go to 900
- icq=0
- if(trim(w(1)).eq.'CQ' .or. (ok1.and.ok2)) then
- if(trim(w(1)).eq.'CQ' .and. len(trim(w(2))).le.4) go to 900
- i3=4
- n3=0
- if(trim(w(1)).eq.'CQ') icq=1
- endif
+ character*13 hash_token
+ type(pack77_type4_source) :: source
+ logical ok
- lhashit=.false.; if(ntxhash.eq.1) lhashit=.true.
- if(icq.eq.1) then
- iflip=0
- n12=0
- c11=adjustr(call_2(1:11))
- call save_hash_txcallvar(w(2),n10,n12,n22,lhashit)
- else if(w(1)(1:1).eq.'<') then
- iflip=0
- i3=4
- call save_hash_txcallvar(w(1),n10,n12,n22,lhashit)
- c11=adjustr(call_2(1:11))
- else if(w(2)(1:1).eq.'<') then
- iflip=1
- i3=4
- call save_hash_txcallvar(w(2),n10,n12,n22,lhashit)
- c11=adjustr(call_1(1:11))
- endif
- n58=0
- do i=1,11
- n58=n58*38 + index(c,c11(i:i)) - 1
- enddo
- nrpt=0
- if(trim(w(3)).eq.'RRR') nrpt=1
- if(trim(w(3)).eq.'RR73') nrpt=2
- if(trim(w(3)).eq.'73') nrpt=3
- if(icq.eq.1) then
- iflip=0
- nrpt=0
- endif
- write(c77,1010) n12,n58,iflip,nrpt,icq,i3
-1010 format(b12.12,b58.58,b1,b2.2,b1,b3.3)
- do i=1,77
- if(c77(i:i).eq.'*') c77(i:i)='0' !### Clean up any illegal chars ###
- enddo
- endif
+ candidate%result=pack77_no_match()
+ call pack77_parse_type4_source(msg,source,ok)
+ if(.not.ok) return
-900 return
-end subroutine pack77_4var
+ hash_token=source%hash_token
+ if(source%icq.eq.1 .and. len_trim(hash_token).eq.0) hash_token=source%c11
+ call pack77_hash_index(candidate%hash_facts,hash_token,12,n12,ok)
+ if(.not.ok) return
+ c11=adjustr(source%c11)
+ n58=pack77_type4_n58_from_call_text(c11)
+ nrpt=pack77_type4_nrpt_from_tail(source%itail)
+ if(source%icq.eq.1) nrpt=0
+ call encode_pack77_type4(n12,n58,source%iflip,nrpt,source%icq,c77,ok)
+ call pack77_accept_candidate_encoded(candidate,4,0,c77,ok)
+end function pack77_4_candidate
-subroutine pack77_5var(nwords,w,i3,n3,c77,ntxhash)
+type(pack77_candidate) function pack77_5_candidate(msg) result(candidate)
! Pack a Type 0.2 message: EU VHF Contest mode
! Example message: PA3XYZ/P R 590003 IO91NP 28 1 1 3 12 25
! <PA3XYZ> <G4ABC/P> R 590003 IO91NP h10 h20 r1 s3 s12 g25
- character*13 w(19),c13
+ character(len=*), intent(in) :: msg
character*77 c77
- character*6 grid6
- logical is_grid6,lhashit
- integer, intent(in) :: ntxhash
-
- is_grid6(grid6)=len(trim(grid6)).eq.6 .and. &
- grid6(1:1).ge.'A' .and. grid6(1:1).le.'R' .and. &
- grid6(2:2).ge.'A' .and. grid6(2:2).le.'R' .and. &
- grid6(3:3).ge.'0' .and. grid6(3:3).le.'9' .and. &
- grid6(4:4).ge.'0' .and. grid6(4:4).le.'9' .and. &
- grid6(5:5).ge.'A' .and. grid6(5:5).le.'X' .and. &
- grid6(6:6).ge.'A' .and. grid6(6:6).le.'X'
-
- if(nwords.lt.4 .or. nwords.gt.5) return !nwords must be 4 or 5
- if(w(1)(1:1).ne.'<' .or. w(2)(1:1).ne.'<') return !Both calls must be hashed
- nx=-1
- read(w(nwords-1),*,err=2) nx
-2 if(nx.lt.520001 .or. nx.gt.594095) return !Exchange between 520001 - 594095
- if(.not.is_grid6(w(nwords)(1:6))) return !Last word must be a valid grid6
-
-! Type 0.2: <PA3XYZ> <G4ABC/P> R 590003 IO91NP h10 h20 r1 s3 s12 g25
-
- i3=5
- n3=0
-
- lhashit=.false.; if(ntxhash.eq.1) lhashit=.true.
- call save_hash_txcallvar(w(1),n10,n12,n22,lhashit)
- i2=index(w(1),'>')
- c13=w(1)(2:i2-1)
- n12=ihashcall(c13,12)
-
- call save_hash_txcallvar(w(2),n10a,n12a,n22,lhashit)
- i2=index(w(2),'>')
- c13=w(2)(2:i2-1)
- n22=ihashcall(c13,22)
-
- ir=0
- if(w(3)(1:2).eq.'R ') ir=1
- irpt=nx/10000 - 52
- iserial=mod(nx,10000)
- if(iserial.gt.2047) iserial=2047
- grid6=w(nwords)(1:6)
- j1=(ichar(grid6(1:1))-ichar('A'))*18*10*10*24*24
- j2=(ichar(grid6(2:2))-ichar('A'))*10*10*24*24
- j3=(ichar(grid6(3:3))-ichar('0'))*10*24*24
- j4=(ichar(grid6(4:4))-ichar('0'))*24*24
- j5=(ichar(grid6(5:5))-ichar('A'))*24
- j6=(ichar(grid6(6:6))-ichar('A'))
- igrid6=j1+j2+j3+j4+j5+j6
- write(c77,1010) n12,n22,ir,irpt,iserial,igrid6,i3
-1010 format(b12.12,b22.22,b1,b3.3,b11.11,b25.25,b3.3)
-
- return
-end subroutine pack77_5var
-
-subroutine packtext77var(c13,c71)
-
- character*13 c13,w
- character*71 c71
- character*42 c
- character*1 qa(10),qb(10)
- data c/' 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ+-./?'/
-
- call mp_short_init
- qa=char(0)
- w=adjustr(c13)
- do i=1,13
- j=index(c,w(i:i))-1
- if(j.lt.0) j=0
- call mp_short_mult(qb,qa(2:10),9,42) !qb(1:9)=42*qa(2:9)
- call mp_short_add(qa,qb(2:10),9,j) !qa(1:9)=qb(2:9)+j
- enddo
-
- write(c71,1010) qa(2:10)
-1010 format(b7.7,8b8.8)
-
- return
-end subroutine packtext77var
-
-subroutine unpacktext77var(c71,c13)
-
- integer*1 ia(10)
- character*1 qa(10),qb(10)
- character*13 c13
- character*71 c71
- character*42 c
- equivalence (qa,ia),(qb,ib)
- data c/' 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ+-./?'/
-
- qa(1)=char(0)
- read(c71,1010) qa(2:10)
-1010 format(b7.7,8b8.8)
-
- do i=13,1,-1
- call mp_short_div(qb,qa(2:10),9,42,ir)
- c13(i:i)=c(ir+1:ir+1)
- qa(2:10)=qb(1:9)
- enddo
+ type(pack77_type5_source) :: source
+ logical ok,matched_shape
- return
-end subroutine unpacktext77var
+ candidate%result=pack77_no_match()
+ call pack77_parse_type5_source(msg,source,ok,matched_shape)
+ if(.not.ok) return
-subroutine add_call_to_recent_callsvar(callsign,nthr)
+! Type 0.2: <PA3XYZ> <G4ABC/P> R 590003 IO91NP h10 h20 r1 s3 s12 g25
- character*13 callsign
- logical ladd
- integer, intent(in) :: nthr
+ call pack77_hash_index(candidate%hash_facts,source%hash_token_1,12,n12,ok)
+ if(.not.ok) return
+ call pack77_hash_index(candidate%hash_facts,source%hash_token_2,22,n22,ok)
+ if(.not.ok) return
-! only add if the callsign is not already on the list
- ladd=.true.
- do i=1,MAXRECENT-1 ! if callsign is at the end of the list add it again
- if(recent_callsvar(i).eq.callsign) ladd=.false.
- enddo
-
- if(ladd) then
- do i=MAXRECENT,2,-1
- recent_callsvar(i)=recent_callsvar(i-1)
- enddo
- recent_callsvar(1)=callsign
- endif
-
-! Make sure that callsign is hashed
- call save_hash_callvar(callsign,nthr)
+ igrid6=pack77_grid6_index(source%grid6)
+ call encode_pack77_type5(n12,n22,source%ir,source%irpt,source%iserial, &
+ igrid6,c77,ok)
+ call pack77_accept_candidate_encoded(candidate,5,0,c77,ok)
return
-end subroutine add_call_to_recent_callsvar
-
-subroutine to_grid4var(n,grid4,ok)
- character*4 grid4
- logical ok
-
- ok=.false.
- j1=n/(18*10*10)
- if (j1.lt.0.or.j1.gt.17) goto 900
- n=n-j1*18*10*10
- j2=n/(10*10)
- if (j2.lt.0.or.j2.gt.17) goto 900
- n=n-j2*10*10
- j3=n/10
- if (j3.lt.0.or.j3.gt.9) goto 900
- j4=n-j3*10
- if (j4.lt.0.or.j4.gt.9) goto 900
- grid4(1:1)=char(j1+ichar('A'))
- grid4(2:2)=char(j2+ichar('A'))
- grid4(3:3)=char(j3+ichar('0'))
- grid4(4:4)=char(j4+ichar('0'))
- ok=.true.
-
-900 return
-end subroutine to_grid4var
-
-subroutine to_grid6var(n,grid6,ok)
- character*6 grid6
- logical ok
-
- ok=.false.
- j1=n/(18*10*10*24*24)
- if (j1.lt.0.or.j1.gt.17) goto 900
- n=n-j1*18*10*10*24*24
- j2=n/(10*10*24*24)
- if (j2.lt.0.or.j2.gt.17) goto 900
- n=n-j2*10*10*24*24
- j3=n/(10*24*24)
- if (j3.lt.0.or.j3.gt.9) goto 900
- n=n-j3*10*24*24
- j4=n/(24*24)
- if (j4.lt.0.or.j4.gt.9) goto 900
- n=n-j4*24*24
- j5=n/24
- if (j5.lt.0.or.j5.gt.23) goto 900
- j6=n-j5*24
- if (j6.lt.0.or.j6.gt.23) goto 900
- grid6(1:1)=char(j1+ichar('A'))
- grid6(2:2)=char(j2+ichar('A'))
- grid6(3:3)=char(j3+ichar('0'))
- grid6(4:4)=char(j4+ichar('0'))
- grid6(5:5)=char(j5+ichar('A'))
- grid6(6:6)=char(j6+ichar('A'))
- ok=.true.
-
-900 return
-end subroutine to_grid6var
-
-subroutine to_gridvar(n,grid6,ok)
- ! 4-, or 6-character grid
- character*6 grid6
- logical ok
-
- ok=.false.
- j1=n/(18*10*10*25*25)
- if (j1.lt.0.or.j1.gt.17) goto 900
- n=n-j1*18*10*10*25*25
- j2=n/(10*10*25*25)
- if (j2.lt.0.or.j2.gt.17) goto 900
- n=n-j2*10*10*25*25
- j3=n/(10*25*25)
- if (j3.lt.0.or.j3.gt.9) goto 900
- n=n-j3*10*25*25
- j4=n/(25*25)
- if (j4.lt.0.or.j4.gt.9) goto 900
- n=n-j4*25*25
- j5=n/25
- if (j5.lt.0.or.j5.gt.24) goto 900
- j6=n-j5*25
- if (j6.lt.0.or.j6.gt.24) goto 900
- grid6=''
- grid6(1:1)=char(j1+ichar('A'))
- grid6(2:2)=char(j2+ichar('A'))
- grid6(3:3)=char(j3+ichar('0'))
- grid6(4:4)=char(j4+ichar('0'))
- if (j5.ne.24.or.j6.ne.24) then
- grid6(5:5)=char(j5+ichar('A'))
- grid6(6:6)=char(j6+ichar('A'))
- endif
- ok=.true.
-
-900 return
-end subroutine to_gridvar
+end function pack77_5_candidate
end module packjt77
@@ -3410,7 +2440,6 @@ logical function callok(w)
character*(*) w
character*1 c1
character*2 pfx
- character*3 sfx
logical isdig,islet
islet(c1)=(ichar(c1).ge.65 .and. ichar(c1).le.90) .or. &
@@ -3421,7 +2450,7 @@ logical function callok(w)
n=len(trim(w))
if(n.lt.3) return !Must be at lkeast three characters
if(w(1:1).eq.'Q') return !Callsigns can't start with Q
-
+
i0=0
do i=n,1,-1
if(isdig(w(i:i))) exit
@@ -3431,7 +2460,6 @@ logical function callok(w)
if(i0.ne.2 .and. i0.ne.3) return
pfx=w(1:i0-1) !Prefix, without call area
- sfx=w(i0+1:) !Suffix
nlp=0
ndp=0
@@ -3440,16 +2468,18 @@ logical function callok(w)
if(isdig(pfx(i:i))) ndp=ndp+1
if(islet(pfx(i:i))) nlp=nlp+1
enddo
+ if(nlp+ndp.ne.np) return
if(nlp.eq.0) return !Prefix must have at least one letter
nls=0
- ns=len(trim(sfx))
- do i=1,ns
- if(islet(sfx(i:i))) nls=nls+1
+ ns=n-i0
+ if(ns.lt.1 .or. ns.gt.3) return
+ do i=i0+1,n
+ if(islet(w(i:i))) nls=nls+1
enddo
if(nls.lt.ns) return !Suffix must be all letters
- callok=.true.
-
+ callok=.true.
+
return
end function callok
diff --git a/lib/77bit/packjt77_grammar.f90 b/lib/77bit/packjt77_grammar.f90
new file mode 100644
index 00000000..7a2616b0
--- /dev/null
+++ b/lib/77bit/packjt77_grammar.f90
@@ -0,0 +1,1530 @@
+module packjt77_grammar
+
+ implicit none
+
+ private :: pack77_gate_staged_call_matches
+
+ integer, parameter :: PACK77_NSEC=86
+ integer, parameter :: PACK77_NUSCAN=171
+ integer, parameter :: PACK77_WSPR_NZZZ=46656
+! c28 number-space partition: special tokens, then 22-bit hashes, then
+! standard callsigns; grid4 indexes above PACK77_MAXGRID4 carry reports.
+ integer, parameter :: PACK77_NTOKENS=2063592
+ integer, parameter :: PACK77_MAX22=4194304
+ integer, parameter :: PACK77_MAXGRID4=32400
+ character(len=36), parameter :: PACK77_BASE36='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
+ character(len=38), parameter :: PACK77_BASE38=' 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ/'
+ character(len=3), parameter :: PACK77_ARRL_SECTIONS(PACK77_NSEC)=(/ &
+ "AB ","AK ","AL ","AR ","AZ ","BC ","CO ","CT ","DE ","EB ", &
+ "EMA","ENY","EPA","EWA","GA ","GH ","IA ","ID ","IL ","IN ", &
+ "KS ","KY ","LA ","LAX","NS ","MB ","MDC","ME ","MI ","MN ", &
+ "MO ","MS ","MT ","NC ","ND ","NE ","NFL","NH ","NL ","NLI", &
+ "NM ","NNJ","NNY","TER","NTX","NV ","OH ","OK ","ONE","ONN", &
+ "ONS","OR ","ORG","PAC","PR ","QC ","RI ","SB ","SC ","SCV", &
+ "SD ","SDG","SF ","SFL","SJV","SK ","SNJ","STX","SV ","TN ", &
+ "UT ","VA ","VI ","VT ","WCF","WI ","WMA","WNY","WPA","WTX", &
+ "WV ","WWA","WY ","DX ","PE ","NB " /)
+ character(len=3), parameter :: PACK77_RTTY_MULTIPLIERS(PACK77_NUSCAN)=(/ &
+ "AL ","AK ","AZ ","AR ","CA ","CO ","CT ","DE ","FL ","GA ", &
+ "HI ","ID ","IL ","IN ","IA ","KS ","KY ","LA ","ME ","MD ", &
+ "MA ","MI ","MN ","MS ","MO ","MT ","NE ","NV ","NH ","NJ ", &
+ "NM ","NY ","NC ","ND ","OH ","OK ","OR ","PA ","RI ","SC ", &
+ "SD ","TN ","TX ","UT ","VT ","VA ","WA ","WV ","WI ","WY ", &
+ "NB ","NS ","QC ","ON ","MB ","SK ","AB ","BC ","NWT","NF ", &
+ "LB ","NU ","YT ","PEI","DC ","DR ","FR ","GD ","GR ","OV ", &
+ "ZH ","ZL ","X01","X02","X03","X04","X05","X06","X07","X08", &
+ "X09","X10","X11","X12","X13","X14","X15","X16","X17","X18", &
+ "X19","X20","X21","X22","X23","X24","X25","X26","X27","X28", &
+ "X29","X30","X31","X32","X33","X34","X35","X36","X37","X38", &
+ "X39","X40","X41","X42","X43","X44","X45","X46","X47","X48", &
+ "X49","X50","X51","X52","X53","X54","X55","X56","X57","X58", &
+ "X59","X60","X61","X62","X63","X64","X65","X66","X67","X68", &
+ "X69","X70","X71","X72","X73","X74","X75","X76","X77","X78", &
+ "X79","X80","X81","X82","X83","X84","X85","X86","X87","X88", &
+ "X89","X90","X91","X92","X93","X94","X95","X96","X97","X98", &
+ "X99" /)
+ integer, parameter :: PACK77_TYPE12_SUFFIX_NONE=0
+ integer, parameter :: PACK77_TYPE12_SUFFIX_R=1
+ integer, parameter :: PACK77_TYPE12_SUFFIX_P=2
+
+
+ type pack77_type12_call_source
+ character(len=13) :: c28_token=''
+ integer :: suffix=PACK77_TYPE12_SUFFIX_NONE
+ logical :: is_hash=.false.
+ logical :: is_cq=.false.
+ end type pack77_type12_call_source
+
+ type pack77_type12_source
+ type(pack77_type12_call_source) :: call_1
+ type(pack77_type12_call_source) :: call_2
+ integer :: ir=0
+ integer :: igrid4=0
+ integer :: i3=1
+ end type pack77_type12_source
+
+ type pack77_dxpedition_source
+ character(len=13) :: call_1='',call_2='',hash_token=''
+ integer :: n5=0
+ end type pack77_dxpedition_source
+
+ type pack77_field_day_source
+ character(len=13) :: call_1='',call_2=''
+ integer :: ir=0,ntx=0,nclass=0,isec=-1
+ end type pack77_field_day_source
+
+ type pack77_wspr_source
+ character(len=13) :: call_token='',hash_token=''
+ character(len=6) :: base_call='',grid6=''
+ character(len=4) :: grid4=''
+ integer :: subtype=0,idbm=0,npfx=0
+ end type pack77_wspr_source
+
+ type pack77_type3_source
+ character(len=13) :: call_1='',call_2=''
+ integer :: itu=0,ir=0,irpt=-1,nexch=0
+ end type pack77_type3_source
+
+ type pack77_type4_source
+ character(len=13) :: hash_token=''
+ character(len=11) :: c11=''
+ integer :: icq=0,iflip=0,itail=0
+ end type pack77_type4_source
+
+ type pack77_type5_source
+ character(len=13) :: hash_token_1='',hash_token_2=''
+ character(len=6) :: grid6=''
+ integer :: ir=0,irpt=0,iserial=0
+ end type pack77_type5_source
+ contains
+
+integer function pack77_arrl_section_index(section) result(isec)
+ character(len=*), intent(in) :: section
+ integer :: i
+
+ isec=-1
+ if(len(section).lt.3) return
+ do i=1,PACK77_NSEC
+ if(PACK77_ARRL_SECTIONS(i).eq.section(1:3)) then
+ isec=i
+ return
+ endif
+ enddo
+
+ return
+end function pack77_arrl_section_index
+
+character(len=3) function pack77_arrl_section_name(isec) result(section)
+ integer, intent(in) :: isec
+
+ section=' '
+ if(isec.ge.1 .and. isec.le.PACK77_NSEC) section=PACK77_ARRL_SECTIONS(isec)
+
+ return
+end function pack77_arrl_section_name
+
+integer function pack77_rtty_multiplier_index(multiplier) result(imult)
+ character(len=*), intent(in) :: multiplier
+ integer :: i
+
+ imult=-1
+ if(len(multiplier).lt.3) return
+ do i=1,PACK77_NUSCAN
+ if(PACK77_RTTY_MULTIPLIERS(i).eq.multiplier(1:3)) then
+ imult=i
+ return
+ endif
+ enddo
+
+ return
+end function pack77_rtty_multiplier_index
+
+character(len=3) function pack77_rtty_multiplier_name(imult) result(multiplier)
+ integer, intent(in) :: imult
+
+ multiplier=' '
+ if(imult.ge.1 .and. imult.le.PACK77_NUSCAN) &
+ multiplier=PACK77_RTTY_MULTIPLIERS(imult)
+
+ return
+end function pack77_rtty_multiplier_name
+
+integer function pack77_report_index_from_snr(isnr) result(irpt)
+ integer, intent(in) :: isnr
+
+ if(isnr.lt.-50 .or. isnr.gt.50) then
+ irpt=-1
+ return
+ endif
+! irpt 1..85 covers the legacy -30..+50 dB range; -50..-31 dB fold to
+! irpt 86..105 above the old top so pre-extension decoders keep their mapping.
+ irpt=isnr
+ if(irpt.ge.-50 .and. irpt.le.-31) irpt=irpt+101
+ irpt=irpt+35
+
+ return
+end function pack77_report_index_from_snr
+
+integer function pack77_snr_from_report_index(irpt) result(isnr)
+ integer, intent(in) :: irpt
+
+ isnr=irpt-35
+ if(isnr.gt.50) isnr=isnr-101
+
+ return
+end function pack77_snr_from_report_index
+
+character(len=3) function pack77_format_snr_report(isnr) result(crpt)
+ integer, intent(in) :: isnr
+
+ write(crpt,'(i3.2)') isnr
+ if(crpt(1:1).eq.' ') crpt(1:1)='+'
+
+ return
+end function pack77_format_snr_report
+
+integer function pack77_rtty_report_index(report) result(irpt)
+ character(len=*), intent(in) :: report
+
+ irpt=-1
+ if(len_trim(report).ne.3) return
+ if(report(1:1).ne.'5') return
+ if(report(2:2).lt.'2' .or. report(2:2).gt.'9') return
+ if(report(3:3).ne.'9') return
+ irpt=iachar(report(2:2))-iachar('2')
+end function pack77_rtty_report_index
+
+character(len=3) function pack77_format_rtty_report(irpt) result(crpt)
+ integer, intent(in) :: irpt
+
+ write(crpt,1001) irpt+2
+1001 format('5',i1,'9')
+
+ return
+end function pack77_format_rtty_report
+
+character(len=6) function pack77_format_vhf_exchange(irpt,iserial) result(cexch)
+ integer, intent(in) :: irpt,iserial
+
+ write(cexch,1002) 52+irpt,iserial
+1002 format(i2,i4.4)
+
+ return
+end function pack77_format_vhf_exchange
+
+character(len=37) function pack77_format_type3_message(itu,ir,call_1,call_2,crpt,exchange) result(msg)
+ integer, intent(in) :: itu,ir
+ character(len=*), intent(in) :: call_1,call_2,crpt,exchange
+ character(len=37) :: body
+
+ body=pack77_format_exchange_message(call_1,call_2,ir,crpt//' '//exchange,.true.)
+ msg=body
+ if(itu.eq.1) msg='TU; '//trim(body)
+
+ return
+end function pack77_format_type3_message
+
+integer function pack77_type3_message_len(itu,ir,call_1_len,call_2_len,exchange_len) result(nmsg)
+ integer, intent(in) :: itu,ir,call_1_len,call_2_len,exchange_len
+
+ nmsg=call_1_len + 1 + call_2_len + 1 + 3 + 1 + exchange_len
+ if(ir.eq.1) nmsg=call_1_len + 1 + call_2_len + 3 + 3 + 1 + exchange_len
+ if(itu.eq.1) nmsg=nmsg+4
+end function pack77_type3_message_len
+
+integer function pack77_type3_display_call_len(n28,call_text) result(ncall)
+ integer, intent(in) :: n28
+ character(len=*), intent(in) :: call_text
+ ncall=len_trim(call_text)
+ if(n28.ge.PACK77_NTOKENS .and. n28.lt.PACK77_NTOKENS+PACK77_MAX22) then
+ if(ncall.gt.11) then
+ ncall=-1
+ else
+ ncall=ncall+2
+ endif
+ endif
+end function pack77_type3_display_call_len
+
+logical function pack77_type3_display_fits(itu,ir,n28a,n28b,call_1,call_2,exchange) result(ok)
+ integer, intent(in) :: itu,ir,n28a,n28b
+ character(len=*), intent(in) :: call_1,call_2,exchange
+ integer :: ncall_1,ncall_2,nmsg
+
+ ok=.false.
+ ncall_1=pack77_type3_display_call_len(n28a,call_1)
+ if(ncall_1.lt.0) return
+ ncall_2=pack77_type3_display_call_len(n28b,call_2)
+ if(ncall_2.lt.0) return
+ nmsg=pack77_type3_message_len(itu,ir,ncall_1,ncall_2,len_trim(exchange))
+ ok=nmsg.le.37
+end function pack77_type3_display_fits
+
+logical function pack77_type3_render_fits(itu,ir,call_1,call_2,exchange) result(ok)
+ integer, intent(in) :: itu,ir
+ character(len=*), intent(in) :: call_1,call_2,exchange
+ integer :: ncall_1,ncall_2,nmsg
+
+ ok=.false.
+ ncall_1=len_trim(call_1)
+ ncall_2=len_trim(call_2)
+ if(call_1(1:1).eq.'<' .and. index(call_1,'>').lt.1) return
+ if(call_2(1:1).eq.'<' .and. index(call_2,'>').lt.1) return
+ nmsg=pack77_type3_message_len(itu,ir,ncall_1,ncall_2,len_trim(exchange))
+ ok=nmsg.le.37
+end function pack77_type3_render_fits
+
+character(len=37) function pack77_format_qso_tail(call_1,call_2,itail) result(msg)
+ character(len=*), intent(in) :: call_1,call_2
+ integer, intent(in) :: itail
+
+ msg=trim(call_1)//' '//trim(call_2)
+ if(itail.eq.1) msg=trim(call_1)//' '//trim(call_2)//' RRR'
+ if(itail.eq.2) msg=trim(call_1)//' '//trim(call_2)//' RR73'
+ if(itail.eq.3) msg=trim(call_1)//' '//trim(call_2)//' 73'
+
+ return
+end function pack77_format_qso_tail
+
+integer function pack77_qso_tail_index(token) result(itail)
+ character(len=*), intent(in) :: token
+
+ itail=0
+ if(trim(token).eq.'RRR') itail=1
+ if(trim(token).eq.'RR73') itail=2
+ if(trim(token).eq.'73') itail=3
+end function pack77_qso_tail_index
+
+integer function pack77_type12_irpt_from_tail(itail) result(irpt)
+ integer, intent(in) :: itail
+
+ irpt=0
+ if(itail.ge.1 .and. itail.le.3) irpt=itail+1
+end function pack77_type12_irpt_from_tail
+
+integer function pack77_tail_from_type12_irpt(irpt) result(itail)
+ integer, intent(in) :: irpt
+
+ itail=0
+ if(irpt.ge.2 .and. irpt.le.4) itail=irpt-1
+end function pack77_tail_from_type12_irpt
+
+integer function pack77_type4_nrpt_from_tail(itail) result(nrpt)
+ integer, intent(in) :: itail
+
+ nrpt=0
+ if(itail.ge.1 .and. itail.le.3) nrpt=itail
+end function pack77_type4_nrpt_from_tail
+
+integer function pack77_tail_from_type4_nrpt(nrpt) result(itail)
+ integer, intent(in) :: nrpt
+
+ itail=0
+ if(nrpt.ge.1 .and. nrpt.le.3) itail=nrpt
+end function pack77_tail_from_type4_nrpt
+
+character(len=37) function pack77_format_exchange_message(call_1,call_2,ir,exchange,reply_has_separate_token) result(msg)
+ character(len=*), intent(in) :: call_1,call_2,exchange
+ integer, intent(in) :: ir
+ logical, intent(in) :: reply_has_separate_token
+
+ msg=trim(call_1)//' '//trim(call_2)//' '//exchange
+ if(ir.eq.1) then
+ if(reply_has_separate_token) then
+ msg=trim(call_1)//' '//trim(call_2)//' R '//exchange
+ else
+ msg=trim(call_1)//' '//trim(call_2)//' R'//exchange
+ endif
+ endif
+
+ return
+end function pack77_format_exchange_message
+
+logical function pack77_is_digit_char(c) result(is_digit)
+ character(len=1), intent(in) :: c
+
+ is_digit=c.ge.'0' .and. c.le.'9'
+
+ return
+end function pack77_is_digit_char
+
+logical function pack77_is_letter_char(c) result(is_letter)
+ character(len=1), intent(in) :: c
+
+ is_letter=c.ge.'A' .and. c.le.'Z'
+
+ return
+end function pack77_is_letter_char
+
+logical function pack77_all_digits(token) result(ok)
+ character(len=*), intent(in) :: token
+ integer :: i,n
+
+ ok=.false.
+ n=len_trim(token)
+ if(n.lt.1) return
+ do i=1,n
+ if(.not.pack77_is_digit_char(token(i:i))) return
+ enddo
+ ok=.true.
+end function pack77_all_digits
+
+subroutine pack77_parse_uint(token,value,ok)
+ character(len=*), intent(in) :: token
+ integer, intent(out) :: value
+ logical, intent(out) :: ok
+
+ value=0
+ ok=pack77_all_digits(token)
+ if(.not.ok) return
+ read(token,*,err=10) value
+ return
+10 ok=.false.
+end subroutine pack77_parse_uint
+
+subroutine pack77_parse_signed_report(token,value,ok)
+ character(len=*), intent(in) :: token
+ integer, intent(out) :: value
+ logical, intent(out) :: ok
+
+ value=0
+ ok=.false.
+ if(len_trim(token).ne.3) return
+ if(token(1:1).ne.'+' .and. token(1:1).ne.'-') return
+ if(.not.pack77_is_digit_char(token(2:2))) return
+ if(.not.pack77_is_digit_char(token(3:3))) return
+ read(token,*,err=10) value
+ ok=.true.
+ return
+10 ok=.false.
+end subroutine pack77_parse_signed_report
+
+subroutine pack77_parse_dxpedition_report(token,n5,ok)
+ character(len=*), intent(in) :: token
+ integer, intent(out) :: n5
+ integer :: isnr
+ logical, intent(out) :: ok
+
+ n5=0
+ call pack77_parse_signed_report(token,isnr,ok)
+ if(.not.ok) return
+ if(isnr.lt.-30 .or. isnr.gt.32) then
+ ok=.false.
+ return
+ endif
+ n5=(isnr+30)/2
+ ok=(2*n5-30).eq.isnr
+end subroutine pack77_parse_dxpedition_report
+
+subroutine pack77_parse_type3_serial(token,nserial,ok)
+ character(len=*), intent(in) :: token
+ integer, intent(out) :: nserial
+ logical, intent(out) :: ok
+
+ nserial=0
+ ok=.false.
+ if(len_trim(token).ne.4) return
+ call pack77_parse_uint(token,nserial,ok)
+ if(.not.ok) return
+ ok=nserial.ge.1 .and. nserial.le.7999
+end subroutine pack77_parse_type3_serial
+
+subroutine pack77_parse_wspr_dbm(token,idbm,ok)
+ character(len=*), intent(in) :: token
+ integer, intent(out) :: idbm
+ integer :: dbm,decoded_dbm
+ logical, intent(out) :: ok
+
+ idbm=0
+ call pack77_parse_uint(token,dbm,ok)
+ if(.not.ok) return
+ if(len_trim(token).gt.1 .and. token(1:1).eq.'0') then
+ ok=.false.
+ return
+ endif
+ if(dbm.lt.0 .or. dbm.gt.60) then
+ ok=.false.
+ return
+ endif
+ idbm=nint(0.3*dbm)
+ decoded_dbm=nint(idbm*10.0/3.0)
+ ok=decoded_dbm.eq.dbm
+end subroutine pack77_parse_wspr_dbm
+
+subroutine pack77_parse_field_day_exchange(token,ntx,nclass,ok)
+ character(len=*), intent(in) :: token
+ integer, intent(out) :: ntx,nclass
+ integer :: n
+ logical, intent(out) :: ok
+
+ ntx=-1
+ nclass=-1
+ ok=.false.
+ n=len_trim(token)
+ if(n.lt.2) return
+ if(n.gt.2 .and. token(1:1).eq.'0') return
+ call pack77_parse_uint(token(1:n-1),ntx,ok)
+ if(.not.ok) return
+ if(ntx.lt.1 .or. ntx.gt.32) then
+ ok=.false.
+ return
+ endif
+ nclass=ichar(token(n:n))-ichar('A')
+ ok=nclass.ge.0 .and. nclass.le.5
+end subroutine pack77_parse_field_day_exchange
+
+logical function pack77_valid_hash_call_token(token) result(ok)
+ character(len=*), intent(in) :: token
+ integer :: n
+
+ ok=.false.
+ n=len_trim(token)
+ if(n.lt.5 .or. n.gt.13) return
+ if(token(1:1).ne.'<' .or. token(n:n).ne.'>') return
+ if(index(token(2:n-1),'<').gt.0) return
+ if(index(token(2:n-1),'>').gt.0) return
+ ok=.true.
+end function pack77_valid_hash_call_token
+
+logical function pack77_valid_cq_modifier(token) result(ok)
+ character(len=*), intent(in) :: token
+ integer :: i,n,nletters,ndigits
+
+ ok=.false.
+ n=len_trim(token)
+ if(n.lt.1 .or. n.gt.4) return
+ nletters=0
+ ndigits=0
+ do i=1,n
+ if(token(i:i).ge.'A' .and. token(i:i).le.'Z') then
+ nletters=nletters+1
+ else if(pack77_is_digit_char(token(i:i))) then
+ ndigits=ndigits+1
+ else
+ return
+ endif
+ enddo
+ ok=(ndigits.eq.3 .and. nletters.eq.0) .or. &
+ (nletters.ge.1 .and. nletters.le.4 .and. ndigits.eq.0)
+end function pack77_valid_cq_modifier
+
+pure subroutine pack77_split_source_tokens(msg,max_words,nwords,w,ok)
+ character(len=*), intent(in) :: msg
+ integer, intent(in) :: max_words
+ integer, intent(out) :: nwords
+ character(len=*), intent(out) :: w(:)
+ logical, intent(out) :: ok
+ character(len=1) :: c,c0
+ integer :: i,n,iz
+
+ nwords=0
+ n=0
+ c0=' '
+ w=' '
+ ok=.true.
+ iz=len_trim(msg)
+ do i=1,iz
+ c=msg(i:i)
+ if(ichar(c).eq.0) c=' '
+ if(c.ge.'a' .and. c.le.'z') c=char(ichar(c)-32)
+ if(c.eq.' ' .and. c0.eq.' ') cycle
+ if(c.ne.' ' .and. c0.eq.' ') then
+ nwords=nwords+1
+ n=0
+ if(nwords.gt.max_words .or. nwords.gt.size(w)) then
+ ok=.false.
+ return
+ endif
+ endif
+ if(c.ne.' ') then
+ n=n+1
+ if(n.gt.len(w(1))) then
+ ok=.false.
+ return
+ endif
+ w(nwords)(n:n)=c
+ endif
+ c0=c
+ enddo
+end subroutine pack77_split_source_tokens
+
+pure subroutine pack77_gate_message_checks(input_msg,decoded_msg,staged_calls, &
+ nstaged,messages_match,resolved_render_fits)
+ character(len=*), intent(in) :: input_msg,decoded_msg
+ character(len=13), intent(in) :: staged_calls(:)
+ integer, intent(in) :: nstaged
+ logical, intent(out) :: messages_match,resolved_render_fits
+ character(len=37) :: input_tokens(19),decoded_tokens(19),input_body
+ integer :: input_nwords,decoded_nwords,i,nrender,nbody
+ logical :: input_ok,decoded_ok,token_match
+
+ messages_match=.false.
+ resolved_render_fits=.false.
+ call pack77_split_source_tokens(input_msg,19,input_nwords,input_tokens,input_ok)
+ call pack77_split_source_tokens(decoded_msg,19,decoded_nwords,decoded_tokens, &
+ decoded_ok)
+ if(.not.input_ok .or. .not.decoded_ok) return
+ if(input_nwords.ne.decoded_nwords) return
+
+ messages_match=.true.
+ resolved_render_fits=.true.
+! nrender is the display length after hash resolution: a decoded <...> token
+! renders as the staged call body plus its two brackets, and separators are
+! counted only between tokens.
+ nrender=0
+ do i=1,input_nwords
+ if(i.gt.1) nrender=nrender+1
+ token_match=.false.
+ if(trim(decoded_tokens(i)).eq.trim(input_tokens(i))) then
+ token_match=.true.
+ nrender=nrender+len_trim(decoded_tokens(i))
+ else
+ input_body=' '
+ input_body='<'//trim(input_tokens(i))//'>'
+ if(trim(decoded_tokens(i)).eq.trim(input_body)) then
+ token_match=.true.
+ nrender=nrender+len_trim(decoded_tokens(i))
+ else if(trim(decoded_tokens(i)).eq.'<...>') then
+ input_body=input_tokens(i)
+ nbody=len_trim(input_body)
+ if(nbody.ge.2 .and. input_body(1:1).eq.'<' .and. &
+ input_body(nbody:nbody).eq.'>') then
+ input_body=' '
+ if(nbody.gt.2) input_body=input_tokens(i)(2:nbody-1)
+ endif
+ token_match=pack77_gate_staged_call_matches(input_body,staged_calls, &
+ nstaged)
+ if(len_trim(input_body).gt.11) resolved_render_fits=.false.
+ nrender=nrender+len_trim(input_body)+2
+ else
+ nrender=nrender+len_trim(decoded_tokens(i))
+ endif
+ endif
+ if(.not.token_match) messages_match=.false.
+ if(trim(decoded_tokens(i)).eq.'<...>' .and. .not.token_match) &
+ resolved_render_fits=.false.
+ if(nrender.gt.37) resolved_render_fits=.false.
+ enddo
+end subroutine pack77_gate_message_checks
+
+! Canonicalization accepted by the encode/decode gate is exhaustive:
+! 1. The tokenizer folds case and collapses blanks before parsing.
+! 2. A compound/nonstandard call in a c28 slot transmits as a hash and decodes bracketed.
+! 3. A bracketed hash decodes as <...> when no hash-table call is available and the staged source call matches.
+! 4. Type 4 CQ accepts only unbracketed c11 CQ targets; bracketed CQ targets are rejected and decoded CQ targets stay unbracketed.
+! 5. DX-macro expansion is performed by callers through pack77_options before this gate.
+! Any other source-vs-decode difference is rejected by this gate.
+pure logical function pack77_gate_messages_match(input_msg,decoded_msg, &
+ staged_calls,nstaged) result(ok)
+ character(len=*), intent(in) :: input_msg,decoded_msg
+ character(len=13), intent(in) :: staged_calls(:)
+ integer, intent(in) :: nstaged
+ logical :: resolved_render_fits
+
+ call pack77_gate_message_checks(input_msg,decoded_msg,staged_calls,nstaged, &
+ ok,resolved_render_fits)
+end function pack77_gate_messages_match
+
+pure logical function pack77_gate_staged_call_matches(input_body,staged_calls, &
+ nstaged) result(ok)
+ character(len=*), intent(in) :: input_body
+ character(len=13), intent(in) :: staged_calls(:)
+ integer, intent(in) :: nstaged
+ integer :: i,n
+
+ ok=.false.
+ n=min(max(nstaged,0),size(staged_calls))
+ do i=1,n
+ if(trim(staged_calls(i)).eq.trim(input_body)) then
+ ok=.true.
+ return
+ endif
+ enddo
+end function pack77_gate_staged_call_matches
+
+pure logical function pack77_gate_resolved_render_fits(input_msg,decoded_msg, &
+ staged_calls,nstaged) result(ok)
+ character(len=*), intent(in) :: input_msg,decoded_msg
+ character(len=13), intent(in) :: staged_calls(:)
+ integer, intent(in) :: nstaged
+ logical :: messages_match
+
+ call pack77_gate_message_checks(input_msg,decoded_msg,staged_calls,nstaged, &
+ messages_match,ok)
+end function pack77_gate_resolved_render_fits
+
+logical function pack77_c28_standard_shape(token) result(ok)
+ character(len=*), intent(in) :: token
+ integer :: i,n,iarea,npdig,nplet,nslet
+ character(len=1) :: c
+
+ ok=.false.
+ n=len_trim(token)
+ if(n.lt.3 .or. n.gt.6) return
+ do i=1,n
+ c=token(i:i)
+ if(.not.((c.ge.'A' .and. c.le.'Z') .or. pack77_is_digit_char(c))) return
+ enddo
+
+ iarea=0
+ do i=n,2,-1
+ if(pack77_is_digit_char(token(i:i))) then
+ iarea=i
+ exit
+ endif
+ enddo
+ if(iarea.ne.2 .and. iarea.ne.3) return
+
+ npdig=0
+ nplet=0
+ do i=1,iarea-1
+ c=token(i:i)
+ if(pack77_is_digit_char(c)) then
+ npdig=npdig+1
+ else if(c.ge.'A' .and. c.le.'Z') then
+ nplet=nplet+1
+ else
+ return
+ endif
+ enddo
+ if(nplet.eq.0 .or. npdig.ge.iarea-1) return
+
+ nslet=0
+ do i=iarea+1,n
+ c=token(i:i)
+ if(c.ge.'A' .and. c.le.'Z') then
+ nslet=nslet+1
+ else
+ return
+ endif
+ enddo
+ ok=nslet.le.3
+end function pack77_c28_standard_shape
+
+logical function pack77_type12_standard_call(token) result(ok)
+ character(len=*), intent(in) :: token
+
+ ok=.false.
+ if(.not.pack77_c28_standard_shape(token)) return
+ ! Q-prefix rejection is a source-grammar policy, not a c28 wire shape fact.
+ if(token(1:1).eq.'Q') return
+ ok=.true.
+end function pack77_type12_standard_call
+
+
+subroutine pack77_parse_type12_call(token,allow_special,call_source,ok)
+ character(len=*), intent(in) :: token
+ logical, intent(in) :: allow_special
+ type(pack77_type12_call_source), intent(out) :: call_source
+ logical, intent(out) :: ok
+ character(len=37) :: base,modifier
+ integer :: n,slash
+
+ call_source=pack77_type12_call_source()
+ ok=.false.
+ n=len_trim(token)
+ if(n.lt.1 .or. n.gt.13) return
+
+ if(allow_special) then
+ if(trim(token).eq.'CQ') then
+ call_source%c28_token='CQ'
+ call_source%is_cq=.true.
+ ok=.true.
+ return
+ endif
+ if(trim(token).eq.'DE' .or. trim(token).eq.'QRZ') then
+ call_source%c28_token=trim(token)
+ ok=.true.
+ return
+ endif
+ if(n.ge.4 .and. token(1:3).eq.'CQ_') then
+ modifier=' '
+ modifier=token(4:n)
+ if(.not.pack77_valid_cq_modifier(modifier)) return
+ call_source%c28_token=trim(token)
+ call_source%is_cq=.true.
+ ok=.true.
+ return
+ endif
+ endif
+
+ if(token(1:1).eq.'<' .or. index(token(1:n),'>').gt.0) then
+ if(.not.pack77_valid_hash_call_token(token)) return
+ call_source%c28_token=trim(token)
+ call_source%is_hash=.true.
+ ok=.true.
+ return
+ endif
+
+ slash=index(token(1:n),'/')
+ base=' '
+ if(slash.gt.0) then
+ if(slash.lt.2 .or. slash.ne.n-1) return
+ if(index(token(slash+1:n),'/').gt.0) return
+ if(token(slash:n).eq.'/R') then
+ call_source%suffix=PACK77_TYPE12_SUFFIX_R
+ else if(token(slash:n).eq.'/P') then
+ call_source%suffix=PACK77_TYPE12_SUFFIX_P
+ else
+ return
+ endif
+ base=token(1:slash-1)
+ else
+ base=token(1:n)
+ endif
+
+ if(.not.pack77_type12_standard_call(base)) return
+ call_source%c28_token=trim(base)
+ ok=.true.
+end subroutine pack77_parse_type12_call
+
+logical function pack77_type12_call_has_suffix(call_source) result(ok)
+ type(pack77_type12_call_source), intent(in) :: call_source
+
+ ok=call_source%suffix.ne.PACK77_TYPE12_SUFFIX_NONE
+end function pack77_type12_call_has_suffix
+
+subroutine pack77_parse_type12_source(msg,source,ok)
+ character(len=*), intent(in) :: msg
+ type(pack77_type12_source), intent(out) :: source
+ logical, intent(out) :: ok
+ character(len=37) :: w(5),call_1_token,tail
+ integer :: nwords,call_2_index,tail_start,ntail,itail,isnr,irpt
+ logical :: split_ok,call_ok,tail_is_grid
+
+ source=pack77_type12_source()
+ ok=.false.
+ call pack77_split_source_tokens(msg,5,nwords,w,split_ok)
+ if(.not.split_ok) return
+ if(nwords.lt.2) return
+
+ call_1_token=w(1)
+ call_2_index=2
+ tail_start=3
+ if(trim(w(1)).eq.'CQ' .and. nwords.ge.3 .and. &
+ pack77_valid_cq_modifier(w(2))) then
+ call_1_token=' '
+ call_1_token='CQ_'//trim(w(2))
+ call_2_index=3
+ tail_start=4
+ endif
+
+ call pack77_parse_type12_call(call_1_token,.true.,source%call_1,call_ok)
+ if(.not.call_ok) return
+ call pack77_parse_type12_call(w(call_2_index),.false.,source%call_2,call_ok)
+ if(.not.call_ok) return
+ if(source%call_1%is_cq .and. source%call_2%is_hash) return
+ if(source%call_1%is_hash .and. &
+ (pack77_type12_call_has_suffix(source%call_2) .or. &
+ index(source%call_2%c28_token,'/').gt.0)) return
+ if(source%call_2%is_hash .and. &
+ (pack77_type12_call_has_suffix(source%call_1) .or. &
+ index(source%call_1%c28_token,'/').gt.0)) return
+
+ if(source%call_1%suffix.eq.PACK77_TYPE12_SUFFIX_R .and. &
+ source%call_2%suffix.eq.PACK77_TYPE12_SUFFIX_P) return
+ if(source%call_1%suffix.eq.PACK77_TYPE12_SUFFIX_P .and. &
+ source%call_2%suffix.eq.PACK77_TYPE12_SUFFIX_R) return
+
+ source%i3=1
+ if(source%call_1%suffix.eq.PACK77_TYPE12_SUFFIX_P .or. &
+ source%call_2%suffix.eq.PACK77_TYPE12_SUFFIX_P) source%i3=2
+
+ ntail=nwords-tail_start+1
+ if(ntail.lt.0 .or. ntail.gt.2) return
+ if(ntail.eq.0) then
+ source%ir=0
+ source%igrid4=PACK77_MAXGRID4+1
+ ok=.true.
+ return
+ endif
+
+ if(ntail.eq.2) then
+ if(trim(w(tail_start)).ne.'R') return
+ if(source%call_1%is_cq) return
+ if(len_trim(w(tail_start+1)).ne.4) return
+ if(.not.pack77_is_grid4(w(tail_start+1))) return
+ source%ir=1
+ source%igrid4=pack77_grid4_index(w(tail_start+1)(1:4))
+ ok=.true.
+ return
+ endif
+
+ tail=w(tail_start)
+ tail_is_grid=.false.
+ if(len_trim(tail).eq.4) tail_is_grid=pack77_is_grid4(tail)
+ if(tail_is_grid) then
+ source%ir=0
+ source%igrid4=pack77_grid4_index(tail(1:4))
+ ok=.true.
+ return
+ endif
+ if(source%call_1%is_cq) return
+
+ if(tail(1:1).eq.'+' .or. tail(1:1).eq.'-') then
+ call pack77_parse_signed_report(tail,isnr,ok)
+ if(.not.ok) return
+ irpt=pack77_report_index_from_snr(isnr)
+ if(irpt.lt.1) then
+ ok=.false.
+ return
+ endif
+ source%ir=0
+ source%igrid4=PACK77_MAXGRID4+irpt
+ ok=.true.
+ return
+ endif
+ if(tail(1:2).eq.'R+' .or. tail(1:2).eq.'R-') then
+ call pack77_parse_signed_report(tail(2:),isnr,ok)
+ if(.not.ok) return
+ irpt=pack77_report_index_from_snr(isnr)
+ if(irpt.lt.1) then
+ ok=.false.
+ return
+ endif
+ source%ir=1
+ source%igrid4=PACK77_MAXGRID4+irpt
+ ok=.true.
+ return
+ endif
+
+ itail=pack77_qso_tail_index(tail)
+ if(itail.lt.1) return
+ source%ir=0
+ source%igrid4=PACK77_MAXGRID4+pack77_type12_irpt_from_tail(itail)
+ ok=.true.
+end subroutine pack77_parse_type12_source
+logical function pack77_valid_c28_call_slot(token) result(ok)
+ character(len=*), intent(in) :: token
+ integer :: i,n,slash
+
+ ok=.false.
+ n=len_trim(token)
+ if(n.lt.3 .or. n.gt.13) return
+ if(pack77_valid_hash_call_token(token)) return
+ do i=1,n
+ if(.not.((token(i:i).ge.'A' .and. token(i:i).le.'Z') .or. &
+ pack77_is_digit_char(token(i:i)) .or. token(i:i).eq.'/')) return
+ enddo
+ if(pack77_type12_standard_call(token)) then
+ ok=.true.
+ return
+ endif
+ slash=index(token(1:n),'/')
+ if(slash.lt.2 .or. slash.ge.n) return
+ if(index(token(slash+1:n),'/').gt.0) return
+ ok=.true.
+end function pack77_valid_c28_call_slot
+
+subroutine pack77_parse_dxpedition_source(msg,source,ok,matched_shape)
+! DXpedition messages encode two c28 calls, a 10-bit hashed callsign, and a
+! report in the fixed "CALL RR73; CALL <HASH> REPORT" token shape.
+ character(len=*), intent(in) :: msg
+ type(pack77_dxpedition_source), intent(out) :: source
+ logical, intent(out) :: ok
+ logical, intent(out) :: matched_shape
+ character(len=37) :: w(5)
+ integer :: nwords
+ logical :: split_ok
+
+ source=pack77_dxpedition_source()
+ ok=.false.
+ matched_shape=.false.
+ call pack77_split_source_tokens(msg,5,nwords,w,split_ok)
+ if(.not.split_ok) return
+ if(nwords.ne.5) return
+ if(trim(w(2)).ne.'RR73;') return
+ matched_shape=.true.
+ if(.not.pack77_valid_c28_call_slot(w(1))) return
+ if(.not.pack77_valid_c28_call_slot(w(3))) return
+ if(.not.pack77_valid_hash_call_token(w(4))) return
+ call pack77_parse_dxpedition_report(w(5),source%n5,ok)
+ if(.not.ok) return
+ source%call_1=trim(w(1))
+ source%call_2=trim(w(3))
+ source%hash_token=trim(w(4))
+end subroutine pack77_parse_dxpedition_source
+
+subroutine pack77_parse_field_day_source(msg,source,ok,matched_shape)
+ character(len=*), intent(in) :: msg
+ type(pack77_field_day_source), intent(out) :: source
+ logical, intent(out) :: ok
+ logical, intent(out) :: matched_shape
+ character(len=37) :: w(5),section
+ integer :: nwords,exchange_index,section_index
+ logical :: split_ok
+
+ source=pack77_field_day_source()
+ ok=.false.
+ matched_shape=.false.
+ call pack77_split_source_tokens(msg,5,nwords,w,split_ok)
+ if(.not.split_ok) return
+ if(nwords.lt.4 .or. nwords.gt.5) return
+ section_index=nwords
+ source%isec=pack77_arrl_section_index(w(section_index))
+ if(source%isec.eq.-1) return
+ section=pack77_arrl_section_name(source%isec)
+ if(len_trim(w(section_index)).ne.len_trim(section)) return
+ matched_shape=.true.
+ if(.not.pack77_valid_c28_call_slot(w(1))) return
+ if(.not.pack77_valid_c28_call_slot(w(2))) return
+ if(nwords.eq.5) then
+ if(trim(w(3)).ne.'R') return
+ source%ir=1
+ endif
+ exchange_index=nwords-1
+ call pack77_parse_field_day_exchange(w(exchange_index), &
+ source%ntx,source%nclass,ok)
+ if(.not.ok) return
+ source%call_1=trim(w(1))
+ source%call_2=trim(w(2))
+ ok=.true.
+end subroutine pack77_parse_field_day_source
+
+subroutine pack77_parse_wspr_source(msg,source,ok,matched_shape)
+ character(len=*), intent(in) :: msg
+ type(pack77_wspr_source), intent(out) :: source
+ logical, intent(out) :: ok
+ logical, intent(out) :: matched_shape
+ character(len=37) :: w(3),base
+ character(len=3) :: cpfx
+ integer :: nwords,m1,m2,slash
+ logical :: split_ok,is_prefix,grid4_ok
+
+ source=pack77_wspr_source()
+ ok=.false.
+ matched_shape=.false.
+ call pack77_split_source_tokens(msg,3,nwords,w,split_ok)
+ if(.not.split_ok) return
+ if(nwords.lt.2 .or. nwords.gt.3) return
+ m1=len_trim(w(1))
+ m2=len_trim(w(2))
+
+ grid4_ok=.false.
+ if(nwords.eq.3) then
+ grid4_ok=m2.eq.4 .and. pack77_is_grid4(w(2))
+ matched_shape=grid4_ok .and. pack77_all_digits(w(3))
+ else if(nwords.eq.2) then
+ matched_shape=index(w(1)(1:m1),'/').gt.0 .and. pack77_all_digits(w(2))
+ endif
+
+ if(nwords.eq.3) then
+ if(.not.pack77_type12_standard_call(w(1))) return
+ if(.not.grid4_ok) return
+ call pack77_parse_wspr_dbm(w(3),source%idbm,ok)
+ if(.not.ok) return
+ source%subtype=1
+ source%call_token=trim(w(1))
+ source%grid4=w(2)(1:4)
+ ok=.true.
+ return
+ endif
+
+ if(m1.ge.5 .and. m1.le.10 .and. m2.le.2) then
+ slash=index(w(1)(1:m1),'/')
+ if(slash.ge.2 .and. slash.lt.m1 .and. &
+ index(w(1)(slash+1:m1),'/').eq.0) then
+ base=' '
+ if(slash.le.4) then
+ base=w(1)(slash+1:m1)
+ else
+ base=w(1)(1:slash-1)
+ endif
+ if(pack77_type12_standard_call(base)) then
+ call pack77_parse_wspr_dbm(w(2),source%idbm,ok)
+ if(.not.ok) return
+ source%npfx=pack77_wspr_affix_index(w(1),slash,m1,ok)
+ if(.not.ok) return
+ call pack77_wspr_affix_text(source%npfx,cpfx,is_prefix,ok)
+ if(.not.ok) return
+ ok=.false.
+ cpfx=adjustl(cpfx)
+ if(slash.le.4) then
+ if(.not.is_prefix) return
+ if(trim(cpfx).ne.w(1)(1:slash-1)) return
+ else
+ if(is_prefix) return
+ if(trim(cpfx).ne.w(1)(slash+1:m1)) return
+ endif
+ source%subtype=2
+ source%call_token=trim(w(1))
+ source%base_call=trim(base)
+ ok=.true.
+ return
+ endif
+ endif
+ endif
+
+ if(m1.ge.5 .and. m1.le.12 .and. m2.le.6) then
+ if(.not.pack77_valid_hash_call_token(w(1))) return
+ if(.not.pack77_is_grid6(w(2),.true.)) return
+ source%subtype=3
+ source%hash_token=trim(w(1))
+ source%grid6=w(2)(1:6)
+ ok=.true.
+ endif
+end subroutine pack77_parse_wspr_source
+
+subroutine pack77_parse_type3_source(msg,source,ok,matched_shape)
+ character(len=*), intent(in) :: msg
+ type(pack77_type3_source), intent(out) :: source
+ logical, intent(out) :: ok
+ logical, intent(out) :: matched_shape
+ character(len=37) :: w(6),exchange
+ integer :: nwords,report_index,exchange_index,nserial,imult
+ logical :: split_ok,serial_ok
+
+ source=pack77_type3_source()
+ ok=.false.
+ matched_shape=.false.
+ call pack77_split_source_tokens(msg,6,nwords,w,split_ok)
+ if(.not.split_ok) return
+ if(nwords.lt.4 .or. nwords.gt.6) return
+
+ if(trim(w(1)).eq.'TU;') source%itu=1
+ if(trim(w(3+source%itu)).eq.'R') source%ir=1
+ report_index=3+source%itu+source%ir
+ if(report_index.le.nwords) &
+ matched_shape=pack77_rtty_report_index(w(report_index)).ge.0
+ if(.not.pack77_valid_c28_call_slot(w(1+source%itu))) return
+ if(.not.pack77_valid_c28_call_slot(w(2+source%itu))) return
+ source%call_1=trim(w(1+source%itu))
+ source%call_2=trim(w(2+source%itu))
+
+ exchange_index=report_index+1
+ if(exchange_index.ne.nwords) return
+
+ source%irpt=pack77_rtty_report_index(w(report_index))
+ if(source%irpt.lt.0) return
+
+ call pack77_parse_type3_serial(w(exchange_index),nserial,serial_ok)
+ if(serial_ok) then
+ source%nexch=nserial
+ ok=.true.
+ return
+ endif
+
+ imult=pack77_rtty_multiplier_index(w(exchange_index))
+ if(imult.le.0) return
+ exchange=pack77_rtty_multiplier_name(imult)
+ if(len_trim(w(exchange_index)).ne.len_trim(exchange)) return
+ source%nexch=8000+imult
+ ok=.true.
+end subroutine pack77_parse_type3_source
+
+subroutine pack77_parse_type4_source(msg,source,ok)
+ character(len=*), intent(in) :: msg
+ type(pack77_type4_source), intent(out) :: source
+ logical, intent(out) :: ok
+ character(len=37) :: w(3),c11_token
+ integer :: nwords
+ logical :: split_ok,hash_1,hash_2
+
+ source=pack77_type4_source()
+ ok=.false.
+ call pack77_split_source_tokens(msg,3,nwords,w,split_ok)
+ if(.not.split_ok) return
+ if(nwords.lt.2 .or. nwords.gt.3) return
+
+ hash_1=pack77_valid_hash_call_token(w(1))
+ hash_2=pack77_valid_hash_call_token(w(2))
+
+ if(trim(w(1)).eq.'CQ') then
+ if(nwords.ne.2) return
+ if(hash_2) return
+ c11_token=w(2)
+ if(len_trim(c11_token).lt.5) return
+ if(.not.pack77_valid_type4_c11(c11_token)) return
+ if(pack77_type12_standard_call(c11_token)) return
+ source%c11=c11_token(1:11)
+ source%icq=1
+ ok=.true.
+ return
+ endif
+
+ if(nwords.eq.3) then
+ source%itail=pack77_qso_tail_index(w(3))
+ if(source%itail.eq.0) return
+ endif
+
+ if(hash_1 .and. .not.hash_2) then
+ if(.not.pack77_valid_type4_c11(w(2))) return
+ if(pack77_type12_standard_call(w(2))) return
+ source%hash_token=trim(w(1))
+ source%c11=w(2)(1:11)
+ source%iflip=0
+ ok=.true.
+ return
+ endif
+
+ if(hash_2 .and. .not.hash_1) then
+ if(.not.pack77_valid_type4_c11(w(1))) return
+ if(pack77_type12_standard_call(w(1))) return
+ source%hash_token=trim(w(2))
+ source%c11=w(1)(1:11)
+ source%iflip=1
+ ok=.true.
+ return
+ endif
+end subroutine pack77_parse_type4_source
+
+subroutine pack77_parse_type5_source(msg,source,ok,matched_shape)
+! Type 5 EU VHF messages carry two explicit hash tokens, an optional R,
+! report+serial as 52..59 plus 0001..2047, and a required six-character grid.
+ character(len=*), intent(in) :: msg
+ type(pack77_type5_source), intent(out) :: source
+ logical, intent(out) :: ok
+ logical, intent(out) :: matched_shape
+ character(len=37) :: w(5)
+ integer :: nwords,exchange_index,grid_index,nx
+ logical :: split_ok
+
+ source=pack77_type5_source()
+ ok=.false.
+ matched_shape=.false.
+ call pack77_split_source_tokens(msg,5,nwords,w,split_ok)
+ if(.not.split_ok) return
+ if(nwords.lt.4 .or. nwords.gt.5) return
+ matched_shape=pack77_valid_hash_call_token(w(1)) .and. &
+ pack77_valid_hash_call_token(w(2))
+ if(.not.pack77_valid_hash_call_token(w(1))) return
+ if(.not.pack77_valid_hash_call_token(w(2))) return
+ if(nwords.eq.5) then
+ if(trim(w(3)).ne.'R') return
+ source%ir=1
+ endif
+
+ exchange_index=nwords-1
+ grid_index=nwords
+ call pack77_valid_type5_exchange(w(exchange_index),nx,ok)
+ if(.not.ok) return
+ if(nx.lt.520001 .or. nx.gt.592047) then
+ ok=.false.
+ return
+ endif
+ source%iserial=mod(nx,10000)
+ if(source%iserial.lt.1 .or. source%iserial.gt.2047) then
+ ok=.false.
+ return
+ endif
+ if(len_trim(w(grid_index)).ne.6) then
+ ok=.false.
+ return
+ endif
+ if(.not.pack77_is_grid6(w(grid_index),.false.)) then
+ ok=.false.
+ return
+ endif
+
+ source%hash_token_1=trim(w(1))
+ source%hash_token_2=trim(w(2))
+ source%irpt=nx/10000 - 52
+ source%grid6=w(grid_index)(1:6)
+ ok=.true.
+end subroutine pack77_parse_type5_source
+
+logical function pack77_valid_type4_c11(token) result(ok)
+ character(len=*), intent(in) :: token
+ integer :: i,n
+
+ ok=.false.
+ n=len_trim(token)
+ if(n.lt.1 .or. n.gt.11) return
+ do i=1,n
+ if(index(PACK77_BASE38,token(i:i)).lt.1) return
+ enddo
+ ok=.true.
+end function pack77_valid_type4_c11
+
+subroutine pack77_valid_type5_exchange(token,nx,ok)
+ character(len=*), intent(in) :: token
+ integer, intent(out) :: nx
+ logical, intent(out) :: ok
+
+ nx=-1
+ ok=.false.
+ if(len_trim(token).ne.6) return
+ call pack77_parse_uint(token,nx,ok)
+end subroutine pack77_valid_type5_exchange
+
+integer function pack77_wspr_affix_index(token,slash_index,token_len,ok) result(npfx)
+ character(len=*), intent(in) :: token
+ integer, intent(in) :: slash_index,token_len
+ logical, intent(out) :: ok
+ integer :: i
+
+ ok=.true.
+ npfx=0
+ if(slash_index.le.4 .and. token_len-slash_index.lt.3) then
+ ok=.false.
+ return
+ endif
+ if(slash_index.gt.4 .and. token_len-slash_index.gt.3) then
+ ok=.false.
+ return
+ endif
+ do i=1,slash_index-1
+ if(index(PACK77_BASE36,token(i:i)).lt.1) then
+ ok=.false.
+ return
+ endif
+ enddo
+ do i=slash_index+1,token_len
+ if(index(PACK77_BASE36,token(i:i)).lt.1) then
+ ok=.false.
+ return
+ endif
+ enddo
+ if(slash_index.le.4) then
+ npfx=index(PACK77_BASE36,token(1:1))-1
+ if(slash_index.ge.3) npfx=36*npfx + index(PACK77_BASE36,token(2:2))-1
+ if(slash_index.eq.4) npfx=36*npfx + index(PACK77_BASE36,token(3:3))-1
+ else
+ if((token_len-slash_index).eq.1) &
+ npfx=index(PACK77_BASE36,token(slash_index+1:slash_index+1))-1
+ if((token_len-slash_index).eq.2) &
+ npfx=36*(index(PACK77_BASE36,token(slash_index+1:slash_index+1))-1) + &
+ index(PACK77_BASE36,token(slash_index+2:slash_index+2))-1
+ if((token_len-slash_index).eq.3) then
+ if(.not.pack77_is_digit_char(token(slash_index+3:slash_index+3))) then
+ ok=.false.
+ return
+ endif
+ npfx=36*10*(index(PACK77_BASE36,token(slash_index+1:slash_index+1))-1) + &
+ 10*(index(PACK77_BASE36,token(slash_index+2:slash_index+2))-1) + &
+ index(PACK77_BASE36,token(slash_index+3:slash_index+3))-1
+ endif
+ npfx=npfx + PACK77_WSPR_NZZZ
+ endif
+
+ return
+end function pack77_wspr_affix_index
+
+subroutine pack77_wspr_affix_text(npfx,cpfx,is_prefix,ok)
+ integer, intent(in) :: npfx
+ character(len=3), intent(out) :: cpfx
+ logical, intent(out) :: is_prefix,ok
+ integer :: n,i,j
+
+ n=npfx
+ cpfx=' '
+ ok=.true.
+ is_prefix=n.lt.PACK77_WSPR_NZZZ
+ if(is_prefix) then
+ do i=3,1,-1
+ j=mod(n,36)+1
+ cpfx(i:i)=PACK77_BASE36(j:j)
+ n=n/36
+ if(n.eq.0) exit
+ enddo
+ else
+ n=n-PACK77_WSPR_NZZZ
+ if(n.le.35) then
+ cpfx(1:1)=PACK77_BASE36(n+1:n+1)
+ else if(n.gt.35 .and. n.le.1295) then
+ cpfx(1:1)=PACK77_BASE36(n/36+1:n/36+1)
+ cpfx(2:2)=PACK77_BASE36(mod(n,36)+1:mod(n,36)+1)
+ else if(n.gt.1295 .and. n.le.12959) then
+ cpfx(1:1)=PACK77_BASE36(n/360+1:n/360+1)
+ cpfx(2:2)=PACK77_BASE36(mod(n/10,36)+1:mod(n/10,36)+1)
+ cpfx(3:3)=PACK77_BASE36(mod(n,10)+1:mod(n,10)+1)
+ else
+ ok=.false.
+ endif
+ endif
+
+ return
+end subroutine pack77_wspr_affix_text
+
+character(len=11) function pack77_type4_call_text_from_n58(n58) result(c11)
+ integer*8, intent(in) :: n58
+ integer*8 :: n
+ integer :: i,j
+
+ c11=' '
+ n=n58
+ do i=11,1,-1
+ j=mod(n,38_8)+1
+ c11(i:i)=PACK77_BASE38(j:j)
+ n=n/38
+ enddo
+
+ return
+end function pack77_type4_call_text_from_n58
+
+integer*8 function pack77_type4_n58_from_call_text(c11) result(n58)
+ character(len=*), intent(in) :: c11
+ integer :: i
+
+ n58=0_8
+ do i=1,11
+ n58=n58*38_8 + index(PACK77_BASE38,c11(i:i)) - 1
+ enddo
+
+ return
+end function pack77_type4_n58_from_call_text
+
+subroutine to_grid4(n,grid4,ok)
+ character*4 grid4
+ logical ok
+ integer :: n,j1,j2,j3,j4
+
+ ok=.false.
+ j1=n/(18*10*10)
+ if (j1.lt.0.or.j1.gt.17) goto 900
+ n=n-j1*18*10*10
+ j2=n/(10*10)
+ if (j2.lt.0.or.j2.gt.17) goto 900
+ n=n-j2*10*10
+ j3=n/10
+ if (j3.lt.0.or.j3.gt.9) goto 900
+ j4=n-j3*10
+ if (j4.lt.0.or.j4.gt.9) goto 900
+ grid4(1:1)=char(j1+ichar('A'))
+ grid4(2:2)=char(j2+ichar('A'))
+ grid4(3:3)=char(j3+ichar('0'))
+ grid4(4:4)=char(j4+ichar('0'))
+ ok=.true.
+
+900 return
+end subroutine to_grid4
+
+subroutine to_grid6(n,grid6,ok)
+ character*6 grid6
+ logical ok
+ integer :: n,j1,j2,j3,j4,j5,j6
+
+ ok=.false.
+ j1=n/(18*10*10*24*24)
+ if (j1.lt.0.or.j1.gt.17) goto 900
+ n=n-j1*18*10*10*24*24
+ j2=n/(10*10*24*24)
+ if (j2.lt.0.or.j2.gt.17) goto 900
+ n=n-j2*10*10*24*24
+ j3=n/(10*24*24)
+ if (j3.lt.0.or.j3.gt.9) goto 900
+ n=n-j3*10*24*24
+ j4=n/(24*24)
+ if (j4.lt.0.or.j4.gt.9) goto 900
+ n=n-j4*24*24
+ j5=n/24
+ if (j5.lt.0.or.j5.gt.23) goto 900
+ j6=n-j5*24
+ if (j6.lt.0.or.j6.gt.23) goto 900
+ grid6(1:1)=char(j1+ichar('A'))
+ grid6(2:2)=char(j2+ichar('A'))
+ grid6(3:3)=char(j3+ichar('0'))
+ grid6(4:4)=char(j4+ichar('0'))
+ grid6(5:5)=char(j5+ichar('A'))
+ grid6(6:6)=char(j6+ichar('A'))
+ ok=.true.
+
+900 return
+end subroutine to_grid6
+
+subroutine to_grid(n,grid6,ok)
+ ! 4-, or 6-character grid
+ character*6 grid6
+ logical ok
+ integer :: n,j1,j2,j3,j4,j5,j6
+
+ ok=.false.
+ j1=n/(18*10*10*25*25)
+ if (j1.lt.0.or.j1.gt.17) goto 900
+ n=n-j1*18*10*10*25*25
+ j2=n/(10*10*25*25)
+ if (j2.lt.0.or.j2.gt.17) goto 900
+ n=n-j2*10*10*25*25
+ j3=n/(10*25*25)
+ if (j3.lt.0.or.j3.gt.9) goto 900
+ n=n-j3*10*25*25
+ j4=n/(25*25)
+ if (j4.lt.0.or.j4.gt.9) goto 900
+ n=n-j4*25*25
+ j5=n/25
+ if (j5.lt.0.or.j5.gt.24) goto 900
+ j6=n-j5*25
+ if (j6.lt.0.or.j6.gt.24) goto 900
+ grid6=''
+ grid6(1:1)=char(j1+ichar('A'))
+ grid6(2:2)=char(j2+ichar('A'))
+ grid6(3:3)=char(j3+ichar('0'))
+ grid6(4:4)=char(j4+ichar('0'))
+ if (j5.ne.24.or.j6.ne.24) then
+ grid6(5:5)=char(j5+ichar('A'))
+ grid6(6:6)=char(j6+ichar('A'))
+ endif
+ ok=.true.
+
+900 return
+end subroutine to_grid
+
+logical function pack77_is_grid4(grid4) result(ok)
+ character(len=*), intent(in) :: grid4
+
+ ok=.false.
+ if(len(grid4).lt.4) return
+ if(len(trim(grid4)).ne.4) return
+ ok=grid4(1:1).ge.'A' .and. grid4(1:1).le.'R' .and. &
+ grid4(2:2).ge.'A' .and. grid4(2:2).le.'R' .and. &
+ grid4(3:3).ge.'0' .and. grid4(3:3).le.'9' .and. &
+ grid4(4:4).ge.'0' .and. grid4(4:4).le.'9'
+
+ return
+end function pack77_is_grid4
+
+logical function pack77_is_grid6(grid6,allow_grid4) result(ok)
+ character(len=*), intent(in) :: grid6
+ logical, intent(in) :: allow_grid4
+ integer :: ngrid
+
+ ok=.false.
+ if(len(grid6).lt.4) return
+ ngrid=len(trim(grid6))
+ if(ngrid.eq.4) then
+ ok=allow_grid4 .and. pack77_is_grid4(grid6(1:4))
+ return
+ endif
+ if(len(grid6).lt.6 .or. ngrid.ne.6) return
+ ok=pack77_is_grid4(grid6(1:4)) .and. &
+ grid6(5:5).ge.'A' .and. grid6(5:5).le.'X' .and. &
+ grid6(6:6).ge.'A' .and. grid6(6:6).le.'X'
+
+ return
+end function pack77_is_grid6
+
+integer function pack77_grid4_index(grid4) result(igrid4)
+ character(len=*), intent(in) :: grid4
+
+ igrid4=(ichar(grid4(1:1))-ichar('A'))*18*10*10 + &
+ (ichar(grid4(2:2))-ichar('A'))*10*10 + &
+ (ichar(grid4(3:3))-ichar('0'))*10 + &
+ (ichar(grid4(4:4))-ichar('0'))
+
+ return
+end function pack77_grid4_index
+
+integer function pack77_grid6_index(grid6) result(igrid6)
+ character(len=*), intent(in) :: grid6
+
+ igrid6=pack77_grid4_index(grid6(1:4))*24*24 + &
+ (ichar(grid6(5:5))-ichar('A'))*24 + &
+ (ichar(grid6(6:6))-ichar('A'))
+
+ return
+end function pack77_grid6_index
+
+integer function pack77_grid6_wspr_index(grid6) result(igrid6)
+ character(len=*), intent(in) :: grid6
+
+ igrid6=pack77_grid4_index(grid6(1:4))*25*25
+ if(grid6(5:6).eq.' ') then
+ igrid6=igrid6 + 24*25 + 24
+ else
+ igrid6=igrid6 + (ichar(grid6(5:5))-ichar('A'))*25 + &
+ (ichar(grid6(6:6))-ichar('A'))
+ endif
+
+ return
+end function pack77_grid6_wspr_index
+
+end module packjt77_grammar
diff --git a/lib/77bit/packjt77_schema.f90 b/lib/77bit/packjt77_schema.f90
new file mode 100644
index 00000000..cfa43687
--- /dev/null
+++ b/lib/77bit/packjt77_schema.f90
@@ -0,0 +1,871 @@
+module packjt77_schema
+
+ use, intrinsic :: iso_fortran_env, only: int64
+ implicit none
+
+ integer, parameter :: PACK77_SCHEMA_INT_KIND=int64
+ integer, parameter :: PACK77_MAX_SCHEMA_FIELDS=8
+ integer, parameter :: PACK77_FIELD_NAME_LEN=16
+ integer, parameter :: PACK77_SCHEMA_NAME_LEN=32
+
+ private :: NO_FIELD,put_int,get_int,begin_message,put_int_i4,put_int_i8, &
+ put_bits,get_int_i4,get_int_i8,get_bits,valid_field_bounds, &
+ encode_pack77_field_day,encode_pack77_type12,decode_pack77_field_day, &
+ decode_pack77_type12,require_int,pack77_binary_precondition, &
+ bits_are_binary
+
+ ! Schema bit ranges use Fortran string coordinates in the 77-character c77
+ ! payload: start_bit is 1-based and integer fields are encoded MSB-first.
+ type bit_field
+ character(len=PACK77_FIELD_NAME_LEN) :: name=''
+ integer :: start_bit=0
+ integer :: width=0
+ integer(kind=int64) :: min_value=0_int64
+ integer(kind=int64) :: max_value=-1_int64
+ logical :: bitstring=.false.
+ end type bit_field
+
+ type message_schema
+ integer :: i3=-1
+ integer :: n3=-1
+ character(len=PACK77_SCHEMA_NAME_LEN) :: name=''
+ integer :: nfields=0
+ type(bit_field) :: fields(PACK77_MAX_SCHEMA_FIELDS)
+ end type message_schema
+
+ type(bit_field), parameter :: NO_FIELD=bit_field('',0,0,0_int64,-1_int64,.false.)
+
+ interface put_int
+ module procedure put_int_i4
+ module procedure put_int_i8
+ end interface put_int
+
+ interface get_int
+ module procedure get_int_i4
+ module procedure get_int_i8
+ end interface get_int
+
+ type(message_schema), parameter :: PACK77_SCHEMA_FREE_TEXT=message_schema( &
+ 0,0,'free text',3,(/ &
+ bit_field('text_bits',1,71,0_int64,0_int64,.true.), &
+ bit_field('n3',72,3,0_int64,0_int64,.false.), &
+ bit_field('i3',75,3,0_int64,0_int64,.false.), &
+ NO_FIELD,NO_FIELD,NO_FIELD,NO_FIELD,NO_FIELD /))
+
+ type(message_schema), parameter :: PACK77_SCHEMA_TELEMETRY=message_schema( &
+ 0,5,'telemetry',5,(/ &
+ bit_field('ntel1',1,23,0_int64,8388607_int64,.false.), &
+ bit_field('ntel2',24,24,0_int64,16777215_int64,.false.), &
+ bit_field('ntel3',48,24,0_int64,16777215_int64,.false.), &
+ bit_field('n3',72,3,5_int64,5_int64,.false.), &
+ bit_field('i3',75,3,0_int64,0_int64,.false.), &
+ NO_FIELD,NO_FIELD,NO_FIELD /))
+
+ type(message_schema), parameter :: PACK77_SCHEMA_DXPEDITION=message_schema( &
+ 0,1,'dxpedition',6,(/ &
+ bit_field('n28a',1,28,0_int64,268435455_int64,.false.), &
+ bit_field('n28b',29,28,0_int64,268435455_int64,.false.), &
+ bit_field('n10',57,10,0_int64,1023_int64,.false.), &
+ bit_field('n5',67,5,0_int64,31_int64,.false.), &
+ bit_field('n3',72,3,1_int64,1_int64,.false.), &
+ bit_field('i3',75,3,0_int64,0_int64,.false.), &
+ NO_FIELD,NO_FIELD /))
+
+ type(message_schema), parameter :: PACK77_SCHEMA_FIELD_DAY_LOW=message_schema( &
+ 0,3,'field day low',8,(/ &
+ bit_field('n28a',1,28,0_int64,268435455_int64,.false.), &
+ bit_field('n28b',29,28,0_int64,268435455_int64,.false.), &
+ bit_field('ir',57,1,0_int64,1_int64,.false.), &
+ bit_field('intx',58,4,0_int64,15_int64,.false.), &
+ bit_field('nclass',62,3,0_int64,7_int64,.false.), &
+ bit_field('isec',65,7,0_int64,127_int64,.false.), &
+ bit_field('n3',72,3,3_int64,3_int64,.false.), &
+ bit_field('i3',75,3,0_int64,0_int64,.false.) /))
+
+ type(message_schema), parameter :: PACK77_SCHEMA_FIELD_DAY_HIGH=message_schema( &
+ 0,4,'field day high',8,(/ &
+ bit_field('n28a',1,28,0_int64,268435455_int64,.false.), &
+ bit_field('n28b',29,28,0_int64,268435455_int64,.false.), &
+ bit_field('ir',57,1,0_int64,1_int64,.false.), &
+ bit_field('intx',58,4,0_int64,15_int64,.false.), &
+ bit_field('nclass',62,3,0_int64,7_int64,.false.), &
+ bit_field('isec',65,7,0_int64,127_int64,.false.), &
+ bit_field('n3',72,3,4_int64,4_int64,.false.), &
+ bit_field('i3',75,3,0_int64,0_int64,.false.) /))
+
+ type(message_schema), parameter :: PACK77_SCHEMA_WSPR_TYPE1=message_schema( &
+ 0,6,'wspr type 1',8,(/ &
+ bit_field('n28',1,28,0_int64,268435455_int64,.false.), &
+ bit_field('igrid4',29,15,0_int64,32767_int64,.false.), &
+ ! idbm max 18 = nint(0.3*dBm) for dBm 0..60; range enforced here
+ bit_field('idbm',44,5,0_int64,18_int64,.false.), &
+ bit_field('j49',49,1,0_int64,0_int64,.false.), &
+ bit_field('j50',50,1,0_int64,0_int64,.false.), &
+ bit_field('pad',51,21,0_int64,0_int64,.false.), &
+ bit_field('n3',72,3,6_int64,6_int64,.false.), &
+ bit_field('i3',75,3,0_int64,0_int64,.false.) /))
+
+ type(message_schema), parameter :: PACK77_SCHEMA_WSPR_TYPE2=message_schema( &
+ 0,6,'wspr type 2',7,(/ &
+ bit_field('n28',1,28,0_int64,268435455_int64,.false.), &
+ bit_field('npfx',29,16,0_int64,65535_int64,.false.), &
+ ! idbm max 18 = nint(0.3*dBm) for dBm 0..60; range enforced here
+ bit_field('idbm',45,5,0_int64,18_int64,.false.), &
+ bit_field('j50',50,1,1_int64,1_int64,.false.), &
+ bit_field('pad',51,21,0_int64,0_int64,.false.), &
+ bit_field('n3',72,3,6_int64,6_int64,.false.), &
+ bit_field('i3',75,3,0_int64,0_int64,.false.), &
+ NO_FIELD /))
+
+ type(message_schema), parameter :: PACK77_SCHEMA_WSPR_TYPE3=message_schema( &
+ 0,6,'wspr type 3',6,(/ &
+ bit_field('n22',1,22,0_int64,4194303_int64,.false.), &
+ bit_field('igrid6',23,25,0_int64,33554431_int64,.false.), &
+ bit_field('selector',48,3,2_int64,2_int64,.false.), &
+ bit_field('pad',51,21,0_int64,0_int64,.false.), &
+ bit_field('n3',72,3,6_int64,6_int64,.false.), &
+ bit_field('i3',75,3,0_int64,0_int64,.false.), &
+ NO_FIELD,NO_FIELD /))
+
+ type(message_schema), parameter :: PACK77_SCHEMA_TYPE1=message_schema( &
+ 1,0,'type 1 standard',7,(/ &
+ bit_field('n28a',1,28,0_int64,268435455_int64,.false.), &
+ bit_field('ipa',29,1,0_int64,1_int64,.false.), &
+ bit_field('n28b',30,28,0_int64,268435455_int64,.false.), &
+ bit_field('ipb',58,1,0_int64,1_int64,.false.), &
+ bit_field('ir',59,1,0_int64,1_int64,.false.), &
+ bit_field('igrid4',60,15,0_int64,32767_int64,.false.), &
+ bit_field('i3',75,3,1_int64,1_int64,.false.), &
+ NO_FIELD /))
+
+ type(message_schema), parameter :: PACK77_SCHEMA_TYPE2=message_schema( &
+ 2,0,'type 2 portable',7,(/ &
+ bit_field('n28a',1,28,0_int64,268435455_int64,.false.), &
+ bit_field('ipa',29,1,0_int64,1_int64,.false.), &
+ bit_field('n28b',30,28,0_int64,268435455_int64,.false.), &
+ bit_field('ipb',58,1,0_int64,1_int64,.false.), &
+ bit_field('ir',59,1,0_int64,1_int64,.false.), &
+ bit_field('igrid4',60,15,0_int64,32767_int64,.false.), &
+ bit_field('i3',75,3,2_int64,2_int64,.false.), &
+ NO_FIELD /))
+
+ type(message_schema), parameter :: PACK77_SCHEMA_TYPE3=message_schema( &
+ 3,0,'type 3 rtty',7,(/ &
+ bit_field('itu',1,1,0_int64,1_int64,.false.), &
+ bit_field('n28a',2,28,0_int64,268435455_int64,.false.), &
+ bit_field('n28b',30,28,0_int64,268435455_int64,.false.), &
+ bit_field('ir',58,1,0_int64,1_int64,.false.), &
+ bit_field('irpt',59,3,0_int64,7_int64,.false.), &
+ bit_field('nexch',62,13,0_int64,8191_int64,.false.), &
+ bit_field('i3',75,3,3_int64,3_int64,.false.), &
+ NO_FIELD /))
+
+ type(message_schema), parameter :: PACK77_SCHEMA_TYPE4=message_schema( &
+ 4,0,'type 4 nonstandard',6,(/ &
+ bit_field('n12',1,12,0_int64,4095_int64,.false.), &
+ bit_field('n58',13,58,0_int64,288230376151711743_int64,.false.), &
+ bit_field('iflip',71,1,0_int64,1_int64,.false.), &
+ bit_field('nrpt',72,2,0_int64,3_int64,.false.), &
+ bit_field('icq',74,1,0_int64,1_int64,.false.), &
+ bit_field('i3',75,3,4_int64,4_int64,.false.), &
+ NO_FIELD,NO_FIELD /))
+
+ type(message_schema), parameter :: PACK77_SCHEMA_TYPE5=message_schema( &
+ 5,0,'type 5 eu vhf',7,(/ &
+ bit_field('n12',1,12,0_int64,4095_int64,.false.), &
+ bit_field('n22',13,22,0_int64,4194303_int64,.false.), &
+ bit_field('ir',35,1,0_int64,1_int64,.false.), &
+ bit_field('irpt',36,3,0_int64,7_int64,.false.), &
+ bit_field('iserial',39,11,1_int64,2047_int64,.false.), &
+ ! igrid6 max 18662399 = EU-VHF grid6 range, enforced here
+ ! (WSPR type3 igrid6 keeps the full 2^25-1 range)
+ bit_field('igrid6',50,25,0_int64,18662399_int64,.false.), &
+ bit_field('i3',75,3,5_int64,5_int64,.false.), &
+ NO_FIELD /))
+
+ type pack77_free_text_fields
+ character(len=71) :: text_bits=''
+ end type pack77_free_text_fields
+
+ type pack77_telemetry_fields
+ integer :: ntel1=0
+ integer :: ntel2=0
+ integer :: ntel3=0
+ end type pack77_telemetry_fields
+
+ type pack77_dxpedition_fields
+ integer :: n28a=0
+ integer :: n28b=0
+ integer :: n10=0
+ integer :: n5=0
+ end type pack77_dxpedition_fields
+
+ type pack77_field_day_fields
+ integer :: n28a=0
+ integer :: n28b=0
+ integer :: ir=0
+ integer :: intx=0
+ integer :: nclass=0
+ integer :: isec=0
+ end type pack77_field_day_fields
+
+ type pack77_wspr_type1_fields
+ integer :: n28=0
+ integer :: igrid4=0
+ integer :: idbm=0
+ end type pack77_wspr_type1_fields
+
+ type pack77_wspr_type2_fields
+ integer :: n28=0
+ integer :: npfx=0
+ integer :: idbm=0
+ end type pack77_wspr_type2_fields
+
+ type pack77_wspr_type3_fields
+ integer :: n22=0
+ integer :: igrid6=0
+ end type pack77_wspr_type3_fields
+
+ type pack77_type12_fields
+ integer :: n28a=0
+ integer :: ipa=0
+ integer :: n28b=0
+ integer :: ipb=0
+ integer :: ir=0
+ integer :: igrid4=0
+ end type pack77_type12_fields
+
+ type pack77_type3_fields
+ integer :: itu=0
+ integer :: n28a=0
+ integer :: n28b=0
+ integer :: ir=0
+ integer :: irpt=0
+ integer :: nexch=0
+ end type pack77_type3_fields
+
+ type pack77_type4_fields
+ integer :: n12=0
+ integer(kind=int64) :: n58=0_int64
+ integer :: iflip=0
+ integer :: nrpt=0
+ integer :: icq=0
+ end type pack77_type4_fields
+
+ type pack77_type5_fields
+ integer :: n12=0
+ integer :: n22=0
+ integer :: ir=0
+ integer :: irpt=0
+ integer :: iserial=0
+ integer :: igrid6=0
+ end type pack77_type5_fields
+contains
+
+
+ subroutine begin_message(c77,ok)
+ character(len=77), intent(out) :: c77
+ logical, intent(out) :: ok
+
+ c77=repeat('0',len(c77))
+ ok=.true.
+ end subroutine begin_message
+
+ subroutine put_int_i4(ok,c77,field,value)
+ logical, intent(inout) :: ok
+ character(len=77), intent(inout) :: c77
+ type(bit_field), intent(in) :: field
+ integer, intent(in) :: value
+
+ call put_int_i8(ok,c77,field,int(value,kind=int64))
+ end subroutine put_int_i4
+
+ subroutine put_int_i8(ok,c77,field,value)
+ logical, intent(inout) :: ok
+ character(len=77), intent(inout) :: c77
+ type(bit_field), intent(in) :: field
+ integer(kind=int64), intent(in) :: value
+ integer :: i
+ integer(kind=int64) :: place
+
+ if(.not.ok) return
+ ok=.false.
+ if(.not.valid_field_bounds(field,len(c77))) return
+ if(field%bitstring) return
+ if(value.lt.field%min_value .or. value.gt.field%max_value) return
+ do i=field%width,1,-1
+ place=2_int64**(field%width-i)
+ if(mod(value/place,2_int64).eq.1_int64) then
+ c77(field%start_bit+i-1:field%start_bit+i-1)='1'
+ else
+ c77(field%start_bit+i-1:field%start_bit+i-1)='0'
+ endif
+ enddo
+ ok=.true.
+ end subroutine put_int_i8
+
+ subroutine put_bits(ok,c77,field,bits)
+ logical, intent(inout) :: ok
+ character(len=77), intent(inout) :: c77
+ type(bit_field), intent(in) :: field
+ character(len=*), intent(in) :: bits
+ integer :: i
+
+ if(.not.ok) return
+ ok=.false.
+ if(.not.valid_field_bounds(field,len(c77))) return
+ if(.not.field%bitstring) return
+ if(len_trim(bits).ne.field%width) return
+ do i=1,field%width
+ if(bits(i:i).ne.'0' .and. bits(i:i).ne.'1') return
+ enddo
+ c77(field%start_bit:field%start_bit+field%width-1)=bits(1:field%width)
+ ok=.true.
+ end subroutine put_bits
+
+ subroutine get_int_i4(ok,c77,field,value)
+ logical, intent(inout) :: ok
+ character(len=77), intent(in) :: c77
+ type(bit_field), intent(in) :: field
+ integer, intent(out) :: value
+ integer(kind=int64) :: int64_value
+
+ value=0
+ call get_int_i8(ok,c77,field,int64_value)
+ if(ok) value=int(int64_value)
+ end subroutine get_int_i4
+
+ subroutine get_int_i8(ok,c77,field,value)
+ logical, intent(inout) :: ok
+ character(len=77), intent(in) :: c77
+ type(bit_field), intent(in) :: field
+ integer(kind=int64), intent(out) :: value
+ integer :: i
+
+ value=0_int64
+ if(.not.ok) return
+ ok=.false.
+ if(.not.valid_field_bounds(field,len(c77))) return
+ if(field%bitstring) return
+ do i=0,field%width-1
+ value=value*2_int64
+ if(c77(field%start_bit+i:field%start_bit+i).eq.'1') then
+ value=value+1_int64
+ else if(c77(field%start_bit+i:field%start_bit+i).ne.'0') then
+ return
+ endif
+ enddo
+ if(value.lt.field%min_value .or. value.gt.field%max_value) return
+ ok=.true.
+ end subroutine get_int_i8
+
+ subroutine get_bits(ok,c77,field,bits)
+ logical, intent(inout) :: ok
+ character(len=77), intent(in) :: c77
+ type(bit_field), intent(in) :: field
+ character(len=*), intent(out) :: bits
+
+ bits=''
+ if(.not.ok) return
+ ok=.false.
+ if(.not.valid_field_bounds(field,len(c77))) return
+ if(.not.field%bitstring) return
+ if(field%width.gt.len(bits)) return
+ if(.not.bits_are_binary(c77(field%start_bit:field%start_bit+field%width-1))) return
+ bits(1:field%width)=c77(field%start_bit:field%start_bit+field%width-1)
+ ok=.true.
+ end subroutine get_bits
+
+ logical function valid_field_bounds(field,nbits) result(ok)
+ type(bit_field), intent(in) :: field
+ integer, intent(in) :: nbits
+
+ ok=.false.
+ if(field%start_bit.lt.1 .or. field%width.lt.1) return
+ if(field%start_bit+field%width-1.gt.nbits) return
+ ok=.true.
+ end function valid_field_bounds
+
+ subroutine encode_pack77_free_text(text_bits,c77,ok)
+ character(len=*), intent(in) :: text_bits
+ character(len=77), intent(out) :: c77
+ logical, intent(out) :: ok
+ character(len=71) :: packed_text
+
+ call begin_message(c77,ok)
+ if(len(text_bits).ne.71) then
+ ok=.false.
+ return
+ endif
+ packed_text=text_bits
+ call put_bits(ok,c77,PACK77_SCHEMA_FREE_TEXT%fields(1),packed_text)
+ call put_int(ok,c77,PACK77_SCHEMA_FREE_TEXT%fields(2),0)
+ call put_int(ok,c77,PACK77_SCHEMA_FREE_TEXT%fields(3),0)
+ end subroutine encode_pack77_free_text
+
+ subroutine encode_pack77_telemetry(ntel1,ntel2,ntel3,c77,ok)
+ integer, intent(in) :: ntel1,ntel2,ntel3
+ character(len=77), intent(out) :: c77
+ logical, intent(out) :: ok
+
+ call begin_message(c77,ok)
+ call put_int(ok,c77,PACK77_SCHEMA_TELEMETRY%fields(1),ntel1)
+ call put_int(ok,c77,PACK77_SCHEMA_TELEMETRY%fields(2),ntel2)
+ call put_int(ok,c77,PACK77_SCHEMA_TELEMETRY%fields(3),ntel3)
+ call put_int(ok,c77,PACK77_SCHEMA_TELEMETRY%fields(4),5)
+ call put_int(ok,c77,PACK77_SCHEMA_TELEMETRY%fields(5),0)
+ end subroutine encode_pack77_telemetry
+
+ subroutine encode_pack77_dxpedition(n28a,n28b,n10,n5,c77,ok)
+ integer, intent(in) :: n28a,n28b,n10,n5
+ character(len=77), intent(out) :: c77
+ logical, intent(out) :: ok
+
+ call begin_message(c77,ok)
+ call put_int(ok,c77,PACK77_SCHEMA_DXPEDITION%fields(1),n28a)
+ call put_int(ok,c77,PACK77_SCHEMA_DXPEDITION%fields(2),n28b)
+ call put_int(ok,c77,PACK77_SCHEMA_DXPEDITION%fields(3),n10)
+ call put_int(ok,c77,PACK77_SCHEMA_DXPEDITION%fields(4),n5)
+ call put_int(ok,c77,PACK77_SCHEMA_DXPEDITION%fields(5),1)
+ call put_int(ok,c77,PACK77_SCHEMA_DXPEDITION%fields(6),0)
+ end subroutine encode_pack77_dxpedition
+
+ subroutine encode_pack77_field_day(schema,n28a,n28b,ir,intx,nclass,isec,c77,ok)
+ type(message_schema), intent(in) :: schema
+ integer, intent(in) :: n28a,n28b,ir,intx,nclass,isec
+ character(len=77), intent(out) :: c77
+ logical, intent(out) :: ok
+
+ call begin_message(c77,ok)
+ call put_int(ok,c77,schema%fields(1),n28a)
+ call put_int(ok,c77,schema%fields(2),n28b)
+ call put_int(ok,c77,schema%fields(3),ir)
+ call put_int(ok,c77,schema%fields(4),intx)
+ call put_int(ok,c77,schema%fields(5),nclass)
+ call put_int(ok,c77,schema%fields(6),isec)
+ call put_int(ok,c77,schema%fields(7),schema%n3)
+ call put_int(ok,c77,schema%fields(8),0)
+ end subroutine encode_pack77_field_day
+
+ subroutine encode_pack77_field_day_low(n28a,n28b,ir,intx,nclass,isec,c77,ok)
+ integer, intent(in) :: n28a,n28b,ir,intx,nclass,isec
+ character(len=77), intent(out) :: c77
+ logical, intent(out) :: ok
+
+ call encode_pack77_field_day(PACK77_SCHEMA_FIELD_DAY_LOW, &
+ n28a,n28b,ir,intx,nclass,isec,c77,ok)
+ end subroutine encode_pack77_field_day_low
+
+ subroutine encode_pack77_field_day_high(n28a,n28b,ir,intx,nclass,isec,c77,ok)
+ integer, intent(in) :: n28a,n28b,ir,intx,nclass,isec
+ character(len=77), intent(out) :: c77
+ logical, intent(out) :: ok
+
+ call encode_pack77_field_day(PACK77_SCHEMA_FIELD_DAY_HIGH, &
+ n28a,n28b,ir,intx,nclass,isec,c77,ok)
+ end subroutine encode_pack77_field_day_high
+
+ subroutine encode_pack77_wspr_type1(n28,igrid4,idbm,c77,ok)
+ integer, intent(in) :: n28,igrid4,idbm
+ character(len=77), intent(out) :: c77
+ logical, intent(out) :: ok
+
+ call begin_message(c77,ok)
+ call put_int(ok,c77,PACK77_SCHEMA_WSPR_TYPE1%fields(1),n28)
+ call put_int(ok,c77,PACK77_SCHEMA_WSPR_TYPE1%fields(2),igrid4)
+ call put_int(ok,c77,PACK77_SCHEMA_WSPR_TYPE1%fields(3),idbm)
+ call put_int(ok,c77,PACK77_SCHEMA_WSPR_TYPE1%fields(4),0)
+ call put_int(ok,c77,PACK77_SCHEMA_WSPR_TYPE1%fields(5),0)
+ call put_int(ok,c77,PACK77_SCHEMA_WSPR_TYPE1%fields(6),0)
+ call put_int(ok,c77,PACK77_SCHEMA_WSPR_TYPE1%fields(7),6)
+ call put_int(ok,c77,PACK77_SCHEMA_WSPR_TYPE1%fields(8),0)
+ end subroutine encode_pack77_wspr_type1
+
+ subroutine encode_pack77_wspr_type2(n28,npfx,idbm,c77,ok)
+ integer, intent(in) :: n28,npfx,idbm
+ character(len=77), intent(out) :: c77
+ logical, intent(out) :: ok
+
+ call begin_message(c77,ok)
+ call put_int(ok,c77,PACK77_SCHEMA_WSPR_TYPE2%fields(1),n28)
+ call put_int(ok,c77,PACK77_SCHEMA_WSPR_TYPE2%fields(2),npfx)
+ call put_int(ok,c77,PACK77_SCHEMA_WSPR_TYPE2%fields(3),idbm)
+ call put_int(ok,c77,PACK77_SCHEMA_WSPR_TYPE2%fields(4),1)
+ call put_int(ok,c77,PACK77_SCHEMA_WSPR_TYPE2%fields(5),0)
+ call put_int(ok,c77,PACK77_SCHEMA_WSPR_TYPE2%fields(6),6)
+ call put_int(ok,c77,PACK77_SCHEMA_WSPR_TYPE2%fields(7),0)
+ end subroutine encode_pack77_wspr_type2
+
+ subroutine encode_pack77_wspr_type3(n22,igrid6,c77,ok)
+ integer, intent(in) :: n22,igrid6
+ character(len=77), intent(out) :: c77
+ logical, intent(out) :: ok
+
+ call begin_message(c77,ok)
+ call put_int(ok,c77,PACK77_SCHEMA_WSPR_TYPE3%fields(1),n22)
+ call put_int(ok,c77,PACK77_SCHEMA_WSPR_TYPE3%fields(2),igrid6)
+ call put_int(ok,c77,PACK77_SCHEMA_WSPR_TYPE3%fields(3),2)
+ call put_int(ok,c77,PACK77_SCHEMA_WSPR_TYPE3%fields(4),0)
+ call put_int(ok,c77,PACK77_SCHEMA_WSPR_TYPE3%fields(5),6)
+ call put_int(ok,c77,PACK77_SCHEMA_WSPR_TYPE3%fields(6),0)
+ end subroutine encode_pack77_wspr_type3
+
+ subroutine encode_pack77_type12(schema,n28a,ipa,n28b,ipb,ir,igrid4,c77,ok)
+ type(message_schema), intent(in) :: schema
+ integer, intent(in) :: n28a,ipa,n28b,ipb,ir,igrid4
+ character(len=77), intent(out) :: c77
+ logical, intent(out) :: ok
+
+ call begin_message(c77,ok)
+ call put_int(ok,c77,schema%fields(1),n28a)
+ call put_int(ok,c77,schema%fields(2),ipa)
+ call put_int(ok,c77,schema%fields(3),n28b)
+ call put_int(ok,c77,schema%fields(4),ipb)
+ call put_int(ok,c77,schema%fields(5),ir)
+ call put_int(ok,c77,schema%fields(6),igrid4)
+ call put_int(ok,c77,schema%fields(7),schema%i3)
+ end subroutine encode_pack77_type12
+
+ subroutine encode_pack77_type1(n28a,ipa,n28b,ipb,ir,igrid4,c77,ok)
+ integer, intent(in) :: n28a,ipa,n28b,ipb,ir,igrid4
+ character(len=77), intent(out) :: c77
+ logical, intent(out) :: ok
+
+ call encode_pack77_type12(PACK77_SCHEMA_TYPE1, &
+ n28a,ipa,n28b,ipb,ir,igrid4,c77,ok)
+ end subroutine encode_pack77_type1
+
+ subroutine encode_pack77_type2(n28a,ipa,n28b,ipb,ir,igrid4,c77,ok)
+ integer, intent(in) :: n28a,ipa,n28b,ipb,ir,igrid4
+ character(len=77), intent(out) :: c77
+ logical, intent(out) :: ok
+
+ call encode_pack77_type12(PACK77_SCHEMA_TYPE2, &
+ n28a,ipa,n28b,ipb,ir,igrid4,c77,ok)
+ end subroutine encode_pack77_type2
+
+ subroutine encode_pack77_type3(itu,n28a,n28b,ir,irpt,nexch,c77,ok)
+ integer, intent(in) :: itu,n28a,n28b,ir,irpt,nexch
+ character(len=77), intent(out) :: c77
+ logical, intent(out) :: ok
+
+ call begin_message(c77,ok)
+ call put_int(ok,c77,PACK77_SCHEMA_TYPE3%fields(1),itu)
+ call put_int(ok,c77,PACK77_SCHEMA_TYPE3%fields(2),n28a)
+ call put_int(ok,c77,PACK77_SCHEMA_TYPE3%fields(3),n28b)
+ call put_int(ok,c77,PACK77_SCHEMA_TYPE3%fields(4),ir)
+ call put_int(ok,c77,PACK77_SCHEMA_TYPE3%fields(5),irpt)
+ call put_int(ok,c77,PACK77_SCHEMA_TYPE3%fields(6),nexch)
+ call put_int(ok,c77,PACK77_SCHEMA_TYPE3%fields(7),3)
+ end subroutine encode_pack77_type3
+
+ subroutine encode_pack77_type4(n12,n58,iflip,nrpt,icq,c77,ok)
+ integer, intent(in) :: n12,iflip,nrpt,icq
+ integer(kind=int64), intent(in) :: n58
+ character(len=77), intent(out) :: c77
+ logical, intent(out) :: ok
+
+ call begin_message(c77,ok)
+ call put_int(ok,c77,PACK77_SCHEMA_TYPE4%fields(1),n12)
+ call put_int(ok,c77,PACK77_SCHEMA_TYPE4%fields(2),n58)
+ call put_int(ok,c77,PACK77_SCHEMA_TYPE4%fields(3),iflip)
+ call put_int(ok,c77,PACK77_SCHEMA_TYPE4%fields(4),nrpt)
+ call put_int(ok,c77,PACK77_SCHEMA_TYPE4%fields(5),icq)
+ call put_int(ok,c77,PACK77_SCHEMA_TYPE4%fields(6),4)
+ end subroutine encode_pack77_type4
+
+ subroutine encode_pack77_type5(n12,n22,ir,irpt,iserial,igrid6,c77,ok)
+ integer, intent(in) :: n12,n22,ir,irpt,iserial,igrid6
+ character(len=77), intent(out) :: c77
+ logical, intent(out) :: ok
+
+ call begin_message(c77,ok)
+ call put_int(ok,c77,PACK77_SCHEMA_TYPE5%fields(1),n12)
+ call put_int(ok,c77,PACK77_SCHEMA_TYPE5%fields(2),n22)
+ call put_int(ok,c77,PACK77_SCHEMA_TYPE5%fields(3),ir)
+ call put_int(ok,c77,PACK77_SCHEMA_TYPE5%fields(4),irpt)
+ call put_int(ok,c77,PACK77_SCHEMA_TYPE5%fields(5),iserial)
+ call put_int(ok,c77,PACK77_SCHEMA_TYPE5%fields(6),igrid6)
+ call put_int(ok,c77,PACK77_SCHEMA_TYPE5%fields(7),5)
+ end subroutine encode_pack77_type5
+
+ subroutine decode_pack77_tag(c77,i3,n3,ok,binary_checked)
+ character(len=77), intent(in) :: c77
+ integer, intent(out) :: i3,n3
+ logical, intent(out) :: ok
+ logical, intent(in), optional :: binary_checked
+ integer(kind=int64) :: value
+
+ i3=-1
+ n3=-1
+ ok=pack77_binary_precondition(c77,binary_checked)
+ call get_int(ok,c77,bit_field('i3',75,3,0_int64,7_int64,.false.),value)
+ if(.not.ok) return
+ i3=int(value)
+ if(i3.eq.0) then
+ call get_int(ok,c77,bit_field('n3',72,3,0_int64,7_int64,.false.),value)
+ if(.not.ok) return
+ n3=int(value)
+ else
+ n3=0
+ endif
+ end subroutine decode_pack77_tag
+
+ subroutine decode_pack77_free_text(c77,fields,ok,binary_checked)
+ character(len=77), intent(in) :: c77
+ type(pack77_free_text_fields), intent(out) :: fields
+ logical, intent(out) :: ok
+ logical, intent(in), optional :: binary_checked
+
+ fields=pack77_free_text_fields()
+ ok=pack77_binary_precondition(c77,binary_checked)
+ call get_bits(ok,c77,PACK77_SCHEMA_FREE_TEXT%fields(1),fields%text_bits)
+ call require_int(ok,c77,PACK77_SCHEMA_FREE_TEXT%fields(2),0)
+ call require_int(ok,c77,PACK77_SCHEMA_FREE_TEXT%fields(3),0)
+ end subroutine decode_pack77_free_text
+
+ subroutine decode_pack77_telemetry(c77,fields,ok,binary_checked)
+ character(len=77), intent(in) :: c77
+ type(pack77_telemetry_fields), intent(out) :: fields
+ logical, intent(out) :: ok
+ logical, intent(in), optional :: binary_checked
+
+ fields=pack77_telemetry_fields()
+ ok=pack77_binary_precondition(c77,binary_checked)
+ call get_int(ok,c77,PACK77_SCHEMA_TELEMETRY%fields(1),fields%ntel1)
+ call get_int(ok,c77,PACK77_SCHEMA_TELEMETRY%fields(2),fields%ntel2)
+ call get_int(ok,c77,PACK77_SCHEMA_TELEMETRY%fields(3),fields%ntel3)
+ call require_int(ok,c77,PACK77_SCHEMA_TELEMETRY%fields(4),5)
+ call require_int(ok,c77,PACK77_SCHEMA_TELEMETRY%fields(5),0)
+ end subroutine decode_pack77_telemetry
+
+ subroutine decode_pack77_dxpedition(c77,fields,ok,binary_checked)
+ character(len=77), intent(in) :: c77
+ type(pack77_dxpedition_fields), intent(out) :: fields
+ logical, intent(out) :: ok
+ logical, intent(in), optional :: binary_checked
+
+ fields=pack77_dxpedition_fields()
+ ok=pack77_binary_precondition(c77,binary_checked)
+ call get_int(ok,c77,PACK77_SCHEMA_DXPEDITION%fields(1),fields%n28a)
+ call get_int(ok,c77,PACK77_SCHEMA_DXPEDITION%fields(2),fields%n28b)
+ call get_int(ok,c77,PACK77_SCHEMA_DXPEDITION%fields(3),fields%n10)
+ call get_int(ok,c77,PACK77_SCHEMA_DXPEDITION%fields(4),fields%n5)
+ call require_int(ok,c77,PACK77_SCHEMA_DXPEDITION%fields(5),1)
+ call require_int(ok,c77,PACK77_SCHEMA_DXPEDITION%fields(6),0)
+ end subroutine decode_pack77_dxpedition
+
+ subroutine decode_pack77_field_day_low(c77,fields,ok,binary_checked)
+ character(len=77), intent(in) :: c77
+ type(pack77_field_day_fields), intent(out) :: fields
+ logical, intent(out) :: ok
+ logical, intent(in), optional :: binary_checked
+
+ call decode_pack77_field_day(PACK77_SCHEMA_FIELD_DAY_LOW,c77,fields, &
+ ok,binary_checked)
+ end subroutine decode_pack77_field_day_low
+
+ subroutine decode_pack77_field_day_high(c77,fields,ok,binary_checked)
+ character(len=77), intent(in) :: c77
+ type(pack77_field_day_fields), intent(out) :: fields
+ logical, intent(out) :: ok
+ logical, intent(in), optional :: binary_checked
+
+ call decode_pack77_field_day(PACK77_SCHEMA_FIELD_DAY_HIGH,c77,fields, &
+ ok,binary_checked)
+ end subroutine decode_pack77_field_day_high
+
+ subroutine decode_pack77_wspr_type1(c77,fields,ok,binary_checked)
+ character(len=77), intent(in) :: c77
+ type(pack77_wspr_type1_fields), intent(out) :: fields
+ logical, intent(out) :: ok
+ logical, intent(in), optional :: binary_checked
+
+ fields=pack77_wspr_type1_fields()
+ ok=pack77_binary_precondition(c77,binary_checked)
+ call get_int(ok,c77,PACK77_SCHEMA_WSPR_TYPE1%fields(1),fields%n28)
+ call get_int(ok,c77,PACK77_SCHEMA_WSPR_TYPE1%fields(2),fields%igrid4)
+ call get_int(ok,c77,PACK77_SCHEMA_WSPR_TYPE1%fields(3),fields%idbm)
+ call require_int(ok,c77,PACK77_SCHEMA_WSPR_TYPE1%fields(4),0)
+ call require_int(ok,c77,PACK77_SCHEMA_WSPR_TYPE1%fields(5),0)
+ call require_int(ok,c77,PACK77_SCHEMA_WSPR_TYPE1%fields(6),0)
+ call require_int(ok,c77,PACK77_SCHEMA_WSPR_TYPE1%fields(7),6)
+ call require_int(ok,c77,PACK77_SCHEMA_WSPR_TYPE1%fields(8),0)
+ end subroutine decode_pack77_wspr_type1
+
+ subroutine decode_pack77_wspr_type2(c77,fields,ok,binary_checked)
+ character(len=77), intent(in) :: c77
+ type(pack77_wspr_type2_fields), intent(out) :: fields
+ logical, intent(out) :: ok
+ logical, intent(in), optional :: binary_checked
+
+ fields=pack77_wspr_type2_fields()
+ ok=pack77_binary_precondition(c77,binary_checked)
+ call get_int(ok,c77,PACK77_SCHEMA_WSPR_TYPE2%fields(1),fields%n28)
+ call get_int(ok,c77,PACK77_SCHEMA_WSPR_TYPE2%fields(2),fields%npfx)
+ call get_int(ok,c77,PACK77_SCHEMA_WSPR_TYPE2%fields(3),fields%idbm)
+ call require_int(ok,c77,PACK77_SCHEMA_WSPR_TYPE2%fields(4),1)
+ call require_int(ok,c77,PACK77_SCHEMA_WSPR_TYPE2%fields(5),0)
+ call require_int(ok,c77,PACK77_SCHEMA_WSPR_TYPE2%fields(6),6)
+ call require_int(ok,c77,PACK77_SCHEMA_WSPR_TYPE2%fields(7),0)
+ end subroutine decode_pack77_wspr_type2
+
+ subroutine decode_pack77_wspr_type3(c77,fields,ok,binary_checked)
+ character(len=77), intent(in) :: c77
+ type(pack77_wspr_type3_fields), intent(out) :: fields
+ logical, intent(out) :: ok
+ logical, intent(in), optional :: binary_checked
+
+ fields=pack77_wspr_type3_fields()
+ ok=pack77_binary_precondition(c77,binary_checked)
+ call get_int(ok,c77,PACK77_SCHEMA_WSPR_TYPE3%fields(1),fields%n22)
+ call get_int(ok,c77,PACK77_SCHEMA_WSPR_TYPE3%fields(2),fields%igrid6)
+ call require_int(ok,c77,PACK77_SCHEMA_WSPR_TYPE3%fields(3),2)
+ call require_int(ok,c77,PACK77_SCHEMA_WSPR_TYPE3%fields(4),0)
+ call require_int(ok,c77,PACK77_SCHEMA_WSPR_TYPE3%fields(5),6)
+ call require_int(ok,c77,PACK77_SCHEMA_WSPR_TYPE3%fields(6),0)
+ end subroutine decode_pack77_wspr_type3
+
+ subroutine decode_pack77_type1(c77,fields,ok,binary_checked)
+ character(len=77), intent(in) :: c77
+ type(pack77_type12_fields), intent(out) :: fields
+ logical, intent(out) :: ok
+ logical, intent(in), optional :: binary_checked
+
+ call decode_pack77_type12(PACK77_SCHEMA_TYPE1,c77,fields,ok,binary_checked)
+ end subroutine decode_pack77_type1
+
+ subroutine decode_pack77_type2(c77,fields,ok,binary_checked)
+ character(len=77), intent(in) :: c77
+ type(pack77_type12_fields), intent(out) :: fields
+ logical, intent(out) :: ok
+ logical, intent(in), optional :: binary_checked
+
+ call decode_pack77_type12(PACK77_SCHEMA_TYPE2,c77,fields,ok,binary_checked)
+ end subroutine decode_pack77_type2
+
+ subroutine decode_pack77_type3(c77,fields,ok,binary_checked)
+ character(len=77), intent(in) :: c77
+ type(pack77_type3_fields), intent(out) :: fields
+ logical, intent(out) :: ok
+ logical, intent(in), optional :: binary_checked
+
+ fields=pack77_type3_fields()
+ ok=pack77_binary_precondition(c77,binary_checked)
+ call get_int(ok,c77,PACK77_SCHEMA_TYPE3%fields(1),fields%itu)
+ call get_int(ok,c77,PACK77_SCHEMA_TYPE3%fields(2),fields%n28a)
+ call get_int(ok,c77,PACK77_SCHEMA_TYPE3%fields(3),fields%n28b)
+ call get_int(ok,c77,PACK77_SCHEMA_TYPE3%fields(4),fields%ir)
+ call get_int(ok,c77,PACK77_SCHEMA_TYPE3%fields(5),fields%irpt)
+ call get_int(ok,c77,PACK77_SCHEMA_TYPE3%fields(6),fields%nexch)
+ call require_int(ok,c77,PACK77_SCHEMA_TYPE3%fields(7),3)
+ end subroutine decode_pack77_type3
+
+ subroutine decode_pack77_type4(c77,fields,ok,binary_checked)
+ character(len=77), intent(in) :: c77
+ type(pack77_type4_fields), intent(out) :: fields
+ logical, intent(out) :: ok
+ logical, intent(in), optional :: binary_checked
+
+ fields=pack77_type4_fields()
+ ok=pack77_binary_precondition(c77,binary_checked)
+ call get_int(ok,c77,PACK77_SCHEMA_TYPE4%fields(1),fields%n12)
+ call get_int(ok,c77,PACK77_SCHEMA_TYPE4%fields(2),fields%n58)
+ call get_int(ok,c77,PACK77_SCHEMA_TYPE4%fields(3),fields%iflip)
+ call get_int(ok,c77,PACK77_SCHEMA_TYPE4%fields(4),fields%nrpt)
+ call get_int(ok,c77,PACK77_SCHEMA_TYPE4%fields(5),fields%icq)
+ call require_int(ok,c77,PACK77_SCHEMA_TYPE4%fields(6),4)
+ end subroutine decode_pack77_type4
+
+ subroutine decode_pack77_type5(c77,fields,ok,binary_checked)
+ character(len=77), intent(in) :: c77
+ type(pack77_type5_fields), intent(out) :: fields
+ logical, intent(out) :: ok
+ logical, intent(in), optional :: binary_checked
+
+ fields=pack77_type5_fields()
+ ok=pack77_binary_precondition(c77,binary_checked)
+ call get_int(ok,c77,PACK77_SCHEMA_TYPE5%fields(1),fields%n12)
+ call get_int(ok,c77,PACK77_SCHEMA_TYPE5%fields(2),fields%n22)
+ call get_int(ok,c77,PACK77_SCHEMA_TYPE5%fields(3),fields%ir)
+ call get_int(ok,c77,PACK77_SCHEMA_TYPE5%fields(4),fields%irpt)
+ call get_int(ok,c77,PACK77_SCHEMA_TYPE5%fields(5),fields%iserial)
+ call get_int(ok,c77,PACK77_SCHEMA_TYPE5%fields(6),fields%igrid6)
+ call require_int(ok,c77,PACK77_SCHEMA_TYPE5%fields(7),5)
+ end subroutine decode_pack77_type5
+
+ subroutine decode_pack77_field_day(schema,c77,fields,ok,binary_checked)
+ type(message_schema), intent(in) :: schema
+ character(len=77), intent(in) :: c77
+ type(pack77_field_day_fields), intent(out) :: fields
+ logical, intent(out) :: ok
+ logical, intent(in), optional :: binary_checked
+
+ fields=pack77_field_day_fields()
+ ok=pack77_binary_precondition(c77,binary_checked)
+ call get_int(ok,c77,schema%fields(1),fields%n28a)
+ call get_int(ok,c77,schema%fields(2),fields%n28b)
+ call get_int(ok,c77,schema%fields(3),fields%ir)
+ call get_int(ok,c77,schema%fields(4),fields%intx)
+ call get_int(ok,c77,schema%fields(5),fields%nclass)
+ call get_int(ok,c77,schema%fields(6),fields%isec)
+ call require_int(ok,c77,schema%fields(7),schema%n3)
+ call require_int(ok,c77,schema%fields(8),0)
+ end subroutine decode_pack77_field_day
+
+ subroutine decode_pack77_type12(schema,c77,fields,ok,binary_checked)
+ type(message_schema), intent(in) :: schema
+ character(len=77), intent(in) :: c77
+ type(pack77_type12_fields), intent(out) :: fields
+ logical, intent(out) :: ok
+ logical, intent(in), optional :: binary_checked
+
+ fields=pack77_type12_fields()
+ ok=pack77_binary_precondition(c77,binary_checked)
+ call get_int(ok,c77,schema%fields(1),fields%n28a)
+ call get_int(ok,c77,schema%fields(2),fields%ipa)
+ call get_int(ok,c77,schema%fields(3),fields%n28b)
+ call get_int(ok,c77,schema%fields(4),fields%ipb)
+ call get_int(ok,c77,schema%fields(5),fields%ir)
+ call get_int(ok,c77,schema%fields(6),fields%igrid4)
+ call require_int(ok,c77,schema%fields(7),schema%i3)
+ end subroutine decode_pack77_type12
+
+ subroutine require_int(ok,c77,field,expected)
+ logical, intent(inout) :: ok
+ character(len=77), intent(in) :: c77
+ type(bit_field), intent(in) :: field
+ integer, intent(in) :: expected
+ integer(kind=int64) :: value
+
+ call get_int(ok,c77,field,value)
+ if(ok) ok=value.eq.int(expected,kind=int64)
+ end subroutine require_int
+
+ logical function pack77_binary_precondition(c77,binary_checked) result(ok)
+ character(len=*), intent(in) :: c77
+ logical, intent(in), optional :: binary_checked
+
+ ok=.false.
+ if(present(binary_checked)) then
+ if(binary_checked) then
+ ! Caller asserts decode_pack77_tag has accepted this same c77.
+ ok=.true.
+ return
+ endif
+ endif
+ ok=bits_are_binary(c77)
+ end function pack77_binary_precondition
+
+ logical function bits_are_binary(c77) result(ok)
+ character(len=*), intent(in) :: c77
+ integer :: i
+
+ ok=.false.
+ do i=1,len(c77)
+ if(c77(i:i).ne.'0' .and. c77(i:i).ne.'1') return
+ enddo
+ ok=.true.
+ end function bits_are_binary
+
+end module packjt77_schema
diff --git a/lib/EchoCallSim.f90 b/lib/EchoCallSim.f90
index 224e68c7..e9b55b5a 100644
--- a/lib/EchoCallSim.f90
+++ b/lib/EchoCallSim.f90
@@ -4,13 +4,13 @@ program EchoCallSim
use wavhdr
parameter (NSPS=4096,NZ=3*12000)
- parameter (NMAX=6*NSPS) !Samples in .wav file, 2.2*12000
+ parameter (NMAX=6*NSPS) !Samples occupied by the signal
type(hdr) h !Header for .wav file
integer*2 iwave(NZ) !Generated waveform
integer itone(6) !Channel symbols, values 0-37
real*4 xnoise(NMAX) !Generated random noise
real*4 dat(NMAX) !Generated real data
- complex cdat(NMAX) !Generated complex waveform
+ complex cdat(NZ) !Generated full-length complex waveform
complex z
real*8 f0,dt,twopi,phi,dphi,fsample,freq
character callsign*6,fname*17,arg*8
@@ -46,7 +46,7 @@ program EchoCallSim
twopi=8.d0*atan(1.d0)
rms=100.
fsample=12000.d0 !Sample rate (Hz)
- npts=NMAX !Total samples in .wav file
+ npts=NMAX !Samples occupied by the signal
nfft=npts
nh=nfft/2
dt=1.d0/fsample !Sample interval (s)
@@ -61,8 +61,11 @@ program EchoCallSim
endif
bandwidth_ratio=2500.0/6000.0
- sig=sqrt(2*bandwidth_ratio)*10.0**(0.05*snrdb)
- if(snrdb.gt.90.0) sig=1.0
+ if(snrdb.ge.90.0) then
+ sig=1.0
+ else
+ sig=sqrt(2*bandwidth_ratio)*10.0**(0.05*snrdb)
+ endif
phi=0.d0
dphi=0.d0
@@ -80,12 +83,22 @@ program EchoCallSim
enddo
enddo
+ cdat(npts+1:)=0.
if(fspread.gt.0.0) call fspread_lorentz(cdat,fspread)
- dat=aimag(cdat) + xnoise !Add generated AWGN noise
- fac=32767.0
- if(snrdb.ge.90.0) iwave(1:npts)=nint(fac*dat(1:npts))
- if(snrdb.lt.90.0) iwave(1:npts)=nint(rms*dat(1:npts))
+ dat=aimag(cdat(1:npts)) + xnoise !Add generated AWGN noise
+ datpk=maxval(abs(dat))
+ fac=rms
+ if(datpk.gt.0.0) then
+ if(snrdb.ge.90.0) then
+ fac=32766.0/datpk
+ elseif(fac*datpk.gt.32766.0) then
+ fac=32766.0/datpk
+ write(*,'(a,i0,a)') 'Warning: normalized file ',ifile, &
+ ' to prevent 16-bit PCM overflow; absolute level was not preserved.'
+ endif
+ endif
+ iwave(1:npts)=nint(fac*dat(1:npts))
iwave(npts+1:)=0
nDop=nint(fdop)
@@ -101,7 +114,7 @@ program EchoCallSim
isec=mod(n,60)
write(fname,1102) ihr,imin,isec
1102 format('000000_',3i2.2,'.wav')
- open(10,file=trim(fname),access='stream',status='unknown')
+ open(10,file=trim(fname),access='stream',status='replace')
write(10) h,iwave !Save the .wav file
close(10)
@@ -111,5 +124,3 @@ program EchoCallSim
enddo
999 end program EchoCallSim
-
-
diff --git a/lib/addit.f90 b/lib/addit.f90
index 48fd8cd4..c3b948aa 100644
--- a/lib/addit.f90
+++ b/lib/addit.f90
@@ -44,6 +44,7 @@ subroutine addcw(icw,ncw,ifreq,sig,dat)
real x(60*12000)
real y(60*12000)
real*8 dt,twopi,phi,dphi,fsample,tdit,t
+ save s,x,y
wpm=25.0
nspd=nint(1.2*12000.0/wpm)
diff --git a/lib/afc9.f90 b/lib/afc9.f90
index dd106aa4..83647867 100644
--- a/lib/afc9.f90
+++ b/lib/afc9.f90
@@ -1,8 +1,8 @@
subroutine afc9(c3a,npts,fsample,a,syncpk)
- parameter (NZ2=1512)
- complex c3a(0:NZ2-1)
- complex c3(0:NZ2-1)
+ parameter (NZ3=1360)
+ complex c3a(0:NZ3-1)
+ complex c3(0:NZ3-1)
real a(3),deltaa(3)
a(1)=0. !f0
diff --git a/lib/allsim.f90 b/lib/allsim.f90
index 94a03ef4..5607c53b 100644
--- a/lib/allsim.f90
+++ b/lib/allsim.f90
@@ -45,7 +45,7 @@ program allsim
call sgran() !Seed C rand generator (used in gran)
h=default_header(12000,NMAX)
- open(10,file='000000_0000.wav',access='stream',status='unknown')
+ open(10,file='000000_0000.wav',access='stream',status='replace')
do i=1,NMAX !Generate gaussian noise
dat(i)=gran()
enddo
@@ -106,7 +106,7 @@ program allsim
endif
if(isig.eq.0 .or. isig.eq.9) then
- call genq65(msg37,0,msgsent37,itone,i3,n3)
+ call genq65(msg37,0,msgsent37,itone,i3,n3,0)
call addit(itone,12000,85,7200,2000,sig,dat) !9 Q65
endif
diff --git a/lib/astro.f90 b/lib/astro.f90
index ae2ad1f2..cb44433d 100644
--- a/lib/astro.f90
+++ b/lib/astro.f90
@@ -1,8 +1,10 @@
subroutine astro(nyear,month,nday,uth,freq8,Mygrid, &
NStation,MoonDX,AzSun,ElSun,AzMoon0,ElMoon0, &
ntsky,doppler00,doppler,dbMoon,RAMoon,DecMoon,HA,Dgrd,sd, &
- poloffset,xnr,day,lon,lat,LST,techo)
+ poloffset,xnr,day,lon,lat,LST,techo,ephemeris_result)
+ use jpl_ephemeris_status, only: EPHEMERIS_INVALID_INPUT, &
+ EPHEMERIS_UNAVAILABLE
! Computes astronomical quantities for display and tracking.
! NB: may want to smooth the Tsky map to 10 degrees or so.
@@ -10,6 +12,7 @@ subroutine astro(nyear,month,nday,uth,freq8,Mygrid, &
real*8 freq8
real LST
real lat,lon
+ integer ephemeris_result
integer*2 nt144(180)
! common/echo/xdop(2),techo,AzMoon,ElMoon,mjd
@@ -43,7 +46,31 @@ subroutine astro(nyear,month,nday,uth,freq8,Mygrid, &
AzSun,ElSun,mjd,day)
call MoonDopJPL(nyear,month,nday,uth,lon,lat,RAMoon,DecMoon, &
- LST,HA,AzMoon,ElMoon,vr,techo)
+ LST,HA,AzMoon,ElMoon,vr,techo,ephemeris_result)
+ if(ephemeris_result.eq.EPHEMERIS_INVALID_INPUT .or. &
+ ephemeris_result.eq.EPHEMERIS_UNAVAILABLE) then
+ AzSun=0.
+ ElSun=0.
+ AzMoon0=0.
+ ElMoon0=0.
+ ntsky=0
+ doppler00=0.
+ doppler=0.
+ dbMoon=0.
+ RAMoon=0.
+ DecMoon=0.
+ HA=0.
+ Dgrd=0.
+ sd=0.
+ poloffset=0.
+ xnr=0.
+ day=0.
+ lon=0.
+ lat=0.
+ LST=0.
+ techo=0.
+ return
+ endif
RAMoon=rad*RAMoon
DecMoon=rad*DecMoon
dist=2.99792458d5*techo/2.d0
diff --git a/lib/astro0.f90 b/lib/astro0.f90
index d852fbf3..207aa6a4 100644
--- a/lib/astro0.f90
+++ b/lib/astro0.f90
@@ -1,35 +1,63 @@
subroutine astro0(nyear,month,nday,uth8,freq8,mygrid,hisgrid, &
AzSun8,ElSun8,AzMoon8,ElMoon8,AzMoonB8,ElMoonB8,ntsky,ndop,ndop00, &
dbMoon8,RAMoon8,DecMoon8,HA8,Dgrd8,sd8,poloffset8,xnr8,dfdt,dfdt0, &
- width1,width2,xlst8,techo8)
+ width1,width2,xlst8,techo8,ephemeris_result)
+ use jpl_ephemeris_status, only: EPHEMERIS_JPL, &
+ EPHEMERIS_ANALYTIC_FALLBACK, EPHEMERIS_INVALID_INPUT, &
+ EPHEMERIS_UNAVAILABLE, jpl_reader_generation
parameter (DEGS=57.2957795130823d0)
- character*6 mygrid,hisgrid
+ character*6 mygrid,hisgrid,mygrid_calc,hisgrid_calc
+ character(len=6), parameter :: legacy_blank_grid='BB44mm'
real*8 AzSun8,ElSun8,AzMoon8,ElMoon8,AzMoonB8,ElMoonB8
real*8 dbMoon8,RAMoon8,DecMoon8,HA8,Dgrd8,xnr8,dfdt,dfdt0,dt
real*8 sd8,poloffset8,width1,width2,xlst8
real*8 uth8,techo8,freq8
real*8 xl,b
+ integer ephemeris_result,result_dx,result_self,last_result
+ integer last_reader_generation
common/librcom/xl(2),b(2)
common/echocom2/fspread_self,fspread_dx
data uth8z/0.d0/
+ data last_result/-1/
+ data last_reader_generation/-1/
save
uth=uth8
- call astro(nyear,month,nday,uth,freq8,hisgrid,2,1, &
+ mygrid_calc=mygrid
+ hisgrid_calc=hisgrid
+! Blank locators historically reduce to the same periodic position as BB44mm.
+ if(len_trim(mygrid_calc).eq.0) mygrid_calc=legacy_blank_grid
+ if(len_trim(hisgrid_calc).eq.0) hisgrid_calc=legacy_blank_grid
+
+ call astro(nyear,month,nday,uth,freq8,hisgrid_calc,2,1, &
AzSun,ElSun,AzMoon,ElMoon,ntsky,doppler00,doppler, &
dbMoon,RAMoon,DecMoon,HA,Dgrd,sd,poloffset,xnr, &
- day,xlon2,xlat2,xlst,techo)
+ day,xlon2,xlat2,xlst,techo,result_dx)
+ if(result_dx.eq.EPHEMERIS_INVALID_INPUT .or. &
+ result_dx.eq.EPHEMERIS_UNAVAILABLE) then
+ ephemeris_result=result_dx
+ go to 800
+ endif
AzMoonB8=AzMoon
ElMoonB8=ElMoon
xl2=xl(1)
xl2a=xl(2)
b2=b(1)
b2a=b(2)
- call astro(nyear,month,nday,uth,freq8,mygrid,1,1, &
+ call astro(nyear,month,nday,uth,freq8,mygrid_calc,1,1, &
AzSun,ElSun,AzMoon,ElMoon,ntsky,doppler00,doppler, &
dbMoon,RAMoon,DecMoon,HA,Dgrd,sd,poloffset,xnr, &
- day,xlon1,xlat1,xlst,techo)
+ day,xlon1,xlat1,xlst,techo,result_self)
+ if(result_self.eq.EPHEMERIS_INVALID_INPUT .or. &
+ result_self.eq.EPHEMERIS_UNAVAILABLE) then
+ ephemeris_result=result_self
+ go to 800
+ endif
+ ephemeris_result=EPHEMERIS_JPL
+ if(result_dx.eq.EPHEMERIS_ANALYTIC_FALLBACK .or. &
+ result_self.eq.EPHEMERIS_ANALYTIC_FALLBACK) &
+ ephemeris_result=EPHEMERIS_ANALYTIC_FALLBACK
xl1=xl(1)
xl1a=xl(2)
b1=b(1)
@@ -45,7 +73,10 @@ subroutine astro0(nyear,month,nday,uth8,freq8,mygrid,hisgrid, &
width1=0.5*6741*fghz*rate1
rate2=sqrt((dldt1+dldt2)**2 + (dbdt1+dbdt2)**2)
width2=0.5*6741*fghz*rate2
- if(hisgrid(1:4).eq.' ') width2=width1 !No hisgrid, use self width
+ if(hisgrid(1:4).eq.' ') then
+ width2=width1
+ xnr=0.
+ endif
fspread_self=width1 !Save for avecho()
fspread_dx=width2 !Save for avecho()
@@ -65,19 +96,53 @@ subroutine astro0(nyear,month,nday,uth8,freq8,mygrid,hisgrid, &
ndop=nint(doppler)
ndop00=nint(doppler00)
- if(uth8z.eq.0.d0) then
- uth8z=uth8-1.d0/3600.d0
- dopplerz=doppler
- doppler00z=doppler00
+ if(uth8z.eq.0.d0 .or. ephemeris_result.ne.last_result .or. &
+ jpl_reader_generation.ne.last_reader_generation) then
+ dfdt=0.d0
+ dfdt0=0.d0
+ else
+ dt=60.0*(uth8-uth8z)
+ if(dt.le.0) dt=1.d0/60.d0
+ dfdt=(doppler-dopplerz)/dt
+ dfdt0=(doppler00-doppler00z)/dt
endif
-
- dt=60.0*(uth8-uth8z)
- if(dt.le.0) dt=1.d0/60.d0
- dfdt=(doppler-dopplerz)/dt
- dfdt0=(doppler00-doppler00z)/dt
uth8z=uth8
dopplerz=doppler
doppler00z=doppler00
+ last_result=ephemeris_result
+ last_reader_generation=jpl_reader_generation
+
+ return
+800 uth8z=0.d0
+ dopplerz=0.0
+ doppler00z=0.0
+ last_result=-1
+ last_reader_generation=-1
+ fspread_self=0.0
+ fspread_dx=0.0
+ AzSun8=0.d0
+ ElSun8=0.d0
+ AzMoon8=0.d0
+ ElMoon8=0.d0
+ AzMoonB8=0.d0
+ ElMoonB8=0.d0
+ ntsky=0
+ ndop=0
+ ndop00=0
+ dbMoon8=0.d0
+ RAMoon8=0.d0
+ DecMoon8=0.d0
+ HA8=0.d0
+ Dgrd8=0.d0
+ sd8=0.d0
+ poloffset8=0.d0
+ xnr8=0.d0
+ dfdt=0.d0
+ dfdt0=0.d0
+ width1=0.d0
+ width2=0.d0
+ xlst8=0.d0
+ techo8=0.d0
return
end subroutine astro0
diff --git a/lib/astrosub.f90 b/lib/astrosub.f90
index 28eaa1ed..35437cc2 100644
--- a/lib/astrosub.f90
+++ b/lib/astrosub.f90
@@ -11,20 +11,24 @@ contains
subroutine astrosub(nyear,month,nday,uth8,freq8,mygrid_cp, &
hisgrid_cp,AzSun8,ElSun8,AzMoon8,ElMoon8,AzMoonB8,ElMoonB8, &
- ntsky,ndop,ndop00,RAMoon8,DecMoon8,Dgrd8,poloffset8,xnr8,extraazel,techo8,width1, &
- width2,bTx,AzElFileName_cp,jpleph_file_name_cp) &
+ ntsky,ndop,ndop00,RAMoon8,DecMoon8,Dgrd8,poloffset8,xnr8,extraazel, &
+ techo8,width1,width2,bTx,AzElFileName_cp,jpleph_file_name_cp, &
+ ephemeris_result) &
bind (C, name="astrosub")
use :: types, only: dp
- use :: C_interface_module, only: C_int, C_double, C_bool, C_ptr, C_string_value, assignment(=)
+ use :: jpl_ephemeris_status, only: EPHEMERIS_INVALID_INPUT, &
+ EPHEMERIS_UNAVAILABLE
+ use :: C_interface_module, only: C_int, C_double, C_bool, C_ptr, &
+ C_string_value, assignment(=)
integer(C_int), intent(in), value :: nyear, month, nday
- logical(C_int), value :: extraazel
+ logical(C_bool), intent(in), value :: extraazel
real(C_double), intent(in), value :: uth8, freq8
real(C_double), intent(out) :: AzSun8, ElSun8, AzMoon8, ElMoon8, AzMoonB8, &
ElMoonB8, Ramoon8, DecMoon8, Dgrd8, poloffset8, xnr8, techo8, width1, &
width2
- integer(C_int), intent(out) :: ntsky, ndop, ndop00
+ integer(C_int), intent(out) :: ntsky, ndop, ndop00, ephemeris_result
logical(C_bool), intent(in), value :: bTx
type(C_ptr), value, intent(in) :: mygrid_cp, hisgrid_cp, AzElFileName_cp, &
jpleph_file_name_cp
@@ -48,12 +52,13 @@ contains
hisgrid = hisgrid_cp
AzElFileName = C_string_value (AzElFileName_cp)
jpleph_file_name = jpleph_file_name_cp
-
call astro0(nyear,month,nday,uth8,freq8,mygrid,hisgrid, &
AzSun8,ElSun8,AzMoon8,ElMoon8,AzMoonB8,ElMoonB8,ntsky,ndop,ndop00, &
dbMoon8,RAMoon8,DecMoon8,HA8,Dgrd8,sd8,poloffset8,xnr8,dfdt,dfdt0, &
- width1,width2,xlst8,techo8)
+ width1,width2,xlst8,techo8,ephemeris_result)
+ if (ephemeris_result.eq.EPHEMERIS_INVALID_INPUT .or. &
+ ephemeris_result.eq.EPHEMERIS_UNAVAILABLE) go to 999
if (len_trim(AzElFileName) .eq. 0) go to 999
if(len(trim(hisgrid)).eq.0) then !If DX grid is blank, set these to zero:
AzMoonB8=0
diff --git a/lib/avecho.f90 b/lib/avecho.f90
index 7b68213f..bfa1be1c 100644
--- a/lib/avecho.f90
+++ b/lib/avecho.f90
@@ -1,4 +1,4 @@
-subroutine avecho(id2_0,ndop,nfrit,nauto,ndf,navg,nqual,f1,xlevel, &
+subroutine avecho(id2_0,ndop,nfrit,nauto,navg,nqual,f1,xlevel, &
snrdb,db_err,dfreq,width,bDiskData,bEchoCall,txcall,rxcall)
parameter (NTX=6*4096)
@@ -29,7 +29,8 @@ subroutine avecho(id2_0,ndop,nfrit,nauto,ndf,navg,nqual,f1,xlevel, &
data navg0/-1/
save dop0,navg0,sax,sbx
- if(ndf.eq.-999) stop !Silence compiler warning
+ rxcall=' '
+
if(bEchoCall .and. .not.bDiskData) then
! Calculate the transmitted tones for real-time Echo Call testing
call gen_echocall(txcall,itone4)
@@ -54,7 +55,7 @@ subroutine avecho(id2_0,ndop,nfrit,nauto,ndf,navg,nqual,f1,xlevel, &
endif
sq=sum(float(id2_0(16:NTX))**2)
- xlevel=10.0*log10(sq/(NTX-15))
+ xlevel=db(sq/(NTX-15))
if(navg.eq.1) nclearave=1
if(nclearave.ne.0) nsum=0
@@ -81,7 +82,6 @@ subroutine avecho(id2_0,ndop,nfrit,nauto,ndf,navg,nqual,f1,xlevel, &
! Shift all tone frequencies to 1500 Hz, returning modified data in id2
! and decoded message in rxcall.
- rxcall=' '
call decode_echo(id2,.false.,rxcall)
x(1:15)=0.
diff --git a/lib/blanker.f90 b/lib/blanker.f90
index fe43931b..ec94f0df 100644
--- a/lib/blanker.f90
+++ b/lib/blanker.f90
@@ -4,6 +4,7 @@ subroutine blanker(iwave,nz,ndropmax,npct,c_bigfft)
complex c_bigfft(0:nz/2)
integer hist(0:32768)
real fblank !Fraction of points to be blanked
+ save hist
fblank=0.01*npct
hist=0
diff --git a/lib/ccf2.f90 b/lib/ccf2.f90
index 8e1f6cf4..c84fc240 100644
--- a/lib/ccf2.f90
+++ b/lib/ccf2.f90
@@ -41,7 +41,7 @@ subroutine ccf2(ss,nz,nflip,ccfbest,xlagpk)
xlagpk=lagpk
endif
enddo
- if( lagpk.gt.-LAGMAX .and. lagpk.lt.LAGMAX) then
+ if( lagpk.gt.LAGMIN .and. lagpk.lt.LAGMAX) then
call peakup(ccf(lagpk-1),ccf(lagpk),ccf(lagpk+1),dx)
xlagpk=lagpk+dx
endif
diff --git a/lib/cwsim.f90 b/lib/cwsim.f90
index 92300b72..3c36a820 100644
--- a/lib/cwsim.f90
+++ b/lib/cwsim.f90
@@ -3,6 +3,7 @@ program cwsim
! Generate simulated audio for a CW message sent repeatedly for 60 seconds
use wavhdr
+ use morse_encoder, only: encode_morse
parameter (NMAX=60*12000)
type(hdr) h !Header for the .wav file
integer*2 iwave(NMAX) !Generated waveform (no noise)
@@ -33,19 +34,23 @@ program cwsim
call getarg(6,arg)
read(arg,*) snrdb !S/N in dB (2500 hz reference BW)
+ call encode_morse(trim(message),icw,ncw)
+ if(ncw.eq.0) then
+ print*,'Error: message contains unsupported Morse characters'
+ stop 1
+ endif
+
rms=500.0
bandwidth_ratio=2500.0/6000.0
sig=sqrt(2*bandwidth_ratio)*10.0**(0.05*snrdb)
twopi=8.0*atan(1.0)
h=default_header(12000,NMAX)
- open(10,file='000000_0000.wav',access='stream',status='unknown')
+ open(10,file='000000_0000.wav',access='stream',status='replace')
do i=1,NMAX !Generate gaussian noise
xnoise(i)=gran()
enddo
- itone=0
- call morse(message,icw,ncw)
call cwsig(icw,ncw,ifreq,wpm,sig,cdat)
nfft=NMAX
@@ -112,6 +117,7 @@ subroutine cwsig(icw,ncw,ifreq,wpm,sig,cdat)
complex z(NMAX)
real x(NMAX)
real y(NMAX)
+ save z,x,y !Keep these big arrays off the stack
real*8 dt,twopi,phi,dphi,fsample,tdit,t
nspd=nint(1.2*12000.0/wpm)
@@ -145,91 +151,3 @@ subroutine cwsig(icw,ncw,ifreq,wpm,sig,cdat)
return
end subroutine cwsig
-
-subroutine morse(msg,idat,n)
-
-! Convert ascii message to a Morse code bit string.
-! Dash = 3 dots
-! Space between dots, dashes = 1 dot
-! Space between letters = 3 dots
-! Space between words = 7 dots
-
- character*(*) msg
- integer idat(500)
- integer*1 ic(21,38)
- data ic/ &
- 1,1,1,0,1,1,1,0,1,1,1,0,1,1,1,0,1,1,1,0,20, &
- 1,0,1,1,1,0,1,1,1,0,1,1,1,0,1,1,1,0,0,0,18, &
- 1,0,1,0,1,1,1,0,1,1,1,0,1,1,1,0,0,0,0,0,16, &
- 1,0,1,0,1,0,1,1,1,0,1,1,1,0,0,0,0,0,0,0,14, &
- 1,0,1,0,1,0,1,0,1,1,1,0,0,0,0,0,0,0,0,0,12, &
- 1,0,1,0,1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,10, &
- 1,1,1,0,1,0,1,0,1,0,1,0,0,0,0,0,0,0,0,0,12, &
- 1,1,1,0,1,1,1,0,1,0,1,0,1,0,0,0,0,0,0,0,14, &
- 1,1,1,0,1,1,1,0,1,1,1,0,1,0,1,0,0,0,0,0,16, &
- 1,1,1,0,1,1,1,0,1,1,1,0,1,1,1,0,1,0,0,0,18, &
- 1,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 6, &
- 1,1,1,0,1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,10, &
- 1,1,1,0,1,0,1,1,1,0,1,0,0,0,0,0,0,0,0,0,12, &
- 1,1,1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0, 8, &
- 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2, &
- 1,0,1,0,1,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0,10, &
- 1,1,1,0,1,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0,10, &
- 1,0,1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0, 8, &
- 1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 4, &
- 1,0,1,1,1,0,1,1,1,0,1,1,1,0,0,0,0,0,0,0,14, &
- 1,1,1,0,1,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,10, &
- 1,0,1,1,1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,10, &
- 1,1,1,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0, 8, &
- 1,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 6, &
- 1,1,1,0,1,1,1,0,1,1,1,0,0,0,0,0,0,0,0,0,12, &
- 1,0,1,1,1,0,1,1,1,0,1,0,0,0,0,0,0,0,0,0,12, &
- 1,1,1,0,1,1,1,0,1,0,1,1,1,0,0,0,0,0,0,0,14, &
- 1,0,1,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0, 8, &
- 1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 6, &
- 1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 4, &
- 1,0,1,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0, 8, &
- 1,0,1,0,1,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,10, &
- 1,0,1,1,1,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,10, &
- 1,1,1,0,1,0,1,0,1,1,1,0,0,0,0,0,0,0,0,0,12, &
- 1,1,1,0,1,0,1,1,1,0,1,1,1,0,0,0,0,0,0,0,14, &
- 1,1,1,0,1,1,1,0,1,0,1,0,0,0,0,0,0,0,0,0,12, &
- 1,1,1,0,1,0,1,0,1,1,1,0,1,0,0,0,0,0,0,0,14, &
- 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2/ !Incremental word space
- save
-
- msglen=len(trim(msg))
- idat=0
- n=6
- do k=1,msglen
- jj=ichar(msg(k:k))
- if(jj.ge.97 .and. jj.le.122) jj=jj-32 !Convert lower to upper case
- if(jj.ge.48 .and. jj.le.57) j=jj-48 !Numbers
- if(jj.ge.65 .and. jj.le.90) j=jj-55 !Letters
- if(jj.eq.47) j=36 !Slash (/)
- if(jj.eq.32) j=37 !Word space
- j=j+1
-
-! Insert this character
- nmax=ic(21,j)
- if (n + nmax + 4 .gt. size (idat)) exit
- do i=1,nmax
- n=n+1
- idat(n)=ic(i,j)
- enddo
-
-! Insert character space of 2 dit lengths:
- n=n+1
- idat(n)=0
- n=n+1
- idat(n)=0
- enddo
-
-! Insert word space at end of message
- do j=1,4
- n=n+1
- idat(n)=0
- enddo
-
- return
-end subroutine morse
diff --git a/lib/decode_completion.f90 b/lib/decode_completion.f90
new file mode 100644
index 00000000..da96872c
--- /dev/null
+++ b/lib/decode_completion.f90
@@ -0,0 +1,90 @@
+module decode_completion_module
+ use iso_fortran_env, only: int64
+ use decoder_ipc_atomic, only: decoder_ipc_progress_report
+ implicit none
+
+ private
+ public :: decode_completion_result
+ public :: reset_decode_completion
+ public :: set_decode_completion
+ public :: write_decode_completion
+ public :: write_decode_progress
+
+ type :: decode_completion_result
+ logical :: available = .false.
+ integer :: synchronized = 0
+ integer :: decoded = 0
+ integer :: average = 0
+ end type decode_completion_result
+
+ integer, save :: progress_thread_generation = 0
+ integer, save :: progress_thread_calls = 0
+ integer(int64), save :: progress_thread_count = 0_int64
+ integer(int64), save :: progress_thread_rate = 0_int64
+!$omp threadprivate(progress_thread_generation, progress_thread_calls, &
+!$omp& progress_thread_count, progress_thread_rate)
+
+contains
+
+ subroutine reset_decode_completion(completion)
+ type(decode_completion_result), intent(out) :: completion
+
+ completion%available = .false.
+ completion%synchronized = 0
+ completion%decoded = 0
+ completion%average = 0
+ end subroutine reset_decode_completion
+
+ subroutine set_decode_completion(completion, synchronized, decoded, average)
+ type(decode_completion_result), intent(out) :: completion
+ integer, intent(in) :: synchronized, decoded, average
+
+ completion%available = .true.
+ completion%synchronized = synchronized
+ completion%decoded = decoded
+ completion%average = average
+ end subroutine set_decode_completion
+
+ subroutine write_decode_completion(completion, generation)
+ type(decode_completion_result), intent(in) :: completion
+ integer, intent(in), optional :: generation
+
+ if (.not. completion%available) return
+ if (present(generation)) then
+ write(*,1001) completion%synchronized, completion%decoded, &
+ completion%average, generation
+1001 format('<DecodeFinished>',2i4,i9,' gen=',i0)
+ else
+ write(*,1000) completion%synchronized, completion%decoded, &
+ completion%average
+1000 format('<DecodeFinished>',2i4,i9)
+ end if
+ end subroutine write_decode_completion
+
+ subroutine write_decode_progress(generation)
+ integer, intent(in) :: generation
+ integer(int64) :: count, count_max, elapsed, rate
+
+ if (generation <= 0) return
+ if (generation == progress_thread_generation) then
+ progress_thread_calls = progress_thread_calls + 1
+ if (progress_thread_calls < 32) return
+ end if
+ progress_thread_calls = 0
+ call system_clock(count, rate, count_max)
+ if (generation == progress_thread_generation .and. &
+ rate == progress_thread_rate .and. rate > 0_int64) then
+ if (count >= progress_thread_count) then
+ elapsed = count - progress_thread_count
+ else
+ elapsed = count_max - progress_thread_count + count + 1_int64
+ end if
+ if (elapsed < max(1_int64, rate)) return
+ end if
+ progress_thread_generation = generation
+ progress_thread_count = count
+ progress_thread_rate = rate
+ call decoder_ipc_progress_report(generation)
+ end subroutine write_decode_progress
+
+end module decode_completion_module
diff --git a/lib/decode_echo.f90 b/lib/decode_echo.f90
index d2ebe71d..7bf30f6d 100644
--- a/lib/decode_echo.f90
+++ b/lib/decode_echo.f90
@@ -15,7 +15,7 @@ subroutine decode_echo(id2,searching,rxcall)
complex c2(0:NZ) !Analytic data with shifted tone freqs
character*6 rxcall !The recovered callsign
real s(0:NSPS-1) !Spectrum for one received character
- real p(0:NSPS-1,6) !Summed spectra for all six received characters
+ real, save :: p(0:NSPS-1,6)=0. !Summed spectra for six characters
real a(3)
character*37 c
common/echocom/nclearave,nsum,blue(4096),red(4096)
diff --git a/lib/decode_msk144.f90 b/lib/decode_msk144.f90
index 17110cf4..513cc342 100644
--- a/lib/decode_msk144.f90
+++ b/lib/decode_msk144.f90
@@ -1,4 +1,8 @@
-subroutine decode_msk144(audio_samples, params, data_dir)
+subroutine decode_msk144_core(audio_samples, params, data_dir, completion)
+ use streaming_emit, only: streaming_emit_enabled, &
+ streaming_emit_decode
+ use decode_completion_module, only: decode_completion_result, &
+ reset_decode_completion, set_decode_completion
include 'jt9com.f90'
! constants
@@ -11,6 +15,7 @@ subroutine decode_msk144(audio_samples, params, data_dir)
integer*2 audio_samples(NMAX)
type(params_block) :: params
character(len = 500) :: data_dir
+ type(decode_completion_result), intent(out) :: completion
! parameters of mskrtd
integer*2 :: buffer(BLOCK_SIZE)
@@ -26,7 +31,10 @@ subroutine decode_msk144(audio_samples, params, data_dir)
! local variables
integer :: sample_count
integer :: position
- integer :: message_count = 0
+ integer :: message_count
+
+ call reset_decode_completion(completion)
+ message_count = 0
! decode in 0.3s blocks
@@ -43,15 +51,60 @@ subroutine decode_msk144(audio_samples, params, data_dir)
if (line(1:1) .ne. char(0)) then
line = line(1:index(line, char(0))-1)
- write(*, 1001) line
+ if (streaming_emit_enabled()) then
+ call emit_msk144_line(line)
+ else
+ write(*, 1001) line
+ end if
1001 format(a80)
message_count = message_count + 1;
end if
end do
- if (.not. params%ndiskdat) then
- write(*, 1002) 0, message_count, 0
- 1002 format('<DecodeFinished>', 2i4, i9)
- end if
+ call set_decode_completion(completion, 0, message_count, 0)
+
+contains
+
+ ! Parse the 80-char mskrtd line and emit it as NDJSON. mskrtd's format
+ ! mirrors the FT8/FT4/Q65 emit shape:
+ ! cols 1-6: HHMMSS (i6.6)
+ ! cols 7-10: snr (i4)
+ ! cols 11-15: dt (f5.1)
+ ! cols 16-20: freq (i5)
+ ! col 22: '&' (mode separator)
+ ! cols 24-60: message (a37, trimmed)
+ subroutine emit_msk144_line(line_in)
+ character(len=*), intent(in) :: line_in
+ integer :: nutc_l, snr_l, freq_l, ios_l
+ real :: dt_l
+ character(len=37) :: msg_l
+ read(line_in, '(i6,i4,f5.1,i5,1x,1x,1x,a37)', &
+ iostat=ios_l) nutc_l, snr_l, dt_l, freq_l, msg_l
+ if (ios_l /= 0) return ! parse failure: silently drop
+ call streaming_emit_decode("MSK144", nutc_l, snr_l, dt_l, freq_l, &
+ adjustl(msg_l))
+ end subroutine emit_msk144_line
+
+end subroutine decode_msk144_core
+
+subroutine decode_msk144(audio_samples, params, data_dir)
+ use streaming_emit, only: streaming_emit_enabled, &
+ streaming_emit_decode_finished
+ use decode_completion_module, only: decode_completion_result, &
+ write_decode_completion
-end subroutine decode_msk144 \ No newline at end of file
+ include 'jt9com.f90'
+
+ integer*2 audio_samples(NMAX)
+ type(params_block) :: params
+ character(len = 500) :: data_dir
+ type(decode_completion_result) :: completion
+
+ call decode_msk144_core(audio_samples, params, data_dir, completion)
+ if (streaming_emit_enabled()) then
+ call streaming_emit_decode_finished(params%nutc)
+ else if (.not. params%ndiskdat) then
+ call write_decode_completion(completion)
+ call flush(6)
+ end if
+end subroutine decode_msk144
diff --git a/lib/decoder.f90 b/lib/decoder.f90
index 6d8e2fe0..d588ffa5 100644
--- a/lib/decoder.f90
+++ b/lib/decoder.f90
@@ -1,4 +1,4 @@
-subroutine multimode_decoder(ss,id2,params,nfsample)
+subroutine multimode_decoder_core(ss,id2,params,nfsample,completion,progress_generation)
!$ use omp_lib
use prog_args
@@ -7,10 +7,23 @@ subroutine multimode_decoder(ss,id2,params,nfsample)
use jt65_decode
use jt9_decode
use ft8_decode
+ use ft8_decode_ranges, only: max_ft8_decode_ranges, partition_ft8_decode_range
+ use ft8_mtd_residual, only: mtd_prepare,mtd_finish,mtd_worker_residual, &
+ mtd_worker_spectrum
use ft8_decodevar
use ft4_decode
use fst4_decode
use q65_decode
+ use decoder_callbacks, only: decoder_callback_context, &
+ counting_jt4_decoder, counting_jt65_decoder, counting_jt9_decoder, &
+ counting_ft8_decoder, counting_ft8_decodervar, counting_ft4_decoder, &
+ counting_fst4_decoder, counting_q65_decoder, ft8_decodedvar, &
+ ft8_decoded, ft4_decoded, fst4_decoded, q65_decoded, jt4_decoded, &
+ jt4_average, jt65_decoded, jt9_decoded
+ use streaming_emit, only: streaming_emit_enabled, &
+ streaming_emit_decode
+ use decode_completion_module, only: decode_completion_result, &
+ reset_decode_completion, set_decode_completion, write_decode_progress
!ft8md added 3 uses below
use ft8_mod1, only : ndecodes,allmessages,allsnrs,allfreq,mycall12_0, &
@@ -18,56 +31,41 @@ subroutine multimode_decoder(ss,id2,params,nfsample)
lqsomsgdcd,mycalllen1,msgroot,msgrootlen,lapmyc,sumxdtt,avexdt, &
nfawide,nfbwide,mycall,hiscall,lhound,mybcall,hisbcall,lenabledxcsearch, &
lwidedxcsearch,hisgrid4,lmultinst,dd8,nft8cycles,lskiptx1,ncandallthr, &
- nincallthr,incall,msgincall,xdtincall,maskincallthr,ltxing,hisgrid
-
- use packjt77, only : lcommonft8b,ihash22var,calls12var,calls22var
+ nincallthr,incall,msgincall,xdtincall,maskincallthr,ltxing,hisgrid, &
+ lastrxmsg,lasthcall
include 'jt9com.f90'
- include 'timer_common.inc'
-
- type, extends(jt4_decoder) :: counting_jt4_decoder
- integer :: decoded
- end type counting_jt4_decoder
-
- type, extends(jt65_decoder) :: counting_jt65_decoder
- integer :: decoded
- end type counting_jt65_decoder
-
- type, extends(jt9_decoder) :: counting_jt9_decoder
- integer :: decoded
- end type counting_jt9_decoder
-
- type, extends(ft8_decoder) :: counting_ft8_decoder
- integer :: decoded
- end type counting_ft8_decoder
-
- type, extends(ft8_decodervar) :: counting_ft8_decodervar
- integer :: decodedvar
- real :: xdtt(200)
- end type counting_ft8_decodervar
-
- type, extends(ft4_decoder) :: counting_ft4_decoder
- integer :: decoded
- end type counting_ft4_decoder
- type, extends(fst4_decoder) :: counting_fst4_decoder
- integer :: decoded
- end type counting_fst4_decoder
-
- type, extends(q65_decoder) :: counting_q65_decoder
- integer :: decoded
- end type counting_q65_decoder
+ interface
+ subroutine wsjt_tsan_acquire_decoder_section_primary() bind(C)
+ end subroutine wsjt_tsan_acquire_decoder_section_primary
+ subroutine wsjt_tsan_release_decoder_section_primary() bind(C)
+ end subroutine wsjt_tsan_release_decoder_section_primary
+ subroutine wsjt_tsan_acquire_decoder_section_secondary() bind(C)
+ end subroutine wsjt_tsan_acquire_decoder_section_secondary
+ subroutine wsjt_tsan_release_decoder_section_secondary() bind(C)
+ end subroutine wsjt_tsan_release_decoder_section_secondary
+ end interface
logical first,firstsd !ft8md
logical(1) lhoundprev !ft8md
integer nutc,ndelay
+ integer :: ft8_range_low(max_ft8_decode_ranges)
+ integer :: ft8_range_high(max_ft8_decode_ranges)
+ integer :: ft8_range_count
+ integer :: requested_threads
+ integer :: nthr
+ integer, intent(in) :: progress_generation
+ integer :: active_progress_generation
type(params_block) :: params
+ type(decode_completion_result), intent(out) :: completion
+ type(decoder_callback_context) :: callback_context
data ndelay/0/
data first/.true./ !ft8md
data firstsd/.true./ !ft8md
data lhoundprev/.false./ !ft8md
real ss(184,NSMAX)
- logical baddata,newdat65,newdat9,single_decode,bVHF,bad0,newdat,ex
+ logical baddata,newdat65,newdat9,single_decode,bVHF,q65_pileup,bad0,newdat,ex
logical lprinthash22
integer*2 id2(NTMAX*12000)
integer nqf(20)
@@ -76,7 +74,6 @@ subroutine multimode_decoder(ss,id2,params,nfsample)
!character(len=12) :: mycall, hiscall !ft8md
character(len=6) :: mygrid!, hisgrid !ft8md
character*60 line
- character*37 msg37
data ndec8/0/,ntr0/-1/
save
type(counting_jt4_decoder) :: my_jt4
@@ -88,6 +85,22 @@ subroutine multimode_decoder(ss,id2,params,nfsample)
type(counting_fst4_decoder) :: my_fst4
type(counting_q65_decoder) :: my_q65
+ call reset_decode_completion(completion)
+ active_progress_generation=progress_generation
+
+ my_jt4%decoded = 0
+ my_jt65%decoded = 0
+ my_jt9%decoded = 0
+ my_ft8%decoded = 0
+ my_ft8var%decodedvar = 0
+ my_ft8var%callback => ft8_decodedvar !Set once in serial init; avoids racing writes in decodevar
+ my_ft4%decoded = 0
+ my_fst4%decoded = 0
+ my_q65%decoded = 0
+ my_ft8var%xdtt=0.
+ nsynced=0
+ navg0=0
+
if(.not.params%newdat .and. params%ntr.gt.ntr0) go to 800
ntr0=params%ntr
rms=sqrt(dot_product(float(id2(1:180000)),float(id2(1:180000)))/180000.0)
@@ -103,17 +116,6 @@ subroutine multimode_decoder(ss,id2,params,nfsample)
hisgrid=transfer(params%hisgrid,hisgrid)
hisgrid4=hisgrid(1:4)
-! Initialize decode counts
- my_jt4%decoded = 0
- my_jt65%decoded = 0
- my_jt9%decoded = 0
- my_ft8%decoded = 0
- my_ft8var%decodedvar = 0
- my_ft4%decoded = 0
- my_fst4%decoded = 0
- my_q65%decoded = 0
- my_ft8var%xdtt=0.
-
ncandall=0 !ft8md
ncandallthr=0 !ft8md
@@ -138,6 +140,7 @@ subroutine multimode_decoder(ss,id2,params,nfsample)
ncontest=iand(params%nexp_decode,7)
single_decode=iand(params%nexp_decode,32).ne.0
bVHF=iand(params%nexp_decode,64).ne.0
+ q65_pileup=iand(params%nexp_decode,128).ne.0 ! bit 7 is reserved for Q65 Pileup
if(mod(params%nranera,2).eq.0) ntrials=10**(params%nranera/2)
if(mod(params%nranera,2).eq.1) ntrials=3*10**(params%nranera/2)
if(params%nranera.eq.0) ntrials=0
@@ -157,6 +160,22 @@ subroutine multimode_decoder(ss,id2,params,nfsample)
endif
endif
+ callback_context%nutc = params%nutc
+ callback_context%nfqso = params%nfqso
+ callback_context%ncontest = ncontest
+ callback_context%ios13 = ios13
+ callback_context%bVHF = bVHF
+ callback_context%b_superfox = params%b_superfox
+ callback_context%mycall = mycall
+ my_jt4%context = callback_context
+ my_jt65%context = callback_context
+ my_jt9%context = callback_context
+ my_ft8%context = callback_context
+ my_ft8var%context = callback_context
+ my_ft4%context = callback_context
+ my_fst4%context = callback_context
+ my_q65%context = callback_context
+
if(params%nmode.eq.8) then
! We're in FT8 mode
if(ncontest.eq.6) then !Fox=6, Hound=7
@@ -180,6 +199,10 @@ subroutine multimode_decoder(ss,id2,params,nfsample)
call sfrx_sub(params%yymmdd,params%nutc,params%nfqso,params%ntol,id2)
else
call timer('decft8 ',0)
+ if(params%nfa.gt.params%nfb) then
+ call timer('decft8 ',1)
+ go to 800
+ endif
newdat=params%newdat
if(params%emedelay.ne.0.0) then
id2(1:156000)=id2(24001:180000) ! Drop the first 2 seconds of data
@@ -190,9 +213,6 @@ subroutine multimode_decoder(ss,id2,params,nfsample)
if(params%lmultift8 .and. params%nmode.eq.8) then
if(params%lmodechanged) then
avexdt=0.
- ihash22var=-1
- calls22var=''
- calls12var=''
nintcount=3
endif ! avexdt fast track in FT8 after mode change
@@ -229,7 +249,6 @@ subroutine multimode_decoder(ss,id2,params,nfsample)
msgroot=''
msgroot=trim(mycall)//' '//trim(hiscall)//' '
msgrootlen=len_trim(msgroot)
- lcommonft8b=params%lcommonft8b
lhound=params%lhound
nft8cycles=params%nft8cycles
forcedt=0.
@@ -254,7 +273,8 @@ subroutine multimode_decoder(ss,id2,params,nfsample)
allmessages=""
allsnrs=0
allfreq=0.
- numcores=omp_get_num_procs()
+ numcores=1
+!$ numcores=omp_get_num_procs()
nuserthr=params%nmt
numthreads=1 ! fallback
@@ -279,8 +299,8 @@ subroutine multimode_decoder(ss,id2,params,nfsample)
endif
endif
- call omp_set_dynamic(.false.)
- call omp_set_nested(.true.)
+!$ call omp_set_dynamic(.false.)
+!$ call omp_set_max_active_levels(omp_get_supported_active_levels())
nfa=params%nfa
nfb=params%nfb
@@ -300,6 +320,15 @@ subroutine multimode_decoder(ss,id2,params,nfsample)
! To do: withdraw limitation when threads are in sync at main passes?
endif
+ call partition_ft8_decode_range(nfa,nfb,numthreads,ft8_range_low, &
+ ft8_range_high,ft8_range_count)
+ if(ft8_range_count.eq.0) then
+ call timer('decft8 ',1)
+ go to 800
+ endif
+ numthreads=ft8_range_count
+ requested_threads=numthreads
+
nsec=mod(nutc,100)
nmsg=0
if(nsec.ne.0 .and. nsec.ne.15 .and. nsec.ne.30 .and. nsec.ne.45) then
@@ -337,729 +366,47 @@ subroutine multimode_decoder(ss,id2,params,nfsample)
nFT8decd=0
sumxdt=0.0
if(params%nmode.eq.4) sumxdtt=0.0
- call fillhashvar(numthreads,.false.)
- call ft8apsetvar(params%lmycallstd,params%lhiscallstd,numthreads)
-
- if(numthreads.eq.1) then
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress, &
- nfqso,params%nft8rxfsens,params%nftx,nutc,nfa,nfb, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 1,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
- endif
-
- if(numthreads.eq.2) then
- nfmid=nfa+nint(abs(nfb-nfa)/2.)
- if((nfmid+1).gt.nfb) nfmid=nfb-1
-
-!$omp parallel sections num_threads(2) shared(dd8,nmsg,even,odd,lqsomsgdcd), &
-!$omp& shared(first_osd,gen,ndecodes,allmessages,allsnrs,allfreq) if(.true.) !iif() needed on Mac
-
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfa,nfmid, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 1,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid+1,nfb, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 2,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp end parallel sections
- endif
- if(numthreads.eq.3) then
- nfdelta=nint(abs(nfb-nfa)/3.)
- nfmid1=nfa+nfdelta
- nfmid2=nfmid1+nfdelta
- if((nfmid2+1).gt.nfb) nfmid2=nfb-1
-!$omp parallel sections num_threads(3) shared(dd8,nmsg,even,odd,lqsomsgdcd), &
-!$omp& shared(first_osd,gen,ndecodes,allmessages,allsnrs,allfreq) if(.true.) !iif() needed on Mac
-
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfa,nfmid1, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 1,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid1+1,nfmid2, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 2,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid2+1,nfb, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 3,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp end parallel sections
+ if(hiscall.eq.'') then
+ lastrxmsg(1)%lstate=.false.
+ else if(lastrxmsg(1)%lstate .and. lasthcall.ne.hiscall .and. &
+ index(lastrxmsg(1)%lastmsg,trim(hiscall)).le.0) then
+ lastrxmsg(1)%lstate=.false.
endif
- if(numthreads.eq.4) then
- nfdelta=nint(abs(nfb-nfa)/4.)
- nfmid1=nfa+nfdelta
- nfmid2=nfmid1+nfdelta
- nfmid3=nfmid2+nfdelta
- if((nfmid3+1).gt.nfb) nfmid3=nfb-1
-
-!$omp parallel sections num_threads(4) shared(dd8,nmsg,even,odd,lqsomsgdcd), &
-!$omp& shared(first_osd,gen,ndecodes,allmessages,allsnrs,allfreq) if(.true.) !iif() needed on Mac
-
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid1+1,nfmid2, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 2,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid2+1,nfmid3, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 3,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfa,nfmid1, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 1,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid3+1,nfb, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 4,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp end parallel sections
- endif
-
- if(numthreads.eq.5) then
- nfdelta=nint(abs(nfb-nfa)/5.)
- nfmid1=nfa+nfdelta
- nfmid2=nfmid1+nfdelta
- nfmid3=nfmid2+nfdelta
- nfmid4=nfmid3+nfdelta
- if((nfmid4+1).gt.nfb) nfmid4=nfb-1
-
-!$omp parallel sections num_threads(5) shared(dd8,nmsg,even,odd,lqsomsgdcd), &
-!$omp& shared(first_osd,gen,ndecodes,allmessages,allsnrs,allfreq) if(.true.) !iif() needed on Mac
-
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid2+1,nfmid3, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 3,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid1+1,nfmid2, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 2,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid3+1,nfmid4, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 4,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfa,nfmid1, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 1,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid4+1,nfb, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 5,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp end parallel sections
- endif
-
- if(numthreads.eq.6) then
- nfdelta=nint(abs(nfb-nfa)/6.)
- nfmid1=nfa+nfdelta
- nfmid2=nfmid1+nfdelta
- nfmid3=nfmid2+nfdelta
- nfmid4=nfmid3+nfdelta
- nfmid5=nfmid4+nfdelta
- if((nfmid5+1).gt.nfb) nfmid5=nfb-1
-
-!$omp parallel sections num_threads(6) shared(dd8,nmsg,even,odd,lqsomsgdcd), &
-!$omp& shared(first_osd,gen,ndecodes,allmessages,allsnrs,allfreq) if(.true.) !iif() needed on Mac
-
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid2+1,nfmid3, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 3,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid3+1,nfmid4, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 4,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid1+1,nfmid2, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 2,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid4+1,nfmid5, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 5,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfa,nfmid1, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 1,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid5+1,nfb, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 6,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp end parallel sections
- endif
-
- if(numthreads.eq.7) then
- nfdelta=nint(abs(nfb-nfa)/7.)
- nfmid1=nfa+nfdelta
- nfmid2=nfmid1+nfdelta
- nfmid3=nfmid2+nfdelta
- nfmid4=nfmid3+nfdelta
- nfmid5=nfmid4+nfdelta
- nfmid6=nfmid5+nfdelta
- if((nfmid6+1).gt.nfb) nfmid6=nfb-1
-
-!$omp parallel sections num_threads(7) shared(dd8,nmsg,even,odd,lqsomsgdcd), &
-!$omp& shared(first_osd,gen,ndecodes,allmessages,allsnrs,allfreq) if(.true.) !iif() needed on Mac
-
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid3+1,nfmid4, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 4,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid2+1,nfmid3, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 3,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid4+1,nfmid5, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 5,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid1+1,nfmid2, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 2,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid5+1,nfmid6, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 6,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfa,nfmid1, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 1,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid6+1,nfb, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 7,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp end parallel sections
- endif
-
- if(numthreads.eq.8) then
- nfdelta=nint(abs(nfb-nfa)/8.)
- nfmid1=nfa+nfdelta
- nfmid2=nfmid1+nfdelta
- nfmid3=nfmid2+nfdelta
- nfmid4=nfmid3+nfdelta
- nfmid5=nfmid4+nfdelta
- nfmid6=nfmid5+nfdelta
- nfmid7=nfmid6+nfdelta
- if((nfmid7+1).gt.nfb) nfmid7=nfb-1
-
-!$omp parallel sections num_threads(8) shared(dd8,nmsg,even,odd,lqsomsgdcd), &
-!$omp& shared(first_osd,gen,ndecodes,allmessages,allsnrs,allfreq) if(.true.) !iif() needed on Mac
-
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid3+1,nfmid4, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 4,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid4+1,nfmid5, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 5,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid2+1,nfmid3, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 3,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid5+1,nfmid6, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 6,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid1+1,nfmid2, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 2,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid6+1,nfmid7, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 7,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfa,nfmid1, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 1,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid7+1,nfb, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 8,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp end parallel sections
- endif
-
- if(numthreads.eq.9) then
- nfdelta=nint(abs(nfb-nfa)/9.)
- nfmid1=nfa+nfdelta
- nfmid2=nfmid1+nfdelta
- nfmid3=nfmid2+nfdelta
- nfmid4=nfmid3+nfdelta
- nfmid5=nfmid4+nfdelta
- nfmid6=nfmid5+nfdelta
- nfmid7=nfmid6+nfdelta
- nfmid8=nfmid7+nfdelta
- if((nfmid8+1).gt.nfb) nfmid8=nfb-1
-
-!$omp parallel sections num_threads(9) shared(dd8,nmsg,even,odd,lqsomsgdcd), &
-!$omp& shared(first_osd,gen,ndecodes,allmessages,allsnrs,allfreq) if(.true.) !iif() needed on Mac
-
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid4+1,nfmid5, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 5,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid3+1,nfmid4, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 4,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid5+1,nfmid6, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 6,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid2+1,nfmid3, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 3,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid6+1,nfmid7, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 7,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid1+1,nfmid2, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 2,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid7+1,nfmid8, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 8,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfa,nfmid1, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 1,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid8+1,nfb, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 9,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp end parallel sections
- endif
-
- if(numthreads.eq.10) then
- nfdelta=nint(abs(nfb-nfa)/10.)
- nfmid1=nfa+nfdelta
- nfmid2=nfmid1+nfdelta
- nfmid3=nfmid2+nfdelta
- nfmid4=nfmid3+nfdelta
- nfmid5=nfmid4+nfdelta
- nfmid6=nfmid5+nfdelta
- nfmid7=nfmid6+nfdelta
- nfmid8=nfmid7+nfdelta
- nfmid9=nfmid8+nfdelta
- if((nfmid9+1).gt.nfb) nfmid9=nfb-1
-
-!$omp parallel sections num_threads(10) shared(dd8,nmsg,even,odd,lqsomsgdcd), &
-!$omp& shared(first_osd,gen,ndecodes,allmessages,allsnrs,allfreq) if(.true.) !iif() needed on Mac
-
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid4+1,nfmid5, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 5,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid5+1,nfmid6, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 6,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid3+1,nfmid4, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 4,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid6+1,nfmid7, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 7,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid2+1,nfmid3, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 3,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid7+1,nfmid8, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 8,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid1+1,nfmid2, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 2,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid8+1,nfmid9, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 9,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfa,nfmid1, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 1,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid9+1,nfb, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 10,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp end parallel sections
- endif
-
- if(numthreads.eq.11) then
- nfdelta=nint(abs(nfb-nfa)/11.)
- nfmid1=nfa+nfdelta
- nfmid2=nfmid1+nfdelta
- nfmid3=nfmid2+nfdelta
- nfmid4=nfmid3+nfdelta
- nfmid5=nfmid4+nfdelta
- nfmid6=nfmid5+nfdelta
- nfmid7=nfmid6+nfdelta
- nfmid8=nfmid7+nfdelta
- nfmid9=nfmid8+nfdelta
- nfmid10=nfmid9+nfdelt
- if((nfmid10+1).gt.nfb) nfmid10=nfb-1
-!$omp parallel sections num_threads(11) shared(dd8,nmsg,even,odd,lqsomsgdcd), &
-!$omp& shared(first_osd,gen,ndecodes,allmessages,allsnrs,allfreq) if(.true.) !iif() needed on Mac
-
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid5+1,nfmid6, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 6,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid4+1,nfmid5, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 5,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid6+1,nfmid7, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 7,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid3+1,nfmid4, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 4,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid7+1,nfmid8, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 8,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid2+1,nfmid3, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 3,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid8+1,nfmid9, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 9,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid1+1,nfmid2, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 2,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid9+1,nfmid10, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 10,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfa,nfmid1, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 1,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid10+1,nfb, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 11,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp end parallel sections
- endif
-
- if(numthreads.eq.12) then
- nfdelta=nint(abs(nfb-nfa)/12.)
- nfmid1=nfa+nfdelta
- nfmid2=nfmid1+nfdelta
- nfmid3=nfmid2+nfdelta
- nfmid4=nfmid3+nfdelta
- nfmid5=nfmid4+nfdelta
- nfmid6=nfmid5+nfdelta
- nfmid7=nfmid6+nfdelta
- nfmid8=nfmid7+nfdelta
- nfmid9=nfmid8+nfdelta
- nfmid10=nfmid9+nfdelta
- nfmid11=nfmid10+nfdelt
- if((nfmid11+1).gt.nfb) nfmid11=nfb-1
-!$omp parallel sections num_threads(12) shared(dd8,nmsg,even,odd,lqsomsgdcd), &
-!$omp& shared(first_osd,gen,ndecodes,allmessages,allsnrs,allfreq) if(.true.) !iif() needed on Mac
+!$omp parallel num_threads(requested_threads) private(nthr) shared(numthreads)
+!$omp single
+ numthreads=1
+!$ numthreads=omp_get_num_threads()
+! Reduced teams cover wider frequency slices, so fixed per-worker candidate limits can lower crowded-band yield.
+ call partition_ft8_decode_range(nfa,nfb,numthreads,ft8_range_low, &
+ ft8_range_high,ft8_range_count)
+ numthreads=ft8_range_count
+ call mtd_prepare(dd8,numthreads)
+ call fillhashvar(numthreads,.false.)
+ call ft8apsetvar(params%lmycallstd,params%lhiscallstd,numthreads)
+!$omp end single
+
+ nthr=1
+!$ nthr=omp_get_thread_num()+1
+ call my_ft8var%decodevar(params%nQSOProgress,nfqso, &
+ params%nft8rxfsens,params%nftx,ft8_range_low(nthr), &
+ ft8_range_high(nthr),params%ncandthin,params%ndtcenter,nsec, &
+ params%napwid,params%lmycallstd,params%lhiscallstd, &
+ params%nstophint,nthr,numthreads,logical(params%nagainfil), &
+ params%lft8lowth,params%lft8subpass,params%lhideft8dupes, &
+ active_progress_generation, &
+ mtd_worker_residual(:,nthr), &
+ mtd_worker_spectrum(:,nthr))
+!$omp end parallel
+
+ call write_decode_progress(active_progress_generation)
+ call mtd_finish(dd8)
+
+ call write_decode_progress(active_progress_generation)
+ call run_ft8_mtd_a8_decode()
+ call write_decode_progress(active_progress_generation)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid5+1,nfmid6, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 6,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid6+1,nfmid7, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 7,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid4+1,nfmid5, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 5,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid7+1,nfmid8, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 8,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid3+1,nfmid4, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 4,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid8+1,nfmid9, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 9,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid2+1,nfmid3, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 3,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid9+1,nfmid10, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 10,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid1+1,nfmid2, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 2,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid10+1,nfmid11, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 11,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfa,nfmid1, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 1,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp section
- call my_ft8var%decodevar(ft8_decodedvar,params%nQSOProgress,nfqso, &
- params%nft8rxfsens,params%nftx,nutc,nfmid11+1,nfb, &
- params%ncandthin,params%ndtcenter,nsec,params%napwid, &
- params%lmycallstd,params%lhiscallstd,params%nstophint, &
- 12,numthreads,logical(params%nagainfil),params%lft8lowth, &
- params%lft8subpass,params%lhideft8dupes,params%lft8apon,ncontest)
-!$omp end parallel sections
- endif
-
do i=1,numthreads
do m=1,nincallthr(i)
nindex=maskincallthr(i)+m
@@ -1132,6 +479,7 @@ subroutine multimode_decoder(ss,id2,params,nfsample)
if(nFT8decd.gt.10 .and. nintcount.eq.1) avexdt=sumxdt/nFT8decd ! fast track after Sync or mode change on crowded bands
call fillhashvar(numthreads,.true.)
+ call write_decode_progress(active_progress_generation)
ncandall=sum(ncandallthr(1:numthreads))
if(nFT8decd.eq.0) avexdt=0. ! reset to let correct sliding in decoder
call timer('decft8 ',1)
@@ -1209,7 +557,8 @@ subroutine multimode_decoder(ss,id2,params,nfsample)
params%nfa,params%nfb,logical(params%nclearave), &
single_decode,logical(params%nagain),params%max_drift, &
logical(params%newdat),params%emedelay,mycall,hiscall,hisgrid, &
- params%nQSOProgress,ncontest,logical(params%lapcqonly),navg0,nqf)
+ params%nQSOProgress,ncontest,q65_pileup,logical(params%lapcqonly), &
+ navg0,nqf)
params%nclearave=.false.
if(.not.params%nagain) then
@@ -1226,8 +575,8 @@ subroutine multimode_decoder(ss,id2,params,nfsample)
params%nfa,params%nfb,logical(params%nclearave), &
.true.,.true.,params%max_drift, &
.false.,params%emedelay,mycall,hiscall,hisgrid, &
- params%nQSOProgress,ncontest,logical(params%lapcqonly), &
- navg0,nqf)
+ params%nQSOProgress,ncontest,q65_pileup, &
+ logical(params%lapcqonly),navg0,nqf)
enddo
endif
@@ -1320,11 +669,14 @@ subroutine multimode_decoder(ss,id2,params,nfsample)
newdat65=params%newdat
newdat9=params%newdat
- call omp_set_dynamic(.true.)
+!$ call omp_set_dynamic(.true.)
+ call wsjt_tsan_release_decoder_section_primary()
+ call wsjt_tsan_release_decoder_section_secondary()
!$omp parallel sections num_threads(2) shared(ndecoded) if(.true.) !iif() needed on Mac
!$omp section
+ call wsjt_tsan_acquire_decoder_section_primary()
if(params%nmode.eq.65) then ! We're in JT65 mode
if(newdat65) dd(1:npts65)=id2(1:npts65)
nf1=params%nfa
@@ -1349,8 +701,10 @@ subroutine multimode_decoder(ss,id2,params,nfsample)
params%nmode,params%nsubmode,params%nexp_decode)
call timer('decjt9 ',1)
endif
+ call wsjt_tsan_release_decoder_section_primary()
!$omp section
+ call wsjt_tsan_acquire_decoder_section_secondary()
if(params%nmode.eq.(65+9)) then !Do the other mode (we're in dual mode)
if (params%ntxmode.eq.9) then
if(newdat65) dd(1:npts65)=id2(1:npts65)
@@ -1374,8 +728,11 @@ subroutine multimode_decoder(ss,id2,params,nfsample)
call timer('decjt9 ',1)
end if
endif
+ call wsjt_tsan_release_decoder_section_secondary()
!$omp end parallel sections
+ call wsjt_tsan_acquire_decoder_section_primary()
+ call wsjt_tsan_acquire_decoder_section_secondary()
! JT65 is not yet producing info for nsynced, ndecoded.
@@ -1401,9 +758,8 @@ subroutine multimode_decoder(ss,id2,params,nfsample)
if(params%nmode.ne.8 .or. params%nzhsym.eq.50 .or. &
(params%lmultift8 .and. params%nmode.eq.8 .and. params%nzhsym.gt.45) .or. &
.not.params%ndiskdat) then !ft8md
- if(.not.lquiet) write(*,1010) nsynced,ndecoded,navg0
-1010 format('<DecodeFinished>',2i4,i9)
- call flush(6)
+ call set_decode_completion(completion,nsynced,ndecoded,navg0)
+ call write_decode_progress(active_progress_generation)
endif
close(13)
if(ncontest.eq.6) close(19)
@@ -1412,545 +768,62 @@ subroutine multimode_decoder(ss,id2,params,nfsample)
contains
- subroutine jt4_decoded(this,snr,dt,freq,have_sync,sync,is_deep, &
- decoded0,qual,ich,is_average,ave)
- implicit none
- class(jt4_decoder), intent(inout) :: this
- integer, intent(in) :: snr
- real, intent(in) :: dt
- integer, intent(in) :: freq
- logical, intent(in) :: have_sync
- logical, intent(in) :: is_deep
- character(len=1), intent(in) :: sync
- character(len=22), intent(in) :: decoded0
- real, intent(in) :: qual
- integer, intent(in) :: ich
- logical, intent(in) :: is_average
- integer, intent(in) :: ave
-
- character*22 decoded
- character*3 cflags
-
- if(ich.eq.-99) stop !Silence compiler warning
- if (have_sync) then
- decoded=decoded0
- cflags=' '
- if(decoded.ne.' ') then
- cflags='f '
- if(is_deep) then
- cflags='d '
- write(cflags(2:2),'(i1)') min(int(qual),9)
- if(qual.ge.10.0) cflags(2:2)='*'
- if(qual.lt.3.0) decoded(22:22)='?'
- endif
- if(is_average) then
- write(cflags(3:3),'(i1)') min(ave,9)
- if(ave.ge.10) cflags(3:3)='*'
- if(cflags(1:1).eq.'f') cflags=cflags(1:1)//cflags(3:3)//' '
- endif
- endif
- write(*,1000) params%nutc,snr,dt,freq,sync,decoded,cflags
-1000 format(i4.4,i4,f5.1,i5,1x,'$',a1,1x,a22,1x,a3)
- else
- write(*,1000) params%nutc,snr,dt,freq
- end if
-
- select type(this)
- type is (counting_jt4_decoder)
- this%decoded = this%decoded + 1
- end select
- end subroutine jt4_decoded
-
- subroutine jt4_average (this, used, utc, sync, dt, freq, flip)
- implicit none
- class(jt4_decoder), intent(inout) :: this
- logical, intent(in) :: used
- integer, intent(in) :: utc
- real, intent(in) :: sync
- real, intent(in) :: dt
- integer, intent(in) :: freq
- logical, intent(in) :: flip
- character(len=1) :: cused, csync
-
- cused = '.'
- csync = '*'
- if (used) cused = '$'
- if (flip) csync = '$'
- write(14,1000) cused,utc,sync,dt,freq,csync
-1000 format(a1,i5.4,f6.1,f6.2,i6,1x,a1)
- end subroutine jt4_average
-
- subroutine jt65_decoded(this,sync,snr,dt,freq,drift,nflip,width, &
- decoded0,ft,qual,nsmo,nsum,minsync)
-
- use jt65_decode
- implicit none
-
- class(jt65_decoder), intent(inout) :: this
- real, intent(in) :: sync
- integer, intent(in) :: snr
- real, intent(in) :: dt
- integer, intent(in) :: freq
- integer, intent(in) :: drift
- integer, intent(in) :: nflip
- real, intent(in) :: width
- character(len=22), intent(in) :: decoded0
- integer, intent(in) :: ft
- integer, intent(in) :: qual
- integer, intent(in) :: nsmo
- integer, intent(in) :: nsum
- integer, intent(in) :: minsync
-
- integer i,nap
- logical is_deep,is_average
- character decoded*22,csync*2,cflags*3
-
- !$omp critical(decode_results)
- decoded=decoded0
- cflags=' '
- is_deep=ft.eq.2
-
- if(ft.eq.0 .and. minsync.ge.0 .and. int(sync).lt.minsync) then
- write(*,1010) params%nutc,snr,dt,freq
- else
- is_average=nsum.ge.2
- if(bVHF .and. ft.gt.0) then
- cflags='f '
- if(is_deep) then
- cflags='d '
- write(cflags(2:2),'(i1)') min(qual,9)
- if(qual.ge.10) cflags(2:2)='*'
- if(qual.lt.3) decoded(22:22)='?'
- endif
- if(is_average) then
- write(cflags(3:3),'(i1)') min(nsum,9)
- if(nsum.ge.10) cflags(3:3)='*'
- endif
- nap=ishft(ft,-2)
- if(nap.ne.0) then
- if(nsum.lt.2) write(cflags(1:3),'(a1,i1," ")') 'a',nap
- if(nsum.ge.2) write(cflags(1:3),'(a1,2i1)') 'a',nap,min(nsum,9)
- endif
- endif
- csync='# '
- i=0
- if(bVHF .and. nflip.ne.0 .and. &
- sync.ge.max(0.0,float(minsync))) then
- csync='#*'
- if(nflip.eq.-1) then
- csync='##'
- if(decoded.ne.' ') then
- do i=22,1,-1
- if(decoded(i:i).ne.' ') exit
- enddo
- if(i.gt.18) i=18
- decoded(i+2:i+4)='OOO'
- endif
- endif
- endif
- n=len(trim(decoded))
- if(n.eq.2 .or. n.eq.3) csync='# '
- if(cflags(1:1).eq.'f') then
- cflags(2:2)=cflags(3:3)
- cflags(3:3)=' '
- endif
- write(*,1010) params%nutc,snr,dt,freq,csync,decoded,cflags
-1010 format(i4.4,i4,f5.1,i5,1x,a2,1x,a22,1x,a3)
- endif
- if(ios13.eq.0) write(13,1012) params%nutc,nint(sync),snr,dt, &
- float(freq),drift,decoded,ft,nsum,nsmo
-1012 format(i4.4,i4,i5,f6.2,f8.0,i4,3x,a22,' JT65',3i3)
- call flush(6)
-
- !$omp end critical(decode_results)
- select type(this)
- type is (counting_jt65_decoder)
- this%decoded = this%decoded + 1
- end select
- end subroutine jt65_decoded
-
- subroutine jt9_decoded (this, sync, snr, dt, freq, drift, decoded)
- use jt9_decode
- implicit none
-
- class(jt9_decoder), intent(inout) :: this
- real, intent(in) :: sync
- integer, intent(in) :: snr
- real, intent(in) :: dt
- real, intent(in) :: freq
- integer, intent(in) :: drift
- character(len=22), intent(in) :: decoded
-
- !$omp critical(decode_results)
-
- write(*,1000) params%nutc,snr,dt,nint(freq),decoded
-1000 format(i4.4,i4,f5.1,i5,1x,'@ ',1x,a22)
- if(ios13.eq.0) write(13,1002) params%nutc,nint(sync),snr,dt,freq, &
- drift,decoded
-1002 format(i4.4,i4,i5,f6.1,f8.0,i4,3x,a22,' JT9')
- call flush(6)
- !$omp end critical(decode_results)
- select type(this)
- type is (counting_jt9_decoder)
- this%decoded = this%decoded + 1
- end select
- end subroutine jt9_decoded
-
- subroutine ft8_decodedvar (this,snr,dt,freq,decodedvar,nap,qual) !ft8md was(this,snr,dt,freq,decodedvar)
- use ft8_decodevar
- implicit none
-
- class(ft8_decodervar), intent(inout) :: this
- integer, intent(in) :: snr
- real, intent(in) :: dt
- real, intent(in) :: freq
- real, intent(in) :: qual
- real fdiff
- character(len=37), intent(in) :: decodedvar !ft8md was 26
- character*2 annot
- character c1*12,c2*12,g2*4,w*4
- integer i1,i2,i3,i4,i5,n30,nwrap
- integer, intent(in) :: nap !ft8md
- integer msglen
- character*37 decoded0
- logical isgrid4,first,b0,b1,b2
- data first/.true./
- save
-
- isgrid4(w)=(len_trim(w).eq.4 .and. &
- ichar(w(1:1)).ge.ichar('A') .and. ichar(w(1:1)).le.ichar('R') .and. &
- ichar(w(2:2)).ge.ichar('A') .and. ichar(w(2:2)).le.ichar('R') .and. &
- ichar(w(3:3)).ge.ichar('0') .and. ichar(w(3:3)).le.ichar('9') .and. &
- ichar(w(4:4)).ge.ichar('0') .and. ichar(w(4:4)).le.ichar('9'))
-
- if(first) then
- c2fox=' '
- g2fox=' '
- nsnrfox=-99
- nfreqfox=-99
- n30z=0
- nwrap=0
- nfox=0
- first=.false.
- endif
-
- fdiff=freq-params%nfqso
- if(abs(fdiff).lt.3.0) ltry_a8=.false.
-
- decoded0=decodedvar
-
- annot=' '
- if(nap.ne.0) then
- if(nap.ge.9) then
- write(annot,'(a1,i1)') 'a',9
- else
- write(annot,'(a1,i1)') 'a',nap
- endif
- if(qual.lt.0.17) decoded0(37:37)='?'
- endif
-
- write(*,1000) params%nutc,snr,dt,nint(freq),decoded0,annot
-1000 format(i6.6,i4,f5.1,i5,' ~ ',1x,a37,1x,a2)
-
- if(ncontest.eq.6) then
- i1=index(decoded0,' ')
- i2=i1 + index(decoded0(i1+1:),' ')
- i3=i2 + index(decoded0(i2+1:),' ')
- if(i1.ge.3 .and. i2.ge.7 .and. i3.ge.10) then
- c1=decoded0(1:i1-1)//' '
- c2=decoded0(i1+1:i2-1)
- g2=decoded0(i2+1:i3-1)
- b0=c1.eq.mycall
- if(c1(1:3).eq.'DE ' .and. index(c2,'/').ge.2) b0=.true.
- if(len(trim(c1)).ne.len(trim(mycall))) then
- i4=index(trim(c1),trim(mycall))
- i5=index(trim(mycall),trim(c1))
- if(i4.ge.1 .or. i5.ge.1) b0=.true.
- endif
- b1=i3-i2.eq.5 .and. isgrid4(g2)
- b2=i3-i2.eq.1
- if(b0 .and. (b1.or.b2) .and. (nint(freq).ge.1000 .or. &
- params%b_superfox)) then
- n=params%nutc
- n30=(3600*(n/10000) + 60*mod((n/100),100) + mod(n,100))/30
- if(n30.lt.n30z) nwrap=nwrap+2880 !New UTC day, handle the wrap
- n30z=n30
- n30=n30+nwrap
- if(nfox.lt.MAXFOX) nfox=nfox+1
- c2fox(nfox)=c2
- g2fox(nfox)=g2
- nsnrfox(nfox)=snr
- nfreqfox(nfox)=nint(freq)
- n30fox(nfox)=n30
- endif
- endif
- endif
- call flush(6)
- if(ios13.eq.0) call flush(13)
-
- select type(this)
- type is (counting_ft8_decodervar)
- this%decodedvar = this%decodedvar + 1
- this%xdtt(this%decodedvar)=dt
- end select
-
- return
- end subroutine ft8_decodedvar
-
- subroutine ft8_decoded (this,sync,snr,dt,freq,decoded,nap,qual)
- use ft8_decode
+ subroutine run_ft8_mtd_a8_decode()
implicit none
- class(ft8_decoder), intent(inout) :: this
- real, intent(in) :: sync
- integer, intent(in) :: snr
- real, intent(in) :: dt
- real, intent(in) :: freq
- character(len=37), intent(in) :: decoded
- character c1*12,c2*12,g2*4,w*4
- integer i0,i1,i2,i3,i4,i5,n30,nwrap
- integer, intent(in) :: nap
- real, intent(in) :: qual
- real fdiff
- character*2 annot
- character*37 decoded0
- logical isgrid4,first,b0,b1,b2
- data first/.true./
- save
-
- isgrid4(w)=(len_trim(w).eq.4 .and. &
- ichar(w(1:1)).ge.ichar('A') .and. ichar(w(1:1)).le.ichar('R') .and. &
- ichar(w(2:2)).ge.ichar('A') .and. ichar(w(2:2)).le.ichar('R') .and. &
- ichar(w(3:3)).ge.ichar('0') .and. ichar(w(3:3)).le.ichar('9') .and. &
- ichar(w(4:4)).ge.ichar('0') .and. ichar(w(4:4)).le.ichar('9'))
-
- if(first) then
- c2fox=' '
- g2fox=' '
- nsnrfox=-99
- nfreqfox=-99
- n30z=0
- nwrap=0
- nfox=0
- first=.false.
- endif
-
- decoded0=decoded
- fdiff=freq-params%nfqso
- if(abs(fdiff).lt.3.0) ltry_a8=.false.
-
- annot=' '
- if(nap.ne.0) then
- write(annot,'(a1,i1)') 'a',nap
- if(qual.lt.0.17) decoded0(37:37)='?'
- endif
-
- ! i0=index(decoded0,';')
- ! Always print 37 characters? Or, send i3,n3 up to here from ft8b_2 and use them
- ! to decide how many chars to print?
- !TEMP
- i0=1
- if(i0.le.0) write(*,1000) params%nutc,snr,dt,nint(freq),decoded0(1:22),annot
-1000 format(i6.6,i4,f5.1,i5,' ~ ',1x,a22,1x,a2)
- if(i0.gt.0) write(*,1001) params%nutc,snr,dt,nint(freq),decoded0,annot
-1001 format(i6.6,i4,f5.1,i5,' ~ ',1x,a37,1x,a2)
- if(ios13.eq.0) write(13,1002) params%nutc,nint(sync),snr,dt,freq,0,decoded0
-1002 format(i6.6,i4,i5,f6.1,f8.0,i4,3x,a37,' FT8')
-
- if(ncontest.eq.6) then
- i1=index(decoded0,' ')
- i2=i1 + index(decoded0(i1+1:),' ')
- i3=i2 + index(decoded0(i2+1:),' ')
- if(i1.ge.3 .and. i2.ge.7 .and. i3.ge.10) then
- c1=decoded0(1:i1-1)//' '
- c2=decoded0(i1+1:i2-1)
- g2=decoded0(i2+1:i3-1)
- b0=c1.eq.mycall
- if(c1(1:3).eq.'DE ' .and. index(c2,'/').ge.2) b0=.true.
- if(len(trim(c1)).ne.len(trim(mycall))) then
- i4=index(trim(c1),trim(mycall))
- i5=index(trim(mycall),trim(c1))
- if(i4.ge.1 .or. i5.ge.1) b0=.true.
- endif
- b1=i3-i2.eq.5 .and. isgrid4(g2)
- b2=i3-i2.eq.1
- if(b0 .and. (b1.or.b2) .and. (nint(freq).ge.1000 .or. &
- params%b_superfox)) then
- n=params%nutc
- n30=(3600*(n/10000) + 60*mod((n/100),100) + mod(n,100))/30
- if(n30.lt.n30z) nwrap=nwrap+2880 !New UTC day, handle the wrap
- n30z=n30
- n30=n30+nwrap
- if(nfox.lt.MAXFOX) nfox=nfox+1
- c2fox(nfox)=c2
- g2fox(nfox)=g2
- nsnrfox(nfox)=snr
- nfreqfox(nfox)=nint(freq)
- n30fox(nfox)=n30
- endif
+ external ft8_a8d
+ real f1,xdt,fbest,xsnr,plog,qual
+ integer nsnr,iaptype
+ character(len=6) dxgrid
+ character(len=37) msg37
+
+ if(.not.params%lft8apon) return
+ if(ncontest.eq.6 .or. ncontest.eq.7) return
+ if(len(trim(hiscall)).lt.3 .or. len(trim(hisgrid4)).lt.4) return
+ if(.not.ltry_a8) return
+
+ f1=nfqso
+ dxgrid=hisgrid4
+ call timer('ft8_a8d ',0)
+ call ft8_a8d(dd8,mycall,hiscall,dxgrid,f1,xdt,fbest,xsnr,plog,msg37, &
+ active_progress_generation)
+ call timer('ft8_a8d ',1)
+
+ if(msg37(1:1).ne.' ') then
+ if(associated(my_ft8var%callback)) then
+ nsnr=nint(xsnr)
+ iaptype=8
+ qual=1.0
+ if(plog.lt.-147.0) qual=0.16
+ call my_ft8var%callback(nsnr,xdt,fbest,msg37,iaptype,qual)
endif
endif
+ end subroutine run_ft8_mtd_a8_decode
- call flush(6)
- if(ios13.eq.0) call flush(13)
-
- select type(this)
- type is (counting_ft8_decoder)
- this%decoded = this%decoded + 1
- end select
-
- return
- end subroutine ft8_decoded
-
- subroutine ft4_decoded (this,sync,snr,dt,freq,decoded,nap,qual)
- use ft4_decode
- implicit none
-
- class(ft4_decoder), intent(inout) :: this
- real, intent(in) :: sync
- integer, intent(in) :: snr
- real, intent(in) :: dt
- real, intent(in) :: freq
- character(len=37), intent(in) :: decoded
- integer, intent(in) :: nap
- real, intent(in) :: qual
- character*2 annot
- character*37 decoded0
-
- decoded0=decoded
-
- annot=' '
- if(nap.ne.0) then
- write(annot,'(a1,i1)') 'a',nap
- if(qual.lt.0.17) decoded0(37:37)='?'
- endif
-
- write(*,1001) params%nutc,snr,dt,nint(freq),decoded0,annot
-1001 format(i6.6,i4,f5.1,i5,' + ',1x,a37,1x,a2)
- if(ios13.eq.0) then
- write(13,1002,err=10) params%nutc,nint(sync),snr,dt,freq,0,decoded0
-1002 format(i6.6,i4,i5,f6.1,f8.0,i4,3x,a37,' FT4')
- flush(13)
- endif
-
-10 call flush(6)
-
- select type(this)
- type is (counting_ft4_decoder)
- this%decoded = this%decoded + 1
- end select
-
- return
- end subroutine ft4_decoded
-
- subroutine fst4_decoded (this,nutc,sync,nsnr,dt,freq,decoded,nap, &
- qual,ntrperiod,fmid,w50)
-
- use fst4_decode
- implicit none
-
- class(fst4_decoder), intent(inout) :: this
- integer, intent(in) :: nutc
- real, intent(in) :: sync
- integer, intent(in) :: nsnr
- real, intent(in) :: dt
- real, intent(in) :: freq
- character(len=37), intent(in) :: decoded
- integer, intent(in) :: nap
- real, intent(in) :: qual
- integer, intent(in) :: ntrperiod
- real, intent(in) :: fmid
- real, intent(in) :: w50
-
- character*2 annot
- character*37 decoded0
- character*70 line
-
- decoded0=decoded
- annot=' '
- if(nap.ne.0) then
- write(annot,'(a1,i1)') 'a',nap
- if(qual.lt.0.17) decoded0(37:37)='?'
- endif
-
- if(ntrperiod.lt.60) then
- write(line,1001) nutc,nsnr,dt,nint(freq),decoded0,annot
-1001 format(i6.6,i4,f5.1,i5,' ` ',1x,a37,1x,a2)
- if(ios13.eq.0) write(13,1002) nutc,nint(sync),nsnr,dt,freq,0,decoded0
-1002 format(i6.6,i4,i5,f6.1,f8.0,i4,3x,a37,' FST4')
- else
- write(line,1003) nutc,nsnr,dt,nint(freq),decoded0,annot
-1003 format(i4.4,i4,f5.1,i5,' ` ',1x,a37,1x,a2,2f7.3)
- if(ios13.eq.0) write(13,1004) nutc,nint(sync),nsnr,dt,freq,0,decoded0
-1004 format(i4.4,i4,i5,f6.1,f8.0,i4,3x,a37,' FST4')
- endif
-
- if(fmid.ne.-999.0) then
- if(w50.lt.0.95) write(line(65:70),'(f6.3)') w50
- if(w50.ge.0.95) write(line(65:70),'(f6.2)') w50
- endif
-
- write(*,1005) line
-1005 format(a70)
+end subroutine multimode_decoder_core
- call flush(6)
- if(ios13.eq.0) call flush(13)
-
- select type(this)
- type is (counting_fst4_decoder)
- this%decoded = this%decoded + 1
- end select
-
- return
- end subroutine fst4_decoded
-
- subroutine q65_decoded (this,nutc,snr1,nsnr,dt,freq,decoded,idec, &
- nused,ntrperiod)
-
- use q65_decode
- implicit none
-
- class(q65_decoder), intent(inout) :: this
- integer, intent(in) :: nutc
- real, intent(in) :: snr1
- integer, intent(in) :: nsnr
- real, intent(in) :: dt
- real, intent(in) :: freq
- character(len=37), intent(in) :: decoded
- integer, intent(in) :: idec
- integer, intent(in) :: nused
- integer, intent(in) :: ntrperiod
- character*3 cflags
-
- cflags=' '
- if(idec.ge.0) then
- cflags='q '
- write(cflags(2:2),'(i1)') idec
- if(nused.ge.2) write(cflags(3:3),'(i1)') nused
- endif
-
- if(ntrperiod.lt.60) then
- write(*,1001) nutc,nsnr,dt,nint(freq),decoded,cflags
-1001 format(i6.6,i4,f5.1,i5,' : ',1x,a37,1x,a3)
- if(ios13.eq.0) write(13,1002) nutc,nint(snr1),nsnr,dt,freq,0,decoded
-1002 format(i6.6,i4,i5,f6.1,f8.0,i4,3x,a37,' Q65')
- else
- write(*,1003) nutc,nsnr,dt,nint(freq),decoded,cflags
-1003 format(i4.4,i4,f5.1,i5,' : ',1x,a37,1x,a3)
- if(ios13.eq.0) write(13,1004) nutc,nint(snr1),nsnr,dt,freq,0,decoded
-1004 format(i4.4,i4,i5,f6.1,f8.0,i4,3x,a37,' Q65')
+subroutine multimode_decoder(ss,id2,params,nfsample)
+ use prog_args, only: lquiet
+ use streaming_emit, only: streaming_emit_enabled, &
+ streaming_emit_decode_finished
+ use decode_completion_module, only: decode_completion_result, &
+ write_decode_completion
- endif
- call flush(6)
- if(ios13.eq.0) call flush(13)
+ include 'jt9com.f90'
- select type(this)
- type is (counting_q65_decoder)
- if(idec.ge.0) this%decoded = this%decoded + 1
- end select
+ real ss(184,NSMAX)
+ integer*2 id2(NTMAX*12000)
+ type(params_block) :: params
+ type(decode_completion_result) :: completion
- return
- end subroutine q65_decoded
+ call multimode_decoder_core(ss,id2,params,nfsample,completion,0)
+ if (.not. completion%available) return
+ if (streaming_emit_enabled()) then
+ call streaming_emit_decode_finished(params%nutc)
+ else if (.not. lquiet) then
+ call write_decode_completion(completion)
+ end if
+ call flush(6)
end subroutine multimode_decoder
diff --git a/lib/decoder_callbacks.f90 b/lib/decoder_callbacks.f90
new file mode 100644
index 00000000..33c2ac85
--- /dev/null
+++ b/lib/decoder_callbacks.f90
@@ -0,0 +1,718 @@
+module decoder_callbacks
+
+ use jt4_decode
+ use jt65_decode
+ use jt9_decode
+ use ft8_decode
+ use ft8_decodevar
+ use ft4_decode
+ use fst4_decode
+ use q65_decode
+ use streaming_emit, only: streaming_emit_enabled, streaming_emit_decode
+
+ implicit none
+
+ type :: decoder_callback_context
+ ! Callback state is stored on each decoder instead of captured by a nested procedure.
+ integer :: nutc = 0
+ integer :: nfqso = 0
+ integer :: ncontest = 0
+ integer :: ios13 = -1
+ logical :: bVHF = .false.
+ logical :: b_superfox = .false.
+ character(len=12) :: mycall = ' '
+ end type decoder_callback_context
+
+ type, extends(jt4_decoder) :: counting_jt4_decoder
+ type(decoder_callback_context) :: context
+ integer :: decoded = 0
+ end type counting_jt4_decoder
+
+ type, extends(jt65_decoder) :: counting_jt65_decoder
+ type(decoder_callback_context) :: context
+ integer :: decoded = 0
+ end type counting_jt65_decoder
+
+ type, extends(jt9_decoder) :: counting_jt9_decoder
+ type(decoder_callback_context) :: context
+ integer :: decoded = 0
+ end type counting_jt9_decoder
+
+ type, extends(ft8_decoder) :: counting_ft8_decoder
+ type(decoder_callback_context) :: context
+ integer :: decoded = 0
+ end type counting_ft8_decoder
+
+ type, extends(ft8_decodervar) :: counting_ft8_decodervar
+ type(decoder_callback_context) :: context
+ integer :: decodedvar = 0
+ real :: xdtt(200)
+ end type counting_ft8_decodervar
+
+ type, extends(ft4_decoder) :: counting_ft4_decoder
+ type(decoder_callback_context) :: context
+ integer :: decoded = 0
+ end type counting_ft4_decoder
+
+ type, extends(fst4_decoder) :: counting_fst4_decoder
+ type(decoder_callback_context) :: context
+ integer :: decoded = 0
+ end type counting_fst4_decoder
+
+ type, extends(q65_decoder) :: counting_q65_decoder
+ type(decoder_callback_context) :: context
+ integer :: decoded = 0
+ end type counting_q65_decoder
+
+contains
+
+ subroutine jt4_decoded(this,snr,dt,freq,have_sync,sync,is_deep, &
+ decoded0,qual,ich,is_average,ave)
+ implicit none
+ class(jt4_decoder), intent(inout) :: this
+ integer, intent(in) :: snr
+ real, intent(in) :: dt
+ integer, intent(in) :: freq
+ logical, intent(in) :: have_sync
+ logical, intent(in) :: is_deep
+ character(len=1), intent(in) :: sync
+ character(len=22), intent(in) :: decoded0
+ real, intent(in) :: qual
+ integer, intent(in) :: ich
+ logical, intent(in) :: is_average
+ integer, intent(in) :: ave
+
+ character*22 decoded
+ character*3 cflags
+ integer context_nutc
+
+ select type (typed_this => this)
+ type is (counting_jt4_decoder)
+ context_nutc = typed_this%context%nutc
+ class default
+ return
+ end select
+
+ if(ich.eq.-99) stop
+ if (have_sync) then
+ decoded=decoded0
+ cflags=' '
+ if(decoded.ne.' ') then
+ cflags='f '
+ if(is_deep) then
+ cflags='d '
+ write(cflags(2:2),'(i1)') min(int(qual),9)
+ if(qual.ge.10.0) cflags(2:2)='*'
+ if(qual.lt.3.0) decoded(22:22)='?'
+ endif
+ if(is_average) then
+ write(cflags(3:3),'(i1)') min(ave,9)
+ if(ave.ge.10) cflags(3:3)='*'
+ if(cflags(1:1).eq.'f') cflags=cflags(1:1)//cflags(3:3)//' '
+ endif
+ endif
+ if (streaming_emit_enabled()) then
+ call streaming_emit_decode("JT4", context_nutc, snr, dt, freq, decoded)
+ else
+ write(*,1000) context_nutc,snr,dt,freq,sync,decoded,cflags
+ end if
+ else
+ if (.not. streaming_emit_enabled()) write(*,1000) context_nutc,snr,dt,freq
+ end if
+1000 format(i4.4,i4,f5.1,i5,1x,'$',a1,1x,a22,1x,a3)
+
+ select type (typed_this => this)
+ type is (counting_jt4_decoder)
+ typed_this%decoded = typed_this%decoded + 1
+ end select
+ end subroutine jt4_decoded
+
+ subroutine jt4_average (this, used, utc, sync, dt, freq, flip)
+ implicit none
+ class(jt4_decoder), intent(inout) :: this
+ logical, intent(in) :: used
+ integer, intent(in) :: utc
+ real, intent(in) :: sync
+ real, intent(in) :: dt
+ integer, intent(in) :: freq
+ logical, intent(in) :: flip
+ character(len=1) :: cused, csync
+
+ cused = '.'
+ csync = '*'
+ if (used) cused = '$'
+ if (flip) csync = '$'
+ write(14,1000) cused,utc,sync,dt,freq,csync
+1000 format(a1,i5.4,f6.1,f6.2,i6,1x,a1)
+ end subroutine jt4_average
+
+ subroutine jt65_decoded(this,sync,snr,dt,freq,drift,nflip,width, &
+ decoded0,ft,qual,nsmo,nsum,minsync)
+
+ implicit none
+
+ class(jt65_decoder), intent(inout) :: this
+ real, intent(in) :: sync
+ integer, intent(in) :: snr
+ real, intent(in) :: dt
+ integer, intent(in) :: freq
+ integer, intent(in) :: drift
+ integer, intent(in) :: nflip
+ real, intent(in) :: width
+ character(len=22), intent(in) :: decoded0
+ integer, intent(in) :: ft
+ integer, intent(in) :: qual
+ integer, intent(in) :: nsmo
+ integer, intent(in) :: nsum
+ integer, intent(in) :: minsync
+
+ integer i,nap,n
+ integer context_nutc, context_ios13
+ logical context_bVHF
+ logical is_deep,is_average
+ character decoded*22,csync*2,cflags*3
+
+ select type (typed_this => this)
+ type is (counting_jt65_decoder)
+ context_nutc = typed_this%context%nutc
+ context_ios13 = typed_this%context%ios13
+ context_bVHF = typed_this%context%bVHF
+ class default
+ return
+ end select
+
+ !$omp critical(decode_results)
+ decoded=decoded0
+ cflags=' '
+ is_deep=ft.eq.2
+
+ if(ft.eq.0 .and. minsync.ge.0 .and. int(sync).lt.minsync) then
+ if (.not. streaming_emit_enabled()) write(*,1010) context_nutc,snr,dt,freq
+ else
+ is_average=nsum.ge.2
+ if(context_bVHF .and. ft.gt.0) then
+ cflags='f '
+ if(is_deep) then
+ cflags='d '
+ write(cflags(2:2),'(i1)') min(qual,9)
+ if(qual.ge.10) cflags(2:2)='*'
+ if(qual.lt.3) decoded(22:22)='?'
+ endif
+ if(is_average) then
+ write(cflags(3:3),'(i1)') min(nsum,9)
+ if(nsum.ge.10) cflags(3:3)='*'
+ endif
+ nap=ishft(ft,-2)
+ if(nap.ne.0) then
+ if(nsum.lt.2) write(cflags(1:3),'(a1,i1," ")') 'a',nap
+ if(nsum.ge.2) write(cflags(1:3),'(a1,2i1)') 'a',nap,min(nsum,9)
+ endif
+ endif
+ csync='# '
+ i=0
+ if(context_bVHF .and. nflip.ne.0 .and. &
+ sync.ge.max(0.0,float(minsync))) then
+ csync='#*'
+ if(nflip.eq.-1) then
+ csync='##'
+ if(decoded.ne.' ') then
+ do i=22,1,-1
+ if(decoded(i:i).ne.' ') exit
+ enddo
+ if(i.gt.18) i=18
+ decoded(i+2:i+4)='OOO'
+ endif
+ endif
+ endif
+ n=len(trim(decoded))
+ if(n.eq.2 .or. n.eq.3) csync='# '
+ if(cflags(1:1).eq.'f') then
+ cflags(2:2)=cflags(3:3)
+ cflags(3:3)=' '
+ endif
+ if (streaming_emit_enabled()) then
+ call streaming_emit_decode("JT65", context_nutc, snr, dt, freq, decoded)
+ else
+ write(*,1010) context_nutc,snr,dt,freq,csync,decoded,cflags
+ end if
+1010 format(i4.4,i4,f5.1,i5,1x,a2,1x,a22,1x,a3)
+ endif
+ if(context_ios13.eq.0) write(13,1012) context_nutc,nint(sync),snr,dt, &
+ float(freq),drift,decoded,ft,nsum,nsmo
+1012 format(i4.4,i4,i5,f6.2,f8.0,i4,3x,a22,' JT65',3i3)
+ call flush(6)
+
+ !$omp end critical(decode_results)
+ select type (typed_this => this)
+ type is (counting_jt65_decoder)
+ typed_this%decoded = typed_this%decoded + 1
+ end select
+ end subroutine jt65_decoded
+
+ subroutine jt9_decoded (this, sync, snr, dt, freq, drift, decoded)
+ implicit none
+
+ class(jt9_decoder), intent(inout) :: this
+ real, intent(in) :: sync
+ integer, intent(in) :: snr
+ real, intent(in) :: dt
+ real, intent(in) :: freq
+ integer, intent(in) :: drift
+ character(len=22), intent(in) :: decoded
+ integer context_nutc, context_ios13
+
+ select type (typed_this => this)
+ type is (counting_jt9_decoder)
+ context_nutc = typed_this%context%nutc
+ context_ios13 = typed_this%context%ios13
+ class default
+ return
+ end select
+
+ !$omp critical(decode_results)
+
+ if (streaming_emit_enabled()) then
+ call streaming_emit_decode("JT9", context_nutc, snr, dt, nint(freq), decoded)
+ else
+ write(*,1000) context_nutc,snr,dt,nint(freq),decoded
+ end if
+1000 format(i4.4,i4,f5.1,i5,1x,'@ ',1x,a22)
+ if(context_ios13.eq.0) write(13,1002) context_nutc,nint(sync),snr,dt,freq, &
+ drift,decoded
+1002 format(i4.4,i4,i5,f6.1,f8.0,i4,3x,a22,' JT9')
+ call flush(6)
+ !$omp end critical(decode_results)
+ select type (typed_this => this)
+ type is (counting_jt9_decoder)
+ typed_this%decoded = typed_this%decoded + 1
+ end select
+ end subroutine jt9_decoded
+
+ subroutine ft8_decodedvar (this,snr,dt,freq,decodedvar,nap,qual)
+ implicit none
+
+ class(ft8_decodervar), intent(inout) :: this
+ integer, intent(in) :: snr
+ real, intent(in) :: dt
+ real, intent(in) :: freq
+ real, intent(in) :: qual
+ character(len=37), intent(in) :: decodedvar
+ integer, intent(in) :: nap
+ real fdiff
+ character*2 annot
+ character c1*12,c2*12,g2*4,w*4
+ integer i1,i2,i3,i4,i5,n,n30,nwrap
+ character*37 decoded0
+ logical isgrid4,first,b0,b1,b2
+ integer context_nutc, context_nfqso, context_ncontest, context_ios13
+ logical context_b_superfox
+ character(len=12) context_mycall
+ data first/.true./
+ save :: first,nwrap
+
+ isgrid4(w)=(len_trim(w).eq.4 .and. &
+ ichar(w(1:1)).ge.ichar('A') .and. ichar(w(1:1)).le.ichar('R') .and. &
+ ichar(w(2:2)).ge.ichar('A') .and. ichar(w(2:2)).le.ichar('R') .and. &
+ ichar(w(3:3)).ge.ichar('0') .and. ichar(w(3:3)).le.ichar('9') .and. &
+ ichar(w(4:4)).ge.ichar('0') .and. ichar(w(4:4)).le.ichar('9'))
+
+ select type (typed_this => this)
+ type is (counting_ft8_decodervar)
+ context_nutc = typed_this%context%nutc
+ context_nfqso = typed_this%context%nfqso
+ context_ncontest = typed_this%context%ncontest
+ context_ios13 = typed_this%context%ios13
+ context_b_superfox = typed_this%context%b_superfox
+ context_mycall = typed_this%context%mycall
+ class default
+ return
+ end select
+
+ if(first) then
+ c2fox=' '
+ g2fox=' '
+ nsnrfox=-99
+ nfreqfox=-99
+ n30z=0
+ nwrap=0
+ nfox=0
+ first=.false.
+ endif
+
+ fdiff=freq-context_nfqso
+ if(abs(fdiff).lt.3.0) ltry_a8=.false.
+
+ decoded0=decodedvar
+
+ annot=' '
+ if(nap.ne.0) then
+ if(nap.ge.9) then
+ write(annot,'(a1,i1)') 'a',9
+ else
+ write(annot,'(a1,i1)') 'a',nap
+ endif
+ if(qual.lt.0.17) decoded0(37:37)='?'
+ endif
+
+ if (streaming_emit_enabled()) then
+ call streaming_emit_decode("FT8", context_nutc, snr, dt, nint(freq), decoded0)
+ else
+ write(*,1000) context_nutc,snr,dt,nint(freq),decoded0,annot
+ end if
+1000 format(i6.6,i4,f5.1,i5,' ~ ',1x,a37,1x,a2)
+
+ if(context_ncontest.eq.6) then
+ i1=index(decoded0,' ')
+ i2=i1 + index(decoded0(i1+1:),' ')
+ i3=i2 + index(decoded0(i2+1:),' ')
+ if(i1.ge.3 .and. i2.ge.7 .and. i3.ge.10) then
+ c1=decoded0(1:i1-1)//' '
+ c2=decoded0(i1+1:i2-1)
+ g2=decoded0(i2+1:i3-1)
+ b0=c1.eq.context_mycall
+ if(c1(1:3).eq.'DE ' .and. index(c2,'/').ge.2) b0=.true.
+ if(len(trim(c1)).ne.len(trim(context_mycall))) then
+ i4=index(trim(c1),trim(context_mycall))
+ i5=index(trim(context_mycall),trim(c1))
+ if(i4.ge.1 .or. i5.ge.1) b0=.true.
+ endif
+ b1=i3-i2.eq.5 .and. isgrid4(g2)
+ b2=i3-i2.eq.1
+ if(b0 .and. (b1.or.b2) .and. (nint(freq).ge.1000 .or. &
+ context_b_superfox)) then
+ n=context_nutc
+ n30=(3600*(n/10000) + 60*mod((n/100),100) + mod(n,100))/30
+ if(n30.lt.n30z) nwrap=nwrap+2880
+ n30z=n30
+ n30=n30+nwrap
+ if(nfox.lt.MAXFOX) nfox=nfox+1
+ c2fox(nfox)=c2
+ g2fox(nfox)=g2
+ nsnrfox(nfox)=snr
+ nfreqfox(nfox)=nint(freq)
+ n30fox(nfox)=n30
+ endif
+ endif
+ endif
+ call flush(6)
+ if(context_ios13.eq.0) call flush(13)
+
+ select type (typed_this => this)
+ type is (counting_ft8_decodervar)
+ typed_this%decodedvar = typed_this%decodedvar + 1
+ typed_this%xdtt(typed_this%decodedvar)=dt
+ end select
+ end subroutine ft8_decodedvar
+
+ subroutine ft8_decoded (this,sync,snr,dt,freq,decoded,nap,qual)
+ implicit none
+
+ class(ft8_decoder), intent(inout) :: this
+ real, intent(in) :: sync
+ integer, intent(in) :: snr
+ real, intent(in) :: dt
+ real, intent(in) :: freq
+ character(len=37), intent(in) :: decoded
+ character c1*12,c2*12,g2*4,w*4
+ integer i0,i1,i2,i3,i4,i5,n,n30,nwrap
+ integer, intent(in) :: nap
+ real, intent(in) :: qual
+ real fdiff
+ character*2 annot
+ character*37 decoded0
+ logical isgrid4,first,b0,b1,b2
+ integer context_nutc, context_nfqso, context_ncontest, context_ios13
+ logical context_b_superfox
+ character(len=12) context_mycall
+ data first/.true./
+ save :: first,nwrap
+
+ isgrid4(w)=(len_trim(w).eq.4 .and. &
+ ichar(w(1:1)).ge.ichar('A') .and. ichar(w(1:1)).le.ichar('R') .and. &
+ ichar(w(2:2)).ge.ichar('A') .and. ichar(w(2:2)).le.ichar('R') .and. &
+ ichar(w(3:3)).ge.ichar('0') .and. ichar(w(3:3)).le.ichar('9') .and. &
+ ichar(w(4:4)).ge.ichar('0') .and. ichar(w(4:4)).le.ichar('9'))
+
+ select type (typed_this => this)
+ type is (counting_ft8_decoder)
+ context_nutc = typed_this%context%nutc
+ context_nfqso = typed_this%context%nfqso
+ context_ncontest = typed_this%context%ncontest
+ context_ios13 = typed_this%context%ios13
+ context_b_superfox = typed_this%context%b_superfox
+ context_mycall = typed_this%context%mycall
+ class default
+ return
+ end select
+
+ if(first) then
+ c2fox=' '
+ g2fox=' '
+ nsnrfox=-99
+ nfreqfox=-99
+ n30z=0
+ nwrap=0
+ nfox=0
+ first=.false.
+ endif
+
+ decoded0=decoded
+ fdiff=freq-context_nfqso
+ if(abs(fdiff).lt.3.0) ltry_a8=.false.
+
+ annot=' '
+ if(nap.ne.0) then
+ write(annot,'(a1,i1)') 'a',nap
+ if(qual.lt.0.17) decoded0(37:37)='?'
+ endif
+
+ i0=1
+ if (streaming_emit_enabled()) then
+ if (i0.le.0) call streaming_emit_decode("FT8", context_nutc, snr, dt, nint(freq), decoded0(1:22))
+ if (i0.gt.0) call streaming_emit_decode("FT8", context_nutc, snr, dt, nint(freq), decoded0)
+ else
+ if(i0.le.0) write(*,1000) context_nutc,snr,dt,nint(freq),decoded0(1:22),annot
+ if(i0.gt.0) write(*,1001) context_nutc,snr,dt,nint(freq),decoded0,annot
+ end if
+1000 format(i6.6,i4,f5.1,i5,' ~ ',1x,a22,1x,a2)
+1001 format(i6.6,i4,f5.1,i5,' ~ ',1x,a37,1x,a2)
+ if(context_ios13.eq.0) write(13,1002) context_nutc,nint(sync),snr,dt,freq,0,decoded0
+1002 format(i6.6,i4,i5,f6.1,f8.0,i4,3x,a37,' FT8')
+
+ if(context_ncontest.eq.6) then
+ i1=index(decoded0,' ')
+ i2=i1 + index(decoded0(i1+1:),' ')
+ i3=i2 + index(decoded0(i2+1:),' ')
+ if(i1.ge.3 .and. i2.ge.7 .and. i3.ge.10) then
+ c1=decoded0(1:i1-1)//' '
+ c2=decoded0(i1+1:i2-1)
+ g2=decoded0(i2+1:i3-1)
+ b0=c1.eq.context_mycall
+ if(c1(1:3).eq.'DE ' .and. index(c2,'/').ge.2) b0=.true.
+ if(len(trim(c1)).ne.len(trim(context_mycall))) then
+ i4=index(trim(c1),trim(context_mycall))
+ i5=index(trim(context_mycall),trim(c1))
+ if(i4.ge.1 .or. i5.ge.1) b0=.true.
+ endif
+ b1=i3-i2.eq.5 .and. isgrid4(g2)
+ b2=i3-i2.eq.1
+ if(b0 .and. (b1.or.b2) .and. (nint(freq).ge.1000 .or. &
+ context_b_superfox)) then
+ n=context_nutc
+ n30=(3600*(n/10000) + 60*mod((n/100),100) + mod(n,100))/30
+ if(n30.lt.n30z) nwrap=nwrap+2880
+ n30z=n30
+ n30=n30+nwrap
+ if(nfox.lt.MAXFOX) nfox=nfox+1
+ c2fox(nfox)=c2
+ g2fox(nfox)=g2
+ nsnrfox(nfox)=snr
+ nfreqfox(nfox)=nint(freq)
+ n30fox(nfox)=n30
+ endif
+ endif
+ endif
+
+ call flush(6)
+ if(context_ios13.eq.0) call flush(13)
+
+ select type (typed_this => this)
+ type is (counting_ft8_decoder)
+ typed_this%decoded = typed_this%decoded + 1
+ end select
+ end subroutine ft8_decoded
+
+ subroutine ft4_decoded (this,sync,snr,dt,freq,decoded,nap,qual)
+ implicit none
+
+ class(ft4_decoder), intent(inout) :: this
+ real, intent(in) :: sync,dt,freq,qual
+ integer, intent(in) :: snr,nap
+ character(len=37), intent(in) :: decoded
+ character*2 annot
+ character*37 decoded0
+ integer context_nutc, context_ios13
+
+ select type (typed_this => this)
+ type is (counting_ft4_decoder)
+ context_nutc = typed_this%context%nutc
+ context_ios13 = typed_this%context%ios13
+ class default
+ return
+ end select
+
+ decoded0=decoded
+
+ annot=' '
+ if(nap.ne.0) then
+ write(annot,'(a1,i1)') 'a',nap
+ if(qual.lt.0.17) decoded0(37:37)='?'
+ endif
+
+ if (streaming_emit_enabled()) then
+ call streaming_emit_decode("FT4", context_nutc, snr, dt, nint(freq), decoded0)
+ else
+ write(*,1001) context_nutc,snr,dt,nint(freq),decoded0,annot
+ end if
+1001 format(i6.6,i4,f5.1,i5,' + ',1x,a37,1x,a2)
+
+ if(context_ios13.eq.0) then
+ write(13,1002,err=10) context_nutc,nint(sync),snr,dt,freq,0,decoded0
+1002 format(i6.6,i4,i5,f6.1,f8.0,i4,3x,a37,' FT4')
+ flush(13)
+ endif
+
+10 call flush(6)
+
+ select type (typed_this => this)
+ type is (counting_ft4_decoder)
+ typed_this%decoded = typed_this%decoded + 1
+ end select
+ end subroutine ft4_decoded
+
+ subroutine fst4_decoded (this,nutc,sync,nsnr,dt,freq,decoded,nap, &
+ qual,ntrperiod,fmid,w50)
+
+ implicit none
+
+ class(fst4_decoder), intent(inout) :: this
+ integer, intent(in) :: nutc
+ real, intent(in) :: sync
+ integer, intent(in) :: nsnr
+ real, intent(in) :: dt
+ real, intent(in) :: freq
+ character(len=37), intent(in) :: decoded
+ integer, intent(in) :: nap
+ real, intent(in) :: qual
+ integer, intent(in) :: ntrperiod
+ real, intent(in) :: fmid
+ real, intent(in) :: w50
+
+ character*2 annot
+ character*37 decoded0
+ character*70 line
+ integer context_ios13
+
+ select type (typed_this => this)
+ type is (counting_fst4_decoder)
+ context_ios13 = typed_this%context%ios13
+ class default
+ return
+ end select
+
+ decoded0=decoded
+ annot=' '
+ if(nap.ne.0) then
+ write(annot,'(a1,i1)') 'a',nap
+ if(qual.lt.0.17) decoded0(37:37)='?'
+ endif
+
+ if(ntrperiod.lt.60) then
+ write(line,1001) nutc,nsnr,dt,nint(freq),decoded0,annot
+1001 format(i6.6,i4,f5.1,i5,' ` ',1x,a37,1x,a2)
+ if(context_ios13.eq.0) write(13,1002) nutc,nint(sync),nsnr,dt,freq,0,decoded0
+1002 format(i6.6,i4,i5,f6.1,f8.0,i4,3x,a37,' FST4')
+ else
+ write(line,1003) nutc,nsnr,dt,nint(freq),decoded0,annot
+1003 format(i4.4,i4,f5.1,i5,' ` ',1x,a37,1x,a2,2f7.3)
+ if(context_ios13.eq.0) write(13,1004) nutc,nint(sync),nsnr,dt,freq,0,decoded0
+1004 format(i4.4,i4,i5,f6.1,f8.0,i4,3x,a37,' FST4')
+ endif
+
+ if(fmid.ne.-999.0) then
+ if(w50.lt.0.95) write(line(65:70),'(f6.3)') w50
+ if(w50.ge.0.95) write(line(65:70),'(f6.2)') w50
+ endif
+
+ if (streaming_emit_enabled()) then
+ call streaming_emit_decode("FST4", nutc, nsnr, dt, nint(freq), decoded0)
+ else
+ write(*,1005) line
+ end if
+1005 format(a70)
+
+ call flush(6)
+ if(context_ios13.eq.0) call flush(13)
+
+ select type (typed_this => this)
+ type is (counting_fst4_decoder)
+ typed_this%decoded = typed_this%decoded + 1
+ end select
+ end subroutine fst4_decoded
+
+ subroutine q65_decoded (this,nutc,snr1,nsnr,dt,freq,decoded,idec, &
+ nused,ntrperiod,iflagdec)
+
+ implicit none
+
+ class(q65_decoder), intent(inout) :: this
+ integer, intent(in) :: nutc
+ real, intent(in) :: snr1
+ integer, intent(in) :: nsnr
+ real, intent(in) :: dt
+ real, intent(in) :: freq
+ character(len=37), intent(in) :: decoded
+ integer, intent(in) :: idec
+ integer, intent(in) :: nused
+ integer, intent(in) :: ntrperiod
+ integer, intent(in) :: iflagdec !Recovered spare 78th bit (see genq65/q65_ap)
+ character*4 cflags
+ integer context_ios13
+
+ select type (typed_this => this)
+ type is (counting_q65_decoder)
+ context_ios13 = typed_this%context%ios13
+ class default
+ return
+ end select
+
+ cflags=' '
+ if(idec.ge.0) then
+ cflags='q '
+ write(cflags(2:2),'(i1)') idec
+ if(nused.ge.2) write(cflags(3:3),'(i1)') nused
+ ! Append '#' (e.g. "q0#", "q3#") when the sender flagged bit78=1,
+ ! copying our last transmission -- leave the qualifier unchanged
+ ! ("q0", "q3", ...) otherwise.
+ if(iflagdec.eq.1) cflags=trim(cflags)//'#'
+ endif
+
+ if(ntrperiod.lt.60) then
+ if (streaming_emit_enabled()) then
+ call streaming_emit_decode("Q65", nutc, nsnr, dt, nint(freq), decoded)
+ else
+ if(len_trim(cflags).gt.3) then
+ write(*,1005) nutc,nsnr,dt,nint(freq),decoded,cflags
+ else
+ write(*,1001) nutc,nsnr,dt,nint(freq),decoded,cflags
+ endif
+ end if
+1001 format(i6.6,i4,f5.1,i5,' : ',1x,a37,1x,a3)
+1005 format(i6.6,i4,f5.1,i5,' : ',1x,a37,1x,a4)
+ if(context_ios13.eq.0) write(13,1002) nutc,nint(snr1),nsnr,dt,freq,0,decoded
+1002 format(i6.6,i4,i5,f6.1,f8.0,i4,3x,a37,' Q65')
+ else
+ if (streaming_emit_enabled()) then
+ call streaming_emit_decode("Q65", nutc, nsnr, dt, nint(freq), decoded)
+ else
+ if(len_trim(cflags).gt.3) then
+ write(*,1006) nutc,nsnr,dt,nint(freq),decoded,cflags
+ else
+ write(*,1003) nutc,nsnr,dt,nint(freq),decoded,cflags
+ endif
+ end if
+1003 format(i4.4,i4,f5.1,i5,' : ',1x,a37,1x,a3)
+1006 format(i4.4,i4,f5.1,i5,' : ',1x,a37,1x,a4)
+ if(context_ios13.eq.0) write(13,1004) nutc,nint(snr1),nsnr,dt,freq,0,decoded
+1004 format(i4.4,i4,i5,f6.1,f8.0,i4,3x,a37,' Q65')
+ endif
+ call flush(6)
+ if(context_ios13.eq.0) call flush(13)
+
+ select type (typed_this => this)
+ type is (counting_q65_decoder)
+ if(idec.ge.0) typed_this%decoded = typed_this%decoded + 1
+ end select
+ end subroutine q65_decoded
+
+end module decoder_callbacks
diff --git a/lib/decoder_ipc_atomic.f90 b/lib/decoder_ipc_atomic.f90
new file mode 100644
index 00000000..2814168d
--- /dev/null
+++ b/lib/decoder_ipc_atomic.f90
@@ -0,0 +1,49 @@
+module decoder_ipc_atomic
+ use, intrinsic :: iso_c_binding, only: c_int
+ implicit none
+
+ integer(c_int), parameter :: DECODER_IPC_CLAIM_INVALID = -2
+ integer(c_int), parameter :: DECODER_IPC_CLAIM_INCOMPATIBLE = -1
+ integer(c_int), parameter :: DECODER_IPC_CLAIM_NONE = 0
+ integer(c_int), parameter :: DECODER_IPC_CLAIMED = 1
+ integer(c_int), parameter :: DECODER_IPC_CLAIM_SHUTDOWN = 2
+
+ interface
+ function decoder_ipc_control_try_claim(generation, state, version, &
+ claimed_generation) bind(C)
+ import c_int
+ integer(c_int), intent(inout) :: generation
+ integer(c_int), intent(inout) :: state
+ integer(c_int), intent(in) :: version
+ integer(c_int), intent(out) :: claimed_generation
+ integer(c_int) :: decoder_ipc_control_try_claim
+ end function decoder_ipc_control_try_claim
+
+ function decoder_ipc_control_finish(generation, state, version, &
+ request_generation) bind(C)
+ import c_int
+ integer(c_int), intent(in) :: generation
+ integer(c_int), intent(inout) :: state
+ integer(c_int), intent(in) :: version
+ integer(c_int), value :: request_generation
+ integer(c_int) :: decoder_ipc_control_finish
+ end function decoder_ipc_control_finish
+
+ subroutine decoder_ipc_progress_bind(generation, state, version, &
+ progress) bind(C)
+ import c_int
+ integer(c_int), intent(in) :: generation
+ integer(c_int), intent(in) :: state
+ integer(c_int), intent(in) :: version
+ integer(c_int), intent(inout) :: progress
+ end subroutine decoder_ipc_progress_bind
+
+ subroutine decoder_ipc_progress_unbind() bind(C)
+ end subroutine decoder_ipc_progress_unbind
+
+ subroutine decoder_ipc_progress_report(request_generation) bind(C)
+ import c_int
+ integer(c_int), value :: request_generation
+ end subroutine decoder_ipc_progress_report
+ end interface
+end module decoder_ipc_atomic
diff --git a/lib/decoder_ipc_control.cpp b/lib/decoder_ipc_control.cpp
new file mode 100644
index 00000000..e72251d7
--- /dev/null
+++ b/lib/decoder_ipc_control.cpp
@@ -0,0 +1,191 @@
+#include "decoder_ipc_control.h"
+
+#include <atomic>
+#include <cstdint>
+#include <limits>
+
+#if defined (_MSC_VER)
+#include <intrin.h>
+#endif
+
+static_assert (sizeof (int) == sizeof (std::int32_t),
+ "decoder IPC requires 32-bit control words");
+
+namespace
+{
+ std::atomic<int const *> progressGeneration {nullptr};
+ std::atomic<int const *> progressState {nullptr};
+ std::atomic<int const *> progressVersion {nullptr};
+ std::atomic<int *> progressCounter {nullptr};
+
+#if defined (_MSC_VER)
+ static_assert (sizeof (long) == sizeof (int),
+ "decoder IPC requires 32-bit MSVC interlocked words");
+
+ int atomicLoad (int const * value)
+ {
+ return static_cast<int> (_InterlockedCompareExchange (
+ reinterpret_cast<volatile long *> (const_cast<int *> (value)), 0, 0));
+ }
+
+ void atomicStore (int * value, int desired)
+ {
+ _InterlockedExchange (reinterpret_cast<volatile long *> (value), desired);
+ }
+
+ bool compareExchange (int * value, int expected, int desired)
+ {
+ return expected == _InterlockedCompareExchange (
+ reinterpret_cast<volatile long *> (value), desired, expected);
+ }
+#else
+ static_assert (__atomic_always_lock_free (sizeof (int), nullptr),
+ "decoder IPC control words must be lock-free");
+
+ int atomicLoad (int const * value)
+ {
+ return __atomic_load_n (value, __ATOMIC_ACQUIRE);
+ }
+
+ void atomicStore (int * value, int desired)
+ {
+ __atomic_store_n (value, desired, __ATOMIC_RELEASE);
+ }
+
+ bool compareExchange (int * value, int expected, int desired)
+ {
+ return __atomic_compare_exchange_n (value, &expected, desired, false,
+ __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE);
+ }
+#endif
+
+ bool hasCurrentVersion (int const * version)
+ {
+ return DECODER_IPC_VERSION == atomicLoad (version);
+ }
+}
+
+extern "C" int decoder_ipc_atomic_load (int const * value)
+{
+ return atomicLoad (value);
+}
+
+extern "C" void decoder_ipc_control_initialize (int * generation, int * state,
+ int * version, int * progress)
+{
+ atomicStore (generation, 0);
+ atomicStore (progress, 0);
+ atomicStore (version, DECODER_IPC_VERSION);
+ atomicStore (state, DECODER_IPC_IDLE);
+}
+
+extern "C" void decoder_ipc_control_shutdown (int * state,
+ int * legacy_acknowledgment)
+{
+ atomicStore (state, DECODER_IPC_SHUTDOWN);
+ atomicStore (legacy_acknowledgment, 1);
+}
+
+extern "C" int decoder_ipc_control_publish (int * generation, int * state,
+ int const * version,
+ int * progress,
+ int request_generation)
+{
+ if (request_generation <= 0 || !hasCurrentVersion (version)
+ || DECODER_IPC_IDLE != atomicLoad (state))
+ {
+ return 0;
+ }
+
+ atomicStore (progress, 0);
+ atomicStore (generation, request_generation);
+ return compareExchange (state, DECODER_IPC_IDLE, DECODER_IPC_READY);
+}
+
+extern "C" int decoder_ipc_control_try_claim (int * generation, int * state,
+ int const * version,
+ int * claimed_generation)
+{
+ if (!hasCurrentVersion (version)) return DECODER_IPC_CLAIM_INCOMPATIBLE;
+
+ auto const currentState = atomicLoad (state);
+ if (DECODER_IPC_SHUTDOWN == currentState) return DECODER_IPC_CLAIM_SHUTDOWN;
+ if (DECODER_IPC_READY != currentState) return DECODER_IPC_CLAIM_NONE;
+
+ auto const currentGeneration = atomicLoad (generation);
+ if (currentGeneration <= 0) return DECODER_IPC_CLAIM_INVALID;
+
+ if (!compareExchange (state, DECODER_IPC_READY, DECODER_IPC_DECODING))
+ {
+ return DECODER_IPC_CLAIM_NONE;
+ }
+
+ *claimed_generation = currentGeneration;
+ return DECODER_IPC_CLAIMED;
+}
+
+extern "C" int decoder_ipc_control_finish (int const * generation, int * state,
+ int const * version,
+ int request_generation)
+{
+ return request_generation > 0
+ && hasCurrentVersion (version)
+ && request_generation == atomicLoad (generation)
+ && compareExchange (state, DECODER_IPC_DECODING, DECODER_IPC_COMPLETE);
+}
+
+extern "C" int decoder_ipc_control_consume (int const * generation, int * state,
+ int const * version,
+ int request_generation)
+{
+ if (request_generation <= 0 || !hasCurrentVersion (version)
+ || request_generation != atomicLoad (generation))
+ {
+ return 0;
+ }
+
+ return compareExchange (state, DECODER_IPC_COMPLETE, DECODER_IPC_IDLE);
+}
+
+extern "C" void decoder_ipc_progress_bind (int const * generation,
+ int const * state,
+ int const * version,
+ int * progress)
+{
+ progressGeneration.store (generation, std::memory_order_relaxed);
+ progressState.store (state, std::memory_order_relaxed);
+ progressVersion.store (version, std::memory_order_relaxed);
+ progressCounter.store (progress, std::memory_order_release);
+}
+
+extern "C" void decoder_ipc_progress_unbind ()
+{
+ progressCounter.store (nullptr, std::memory_order_release);
+ progressVersion.store (nullptr, std::memory_order_relaxed);
+ progressState.store (nullptr, std::memory_order_relaxed);
+ progressGeneration.store (nullptr, std::memory_order_relaxed);
+}
+
+extern "C" void decoder_ipc_progress_report (int request_generation)
+{
+ auto * progress = progressCounter.load (std::memory_order_acquire);
+ auto const * version = progressVersion.load (std::memory_order_relaxed);
+ auto const * state = progressState.load (std::memory_order_relaxed);
+ auto const * generation = progressGeneration.load (std::memory_order_relaxed);
+ if (!progress || !version || !state || !generation
+ || request_generation <= 0
+ || DECODER_IPC_VERSION != atomicLoad (version)
+ || DECODER_IPC_DECODING != atomicLoad (state)
+ || request_generation != atomicLoad (generation))
+ {
+ return;
+ }
+
+ for (;;)
+ {
+ auto const current = atomicLoad (progress);
+ auto const next = std::numeric_limits<int>::max () == current
+ ? 1 : current + 1;
+ if (compareExchange (progress, current, next)) return;
+ }
+}
diff --git a/lib/decoder_ipc_control.h b/lib/decoder_ipc_control.h
new file mode 100644
index 00000000..5bf593ba
--- /dev/null
+++ b/lib/decoder_ipc_control.h
@@ -0,0 +1,40 @@
+#ifndef DECODER_IPC_CONTROL_H
+#define DECODER_IPC_CONTROL_H
+
+#include "../DecoderIpcProtocol.h"
+
+enum decoder_ipc_claim_result
+{
+ DECODER_IPC_CLAIM_INVALID = -2,
+ DECODER_IPC_CLAIM_INCOMPATIBLE = -1,
+ DECODER_IPC_CLAIM_NONE = 0,
+ DECODER_IPC_CLAIMED = 1,
+ DECODER_IPC_CLAIM_SHUTDOWN = 2
+};
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+int decoder_ipc_atomic_load (int const * value);
+void decoder_ipc_control_initialize (int * generation, int * state, int * version,
+ int * progress);
+void decoder_ipc_control_shutdown (int * state, int * legacy_acknowledgment);
+int decoder_ipc_control_publish (int * generation, int * state,
+ int const * version, int * progress,
+ int request_generation);
+int decoder_ipc_control_try_claim (int * generation, int * state, int const * version,
+ int * claimed_generation);
+int decoder_ipc_control_finish (int const * generation, int * state,
+ int const * version, int request_generation);
+int decoder_ipc_control_consume (int const * generation, int * state,
+ int const * version, int request_generation);
+void decoder_ipc_progress_bind (int const * generation, int const * state,
+ int const * version, int * progress);
+void decoder_ipc_progress_unbind (void);
+void decoder_ipc_progress_report (int request_generation);
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/lib/digi-contest.txt b/lib/digi-contest.txt
index b0eafaec..a45e4d04 100644
--- a/lib/digi-contest.txt
+++ b/lib/digi-contest.txt
@@ -95,13 +95,14 @@ CQ WW RTTY US/Can: RST CQZ state/prov R 579 8 NJ r1 r3 z6 s6 16 72
ARRL VHF+ grid4 R FN42 r1 g15 16 72
-EU VHF+ rpt serial grid6 R 590013 IO91NP r1 r3 n12 g25 41 97
+EU VHF+ rpt serial grid6 R 590013 IO91NP r1 r3 n11 g25 40 96
------------------------------------------------------------------------------
Meaning and number of bits for each exchange component:
c3 Operating class (A-F)
g15 grid4
g25 grid6
+n11 Serial number for EU VHF Type 5
n12 Serial number
n5 Number of transmitters (0-31)
r1 acknowledgment of received exchange
diff --git a/lib/echo_snr.f90 b/lib/echo_snr.f90
index 786f1aea..ce806fa6 100644
--- a/lib/echo_snr.f90
+++ b/lib/echo_snr.f90
@@ -15,7 +15,14 @@ subroutine echo_snr(sa,sb,fspread,blue,red,snrdb,db_err,fpeak,snr_detect)
i3=nint((1500.0 + wh)/df) - 2048
i4=nint((1500.0 + 2.0*wh)/df) - 2048
+ blue=0.
+ red=0.
+ snrdb=-99.
+ db_err=1.8
+ fpeak=0.
+ snr_detect=0.
baseline=(sum(sb(i1:i2-1)) + sum(sb(i3+1:i4)))/(i2+i4-i1-i3)
+ if(.not.(baseline.gt.0.)) return
blue=sa/baseline
red=sb/baseline
psig=sum(red(i2:i3)-1.0)
@@ -23,6 +30,7 @@ subroutine echo_snr(sa,sb,fspread,blue,red,snrdb,db_err,fpeak,snr_detect)
snrdb=db(psig/pnoise_2500)
smax=0.
+ ipk=2048
mh=max(1,nint(0.2*fspread/df))
do i=i2,i3
ssum=sum(red(i-mh:i+mh))
@@ -36,7 +44,7 @@ subroutine echo_snr(sa,sb,fspread,blue,red,snrdb,db_err,fpeak,snr_detect)
call averms(red(i1:i2-1),i2-i1,-1,ave1,rms1)
call averms(red(i3+1:i4),i4-i3,-1,ave2,rms2)
perr=0.707*(rms1+rms2)*sqrt(float(i2-i1+i4-i3))
- snr_detect=psig/perr
+ if(perr.gt.0.) snr_detect=psig/perr
db_err=0.8
if(snrdb.lt.-10.0) db_err=0.8
if(snrdb.lt.-11.0) db_err=0.9
diff --git a/lib/echosim.f90 b/lib/echosim.f90
index 96854aae..aa70bb5a 100644
--- a/lib/echosim.f90
+++ b/lib/echosim.f90
@@ -3,15 +3,21 @@ program echosim
! Generate simulated echo-mode files -- self-echo or "measure"
use wavhdr
- parameter (NWAVE=27648,NMAX=32768,NZ=36000)
+ use julian
+ parameter (NWAVE=27648,NZ=36000)
type(hdr) h !Header for .wav file
character arg*12,fname*17
- complex c0(0:NMAX-1)
- complex c(0:NMAX-1)
+ complex c0(0:NZ-1)
real*4 level_1,level_2
real*8 f0,dt,twopi,phi,dphi
real wave(NZ)
integer*2 iwave(NZ) !Generated full-length waveform
+ character*32 isft !WAV LIST/INFO trailer fields
+ character*24 icrd
+ character*64 icmt
+ integer*8 tsec8
+ integer gmt(9)
+ integer*4 trailerlen,wav_trailer_length
equivalence (nDop0,iwave(1))
equivalence (nDopAudio0,iwave(3))
equivalence (nfrit0,iwave(5))
@@ -59,6 +65,15 @@ program echosim
write(*,1000)
1000 format(' N f0 fDop fSpread SNR File name'/51('-'))
+ isft='WSJT-X echosim'
+ tsec8=itime8()
+ call gmtime(int(tsec8,4),gmt)
+ write(icrd,1004) gmt(6)+1900,gmt(5)+1,gmt(4),gmt(3),gmt(2),gmt(1)
+1004 format(i4.4,'-',i2.2,'-',i2.2,'T',i2.2,':',i2.2,':',i2.2,'Z')
+ write(icmt,1005) nfiles
+1005 format('Mode=Echo; Simulated by echosim; nfiles=',i0)
+ trailerlen=wav_trailer_length(isft,icrd,icmt)
+
do ifile=1,nfiles
wave=0.
@@ -72,9 +87,7 @@ program echosim
enddo
c0(NWAVE:)=0.
if(fspread.gt.0.0) call fspread_lorentz(c0,fspread)
- c=sig*c0
- wave(1:NWAVE)=imag(c(1:NWAVE))
- peak=maxval(abs(wave))
+ wave(1:NWAVE)=sig*imag(c0(0:NWAVE-1))
endif
if(snrdb.lt.90) then
@@ -109,18 +122,66 @@ program echosim
f10=f0 + fdop
fspread0=fspread
- h=default_header(12000,NMAX)
+ h=default_header(12000,NZ)
+ h%lenfile=h%lenfile + trailerlen ! Include trailing metadata in the RIFF size
n=3*(ifile-1)
ihr=n/3600
imin=(n-3600*ihr)/60
isec=mod(n,60)
write(fname,1102) ihr,imin,isec
1102 format('000000_',3i2.2,'.wav')
- open(10,file=fname,status='unknown',access='stream')
+ open(10,file=fname,status='replace',access='stream')
write(10) h,iwave !Save to *.wav file
+ call write_wav_info_trailer(10,isft,icrd,icmt)
close(10)
write(*,1110) ifile,f0,fdop,fspread,snrdb,fname
1110 format(i4,4f7.1,2x,a17)
enddo
999 end program echosim
+
+integer*4 function wav_info_field_bytes(nchar)
+! Match BWFFile's NUL-terminated, word-aligned INFO subchunk layout.
+ integer, intent(in) :: nchar
+ integer*4 n
+ n=nchar+1
+ wav_info_field_bytes=8+n+mod(n,2)
+end function wav_info_field_bytes
+
+integer*4 function wav_trailer_length(isft,icrd,icmt)
+! Return the complete LIST chunk size, including its 8-byte header.
+ character(len=*), intent(in) :: isft,icrd,icmt
+ integer*4 wav_info_field_bytes
+ wav_trailer_length = 8 + 4 & !'LIST' id+size, 'INFO'
+ + wav_info_field_bytes(len_trim(isft)) &
+ + wav_info_field_bytes(len_trim(icrd)) &
+ + wav_info_field_bytes(len_trim(icmt))
+end function wav_trailer_length
+
+subroutine write_wav_info_trailer(lu,isft,icrd,icmt)
+! Append LIST/INFO metadata at the current stream position.
+ integer, intent(in) :: lu
+ character(len=*), intent(in) :: isft,icrd,icmt
+ integer*4 listlen,wav_info_field_bytes
+
+ listlen = 4 & !'INFO'
+ + wav_info_field_bytes(len_trim(isft)) &
+ + wav_info_field_bytes(len_trim(icrd)) &
+ + wav_info_field_bytes(len_trim(icmt))
+
+ write(lu) 'LIST',listlen,'INFO'
+ call write_wav_info_field(lu,'ISFT',isft(1:len_trim(isft)))
+ call write_wav_info_field(lu,'ICRD',icrd(1:len_trim(icrd)))
+ call write_wav_info_field(lu,'ICMT',icmt(1:len_trim(icmt)))
+end subroutine write_wav_info_trailer
+
+subroutine write_wav_info_field(lu,id,value)
+! Write one NUL-terminated, word-aligned INFO subchunk.
+ integer, intent(in) :: lu
+ character*4, intent(in) :: id
+ character(len=*), intent(in) :: value
+ integer*4 n
+ n=len(value)+1
+ write(lu) id,n,value,char(0)
+ if(mod(n,2).eq.1) write(lu) char(0)
+end subroutine write_wav_info_field
diff --git a/lib/emedop.f90 b/lib/emedop.f90
index 4a95fb87..da57bb9c 100644
--- a/lib/emedop.f90
+++ b/lib/emedop.f90
@@ -1,10 +1,15 @@
program emedop
+ use jpl_ephemeris_status, only: EPHEMERIS_INVALID_INPUT, &
+ EPHEMERIS_UNAVAILABLE
real*8 txfreq8
real*8 rxfreq8
real*4 LST
real*4 lat_a
real*4 lat_b
+ integer start_year,start_month,start_day
+ integer stop_year,stop_month,stop_day
+ integer ephemeris_result_a,ephemeris_result_b
character*80 infile
character*256 jpleph_file_name
common/jplcom/jpleph_file_name
@@ -24,13 +29,27 @@ program emedop
read(10,1001) lat_b
read(10,1001) wlon_b
read(10,1001) txfreq8
- read(10,1002) nyear,month,nday,ih,im,is
+ read(10,1002) start_year,start_month,start_day,ih,im,is
1002 format(10x,i4,2i2,1x,i2,1x,i2,1x,i2)
sec_start=3600.0*ih + 60.0*im + is
- read(10,1002) nyear,month,nday,ih,im,is
+ read(10,1002) stop_year,stop_month,stop_day,ih,im,is
sec_stop=3600.0*ih + 60.0*im + is
read(10,1001) sec_step
+ if(start_year.ne.stop_year .or. start_month.ne.stop_month .or. &
+ start_day.ne.stop_day) then
+ print*,'Start and stop dates must be the same'
+ go to 999
+ endif
+ if(sec_stop.lt.sec_start) then
+ print*,'Stop time must not precede start time'
+ go to 999
+ endif
+ if(sec_step.le.0.0) then
+ print*,'Time step must be positive'
+ go to 999
+ endif
+
write(*,1005)
1005 format(' Date UTC Tx Freq Rx Freq Doppler'/ &
'------------------------------------------------------')
@@ -40,11 +59,23 @@ program emedop
do icalc=1,ncalc
uth=sec/3600.0
- call MoonDopJPL(nyear,month,nday,uth,-wlon_a,lat_a,RAMoon,DecMoon, &
- LST,HA,AzMoon,ElMoon,vr_a,techo)
+ call MoonDopJPL(start_year,start_month,start_day,uth,-wlon_a,lat_a, &
+ RAMoon,DecMoon, &
+ LST,HA,AzMoon,ElMoon,vr_a,techo,ephemeris_result_a)
- call MoonDopJPL(nyear,month,nday,uth,-wlon_b,lat_b,RAMoon,DecMoon, &
- LST,HA,AzMoon,ElMoon,vr_b,techo)
+ call MoonDopJPL(start_year,start_month,start_day,uth,-wlon_b,lat_b, &
+ RAMoon,DecMoon, &
+ LST,HA,AzMoon,ElMoon,vr_b,techo,ephemeris_result_b)
+ if(ephemeris_result_a.eq.EPHEMERIS_INVALID_INPUT .or. &
+ ephemeris_result_b.eq.EPHEMERIS_INVALID_INPUT) then
+ print*,'Invalid date or time in input file'
+ go to 999
+ endif
+ if(ephemeris_result_a.eq.EPHEMERIS_UNAVAILABLE .or. &
+ ephemeris_result_b.eq.EPHEMERIS_UNAVAILABLE) then
+ print*,'Ephemeris calculation failed'
+ go to 999
+ endif
dop_a=-txfreq8*vr_a/2.99792458e5 !One-way Doppler from a
dop_b=-txfreq8*vr_b/2.99792458e5 !One-way Doppler to b
@@ -54,7 +85,8 @@ program emedop
ih=sec/3600.0
im=(sec-ih*3600.0)/60.0
is=nint(mod(sec,60.0))
- write(*,1010) nyear,month,nday,ih,im,is,txFreq8,rxFreq8,doppler
+ write(*,1010) start_year,start_month,start_day,ih,im,is,txFreq8, &
+ rxFreq8,doppler
1010 format(i4,2i2.2,2x,i2.2,':',i2.2,':',i2.2,2f13.7,f8.1)
sec=sec + sec_step
@@ -64,4 +96,3 @@ program emedop
999 end program emedop
-
diff --git a/lib/ephem.f90 b/lib/ephem.f90
index a24ddbd0..be5b711a 100644
--- a/lib/ephem.f90
+++ b/lib/ephem.f90
@@ -1,85 +1,174 @@
subroutine ephem(mjd0,dut,east_long,geodetic_lat,height,nspecial, &
- RA,Dec,Az,El,techo,dop,fspread_1GHz,vr)
+ RA,Dec,Az,El,techo,dop,fspread_1GHz,vr,ephemeris_result)
+ use ieee_arithmetic, only: ieee_is_finite
+ use jpl_ephemeris_status, only: JPL_STATUS_OK, EPHEMERIS_JPL, &
+ EPHEMERIS_ANALYTIC_FALLBACK, EPHEMERIS_UNAVAILABLE
implicit real*8 (a-h,o-z)
- real*8 jd !Time of observationa as a Julian Date
- real*8 mjd,mjd0 !Modified Julian Date
- real*8 prec(3,3) !Precession matrix, J2000 to Date
- real*8 rmatn(3,3) !Nutation matrix
- real*8 rme2000(6) !Vector from Earth center to Moon, JD2000
- real*8 rmeDate(6) !Vector from Earth center to Moon at Date
- real*8 rmeTrue(6) !Include nutation
- real*8 raeTrue(6) !Vector from Earth center to Obs at Date
- real*8 rmaTrue(6) !Vector from Obs to Moon at Date
- logical km,bary !Set km=.true. to get km, km/s from ephemeris
- common/stcomx/km,bary,pvsun(6) !Common used in JPL subroutines
+ real*8 jd
+ real*8 mjd,mjd0
+ real*8 prec(3,3)
+ real*8 rmatn(3,3)
+ real*8 rme2000(6,2)
+ real*8 rmeDate(6)
+ real*8 rmeTrue(6)
+ real*8 raeTrue(6)
+ real*8 rmaTrue(6)
+ real*8 djutc_sample(2),jd_sample(2),djtt_sample(2)
+ real*8, parameter :: max_lunar_position_km=1.d7
+ real*8, parameter :: max_lunar_velocity_km_s=100.d0
+ logical km,bary,jpl_available,use_jpl,derived_valid
+ integer ephemeris_result,jpl_status,attempt
+ common/stcomx/km,bary,pvsun(6)
common/librcom/xl(2),b(2)
- twopi=8.d0*atan(1.d0) !Define some constants
+ RA=0.d0
+ Dec=0.d0
+ Az=0.d0
+ El=0.d0
+ techo=0.d0
+ dop=0.d0
+ fspread_1GHz=0.d0
+ vr=0.d0
+ ephemeris_result=EPHEMERIS_UNAVAILABLE
+
+ twopi=8.d0*atan(1.d0)
rad=360.d0/twopi
clight=2.99792458d5
au2km=0.1495978706910000d9
- pi=0.5d0*twopi
- pio2=0.5d0*pi
km=.true.
freq=1000.0d6
+ jpl_available=nspecial.ne.8
do jj=1,2
mjd=mjd0
if(jj.eq.1) mjd=mjd - 1.d0/1440.d0
- djutc=mjd
- jd=2400000.5d0 + mjd
- djtt=mjd + sla_DTT(jd)/86400.d0
- ttjd=jd + sla_DTT(jd)/86400.d0
-
- if(nspecial.ne.8) then
- call pleph(ttjd,10,3,rme2000) !RME (J2000) from JPL ephemeris
-
- year=2000.d0 + (jd-2451545.d0)/365.25d0
- call sla_PREC (2000.0d0, year, prec) !Get precession matrix
- rmeDate(1:3)=matmul(prec,rme2000(1:3)) !Moon geocentric xyz at Date
- rmeDate(4:6)=matmul(prec,rme2000(4:6)) !Moon geocentric vel at Date
- else
- call sla_DMOON(djtt,rmeDate) !No JPL ephemeris, use DMOON
- rmeDate=rmeDate*au2km
- endif
+ djutc_sample(jj)=mjd
+ jd_sample(jj)=2400000.5d0 + mjd
+ djtt_sample(jj)=mjd + sla_DTT(jd_sample(jj))/86400.d0
- if(nspecial.eq.7) then
- rmeTrue=rmeDate
- else
-!Nutation to true equinox of Date
- call sla_NUT(djtt,rmatn)
- call sla_DMXV(rmatn,rmeDate,rmeTrue)
- call sla_DMXV(rmatn,rmeDate(4),rmeTrue(4))
+ if(jpl_available) then
+ ttjd=2400000.5d0 + djtt_sample(jj)
+ call pleph(ttjd,10,3,rme2000(:,jj),jpl_status)
+ if(jpl_status.ne.JPL_STATUS_OK) jpl_available=.false.
+ if(jpl_available) then
+ if(.not.all(ieee_is_finite(rme2000(:,jj)))) &
+ jpl_available=.false.
+ endif
+ if(jpl_available) then
+ if(any(abs(rme2000(1:3,jj)).gt.max_lunar_position_km) &
+ .or. any(abs(rme2000(4:6,jj)).gt. &
+ max_lunar_velocity_km_s)) &
+ jpl_available=.false.
+ endif
endif
+ enddo
+
+ do attempt=1,2
+ use_jpl=jpl_available
+ derived_valid=.true.
+
+ do jj=1,2
+ djutc=djutc_sample(jj)
+ jd=jd_sample(jj)
+ djtt=djtt_sample(jj)
+
+ if(use_jpl) then
+ year=2000.d0 + (jd-2451545.d0)/365.25d0
+ call sla_PREC(2000.0d0,year,prec)
+ rmeDate(1:3)=matmul(prec,rme2000(1:3,jj))
+ rmeDate(4:6)=matmul(prec,rme2000(4:6,jj))
+ else
+ call sla_DMOON(djtt,rmeDate)
+ rmeDate=rmeDate*au2km
+ endif
+ if(.not.all(ieee_is_finite(rmeDate))) then
+ derived_valid=.false.
+ exit
+ endif
-! Local Apparent Sidereal Time:
- djut1=djutc + dut/86400.d0
- if(nspecial.eq.6) djut1=djutc
- xlast=sla_DRANRM(sla_GMST(djut1) + sla_EQEQX(djtt) + east_long)
- call sla_PVOBS(geodetic_lat,height,xlast,raeTrue)
- rmaTrue=rmeTrue - raeTrue*au2km
-
- if(nspecial.ne.2) then
-! Allow for planetary aberration
- tl=499.004782D0*SQRT(rmaTrue(1)**2 + rmaTrue(2)**2 + rmaTrue(3)**2)
- rmaTrue(1:3)=rmaTrue(1:3)-tl*rmaTrue(4:6)/au2km
+ if(nspecial.eq.7) then
+ rmeTrue=rmeDate
+ else
+ call sla_NUT(djtt,rmatn)
+ call sla_DMXV(rmatn,rmeDate,rmeTrue)
+ call sla_DMXV(rmatn,rmeDate(4),rmeTrue(4))
+ endif
+ if(.not.all(ieee_is_finite(rmeTrue))) then
+ derived_valid=.false.
+ exit
+ endif
+
+ djut1=djutc + dut/86400.d0
+ if(nspecial.eq.6) djut1=djutc
+ xlast=sla_DRANRM(sla_GMST(djut1) + sla_EQEQX(djtt) + &
+ east_long)
+ call sla_PVOBS(geodetic_lat,height,xlast,raeTrue)
+ rmaTrue=rmeTrue - raeTrue*au2km
+ if(.not.ieee_is_finite(xlast) .or. &
+ .not.all(ieee_is_finite(raeTrue)) .or. &
+ .not.all(ieee_is_finite(rmaTrue))) then
+ derived_valid=.false.
+ exit
+ endif
+
+ if(nspecial.ne.2) then
+ tl=499.004782D0*SQRT(rmaTrue(1)**2 + rmaTrue(2)**2 + &
+ rmaTrue(3)**2)
+ rmaTrue(1:3)=rmaTrue(1:3)-tl*rmaTrue(4:6)/au2km
+ if(.not.ieee_is_finite(tl) .or. &
+ .not.all(ieee_is_finite(rmaTrue))) then
+ derived_valid=.false.
+ exit
+ endif
+ endif
+
+ call sla_DC62S(rmaTrue,RA,Dec,dist,RAdot,DECdot,vr)
+ dop=-2.d0 * freq * vr/clight
+ techo=2.d0*dist/clight
+ call libration(jd,RA,Dec,xl(jj),b(jj))
+ if(.not.all(ieee_is_finite((/RA,Dec,dist,RAdot,DECdot,vr, &
+ dop,techo,xl(jj),b(jj)/)))) then
+ derived_valid=.false.
+ exit
+ endif
+ enddo
+
+ if(derived_valid) then
+ dldt=57.2957795131*(xl(2)-xl(1))
+ dbdt=57.2957795131*(b(2)-b(1))
+ rate=sqrt((2*dldt)**2 + (2*dbdt)**2)
+ fspread_1GHz=0.5*6741*rate
+ call sla_DE2H(xlast-RA,Dec,geodetic_lat,Az,El)
+ if(.not.all(ieee_is_finite((/dldt,dbdt,rate,fspread_1GHz, &
+ Az,El/)))) derived_valid=.false.
endif
-!Topocentric RA, Dec, dist, velocity
- call sla_DC62S(rmaTrue,RA,Dec,dist,RAdot,DECdot,vr)
- dop=-2.d0 * freq * vr/clight !EME doppler shift
- techo=2.d0*dist/clight !Echo delay time (s)
- call libration(jd,RA,Dec,xl(jj),b(jj))
+ if(use_jpl .and. .not.derived_valid) then
+ jpl_available=.false.
+ cycle
+ endif
+ exit
enddo
- fspread_1GHz=0.0d0
- dldt=57.2957795131*(xl(2)-xl(1))
- dbdt=57.2957795131*(b(2)-b(1))
- rate=sqrt((2*dldt)**2 + (2*dbdt)**2)
- fspread_1GHz=0.5*6741*rate
-
- call sla_DE2H(xlast-RA,Dec,geodetic_lat,Az,El)
+ if(derived_valid) then
+ if(use_jpl) then
+ ephemeris_result=EPHEMERIS_JPL
+ else
+ ephemeris_result=EPHEMERIS_ANALYTIC_FALLBACK
+ endif
+ else
+ ephemeris_result=EPHEMERIS_UNAVAILABLE
+ RA=0.d0
+ Dec=0.d0
+ Az=0.d0
+ El=0.d0
+ techo=0.d0
+ dop=0.d0
+ fspread_1GHz=0.d0
+ vr=0.d0
+ xl=0.d0
+ b=0.d0
+ endif
- return
end subroutine ephem
diff --git a/lib/fil4.f90 b/lib/fil4.f90
index 4946da2f..da98ded6 100644
--- a/lib/fil4.f90
+++ b/lib/fil4.f90
@@ -1,5 +1,19 @@
subroutine fil4(id1,n1,id2,n2)
+ parameter (NTAPS=49)
+ integer*2 id1(n1)
+ integer*2 id2(*)
+ real t(NTAPS)
+ data t/NTAPS*0.0/
+ save t
+
+ call fil4_state(id1,n1,id2,n2,t)
+
+ return
+end subroutine fil4
+
+subroutine fil4_state(id1,n1,id2,n2,t)
+
! FIR lowpass filter designed using ScopeFIR
! fsample = 48000 Hz
@@ -15,7 +29,6 @@ subroutine fil4(id1,n1,id2,n2)
integer*2 id1(n1)
integer*2 id2(*)
real t(NTAPS)
- data t/NTAPS*0.0/
! Filter coefficients:
real w(NTAPS)
@@ -33,7 +46,7 @@ subroutine fil4(id1,n1,id2,n2)
-0.013752163325,-0.011720748164,-0.005202883094, 0.002613872664, &
0.008706594219, 0.011363155076, 0.010161983649, 0.010051920210, &
0.000861074040/
- save w,t
+ save w
n2=n1/NDOWN
if(n2*NDOWN.ne.n1) stop 'Error in fil4'
@@ -46,4 +59,4 @@ subroutine fil4(id1,n1,id2,n2)
enddo
return
-end subroutine fil4
+end subroutine fil4_state
diff --git a/lib/flat4.f90 b/lib/flat4.f90
index faf15459..44f1e9c7 100644
--- a/lib/flat4.f90
+++ b/lib/flat4.f90
@@ -12,10 +12,11 @@ subroutine flat4(s,npts0,nflatten)
real*8 x(1000),y(1000),a(5)
data nseg/10/,npct/10/
+ epsilon=tiny(s(1))
npts=min(6827,npts0)
if(s(1).gt.1.e29) go to 900 !Boundary between Rx intervals: do nothing
do i=1,npts
- s(i)=10.0*log10(s(i)) !Convert to dB scale
+ s(i)=10.0*log10(max(s(i),epsilon)) !Convert to dB scale
enddo
if(nflatten.gt.0) then
diff --git a/lib/fst4/fastosd240_74.f90 b/lib/fst4/fastosd240_74.f90
index 39d20b8e..9af0f4e9 100644
--- a/lib/fst4/fastosd240_74.f90
+++ b/lib/fst4/fastosd240_74.f90
@@ -168,6 +168,7 @@ subroutine fastosd240_74(llr,k,apmask,ndeep,message74,cw,nhardmin,dmin)
if(ndeep.eq.0) goto 998 ! norder=0
if(ndeep.gt.4) ndeep=4
+ nord=0
nsyndmax=0
if( ndeep.eq. 1) then
nord=1
diff --git a/lib/fst4/fst4sim.f90 b/lib/fst4/fst4sim.f90
index 936c4b6f..3476d097 100644
--- a/lib/fst4/fst4sim.f90
+++ b/lib/fst4/fst4sim.f90
@@ -13,11 +13,14 @@ program fst4sim
complex, allocatable :: c(:)
real, allocatable :: wave(:)
integer hmod
+ integer exit_status
+ integer pack_status
integer itone(NN)
integer*1 msgbits(101)
integer*2, allocatable :: iwave(:) !Generated full-length waveform
! Get command-line argument(s)
+ exit_status=0
nargs=iargc()
if(nargs.ne.9) then
print*,'Need 9 arguments, got ',nargs
@@ -76,15 +79,27 @@ program fst4sim
if(snrdb.gt.90.0) sig=1.0
if(wspr_hint) then
- i3=0
- n3=6
+ iwspr=1
else
- i3=-1
- n3=-1
+ iwspr=0
endif
- call pack77(msg37,i3,n3,c77)
- if(i3.eq.0.and.n3.eq.6) iwspr=1
call genfst4(msg37,0,msgsent37,msgbits,itone,iwspr)
+ if(trim(msgsent37).eq.'*** bad message ***') then
+ print*,'Cannot encode message: ',trim(msg37)
+ exit_status=1
+ go to 999
+ endif
+ if(iwspr.eq.1) then
+ call pack77(msgsent37,i3,n3,c77, &
+ pack77_options(prefer_wspr_50bit=.true.),pack_status)
+ else
+ call pack77(msgsent37,i3,n3,c77,status=pack_status)
+ endif
+ if(pack_status.ne.PACK77_STATUS_ENCODED) then
+ print*,'Cannot encode message: ',trim(msg37)
+ exit_status=1
+ go to 999
+ endif
write(*,*)
write(*,'(a9,a37,a3,L2,a7,i2)') 'Message: ',msgsent37,'W:',wspr_hint,' iwspr:',iwspr
write(*,1000) f00,xdt,txt,snrdb
@@ -149,11 +164,17 @@ program fst4sim
write(fname,1104) ifile
1104 format('000000_',i4.4,'.wav')
endif
- open(10,file=trim(fname),status='unknown',access='stream')
+ open(10,file=trim(fname),status='replace',access='stream')
write(10) h,iwave !Save to *.wav file
close(10)
write(*,1110) ifile,xdt,f00,snrdb,fname
1110 format(i4,f7.2,f8.2,f7.1,2x,a17)
enddo
-999 end program fst4sim
+999 if(allocated(c0)) deallocate(c0)
+ if(allocated(c)) deallocate(c)
+ if(allocated(wave)) deallocate(wave)
+ if(allocated(iwave)) deallocate(iwave)
+ if(exit_status.ne.0) stop 1
+
+end program fst4sim
diff --git a/lib/fst4/gen_fst4wave.f90 b/lib/fst4/gen_fst4wave.f90
index 74a9b34c..516bf722 100644
--- a/lib/fst4/gen_fst4wave.f90
+++ b/lib/fst4/gen_fst4wave.f90
@@ -7,7 +7,7 @@ subroutine gen_fst4wave(itone,nsym,nsps,nwave,fsample,hmod,f0, &
complex cwave(nwave),ctab(0:NTAB-1)
character(len=1) :: cvalue
real, allocatable, save :: pulse(:)
- real, allocatable :: dphi(:)
+ real, allocatable :: dphi(:), scaled_pulse(:)
integer hmod
integer itone(nsym)
logical first, lshape
@@ -40,34 +40,36 @@ subroutine gen_fst4wave(itone,nsym,nsps,nwave,fsample,hmod,f0, &
nsps0=nsps
endif
-! Compute the smoothed frequency waveform.
-! Length = (nsym+2)*nsps samples, zero-padded
- allocate( dphi(0:(nsym+2)*nsps-1) )
+! Generate one symbol at a time, retaining phase across symbol boundaries.
+ allocate(dphi(0:nsps-1))
dphi_peak=twopi*hmod/real(nsps)
- dphi=0.0
- do j=1,nsym
- ib=(j-1)*nsps
- ie=ib+3*nsps-1
- dphi(ib:ie) = dphi(ib:ie) + dphi_peak*pulse(1:3*nsps)*itone(j)
- enddo
-
-! Calculate and insert the audio waveform
+ allocate(scaled_pulse(3*nsps))
+ scaled_pulse=dphi_peak*pulse
+ carrier=twopi*(f0-1.5*hmod/tsym)*dt
+ if(icmplx.eq.0) wave(nsym*nsps+1:nwave)=0.
+ if(icmplx.eq.1) cwave(nsym*nsps+1:nwave)=0.
phi=0.0
- dphi = dphi + twopi*(f0-1.5*hmod/tsym)*dt !Shift frequency up by f0
- if(icmplx.eq.0) wave=0.
- if(icmplx.eq.1) cwave=0.
k=0
- do j=nsps,(nsym+1)*nsps-1
- k=k+1
- i=phi*float(NTAB)/twopi
- i=iand(i,NTAB-1)
- if(icmplx.eq.0) then
- wave(k)=aimag(ctab(i))
- else
- cwave(k)=ctab(i)
- endif
- phi=phi+dphi(j)
- if(phi.gt.twopi) phi=phi-twopi
+ do iblock=1,nsym
+ dphi=0.0
+! Accumulate overlapping pulses in tone order to preserve phase rounding.
+ do j=max(1,iblock-1),min(nsym,iblock+1)
+ ip=(iblock-j+1)*nsps+1
+ dphi=dphi+scaled_pulse(ip:ip+nsps-1)*itone(j)
+ enddo
+ dphi=dphi+carrier
+ do j=0,nsps-1
+ k=k+1
+ i=phi*float(NTAB)/twopi
+ i=iand(i,NTAB-1)
+ if(icmplx.eq.0) then
+ wave(k)=aimag(ctab(i))
+ else
+ cwave(k)=ctab(i)
+ endif
+ phi=phi+dphi(j)
+ if(phi.gt.twopi) phi=phi-twopi
+ enddo
enddo
! Compute the ramp-up and ramp-down symbols
diff --git a/lib/fst4/genfst4.f90 b/lib/fst4/genfst4.f90
index 42950554..643a08cf 100644
--- a/lib/fst4/genfst4.f90
+++ b/lib/fst4/genfst4.f90
@@ -23,7 +23,7 @@ subroutine genfst4(msg0,ichk,msgsent,msgbits,i4tone,iwspr)
integer*1 msgbits(101),rvec(77)
integer isyncword1(8),isyncword2(8)
integer ncrc24
- logical unpk77_success
+ logical requested_wspr,encoded_wspr,unpk77_success
data isyncword1/0,1,3,2,1,0,2,3/
data isyncword2/2,3,1,0,3,2,0,1/
data rvec/0,1,0,0,1,0,1,0,0,1,0,1,1,1,1,0,1,0,0,0,1,0,0,1,1,0,1,1,0, &
@@ -42,24 +42,35 @@ subroutine genfst4(msg0,ichk,msgsent,msgbits,i4tone,iwspr)
message=message(i+1:)
enddo
+ requested_wspr=iwspr.eq.1
i3=-1
n3=-1
- if(iwspr.eq.1) then
- i3=0
- n3=6
+ c77=' '
+ if(requested_wspr) then
+ call pack77(message,i3,n3,c77, &
+ pack77_options(prefer_wspr_50bit=.true.))
+ else
+ call pack77_legacy_truncating_fallback(message,i3,n3,c77)
+ endif
+ encoded_wspr=i3.eq.0.and.n3.eq.6
+ unpk77_success=.false.
+ if(i3.ge.0.and.n3.ge.0) then
+ call unpack77(c77,0,msgsent,unpk77_success) !Unpack to get msgsent
endif
- call pack77(message,i3,n3,c77)
- call unpack77(c77,0,msgsent,unpk77_success) !Unpack to get msgsent
msgbits=0
iwspr=0
- if(i3.eq.0.and.n3.eq.6) then
+ if(requested_wspr.and..not.encoded_wspr) then
+ iwspr=1
+ go to 1
+ endif
+ if(encoded_wspr) then
iwspr=1
read(c77,'(50i1)') msgbits(1:50)
call get_crc24(msgbits,74,ncrc24)
write(c24,'(b24.24)') ncrc24
read(c24,'(24i1)') msgbits(51:74)
else
- read(c77,'(77i1)') msgbits(1:77)
+ read(c77,'(77i1)',err=1) msgbits(1:77)
msgbits(1:77)=mod(msgbits(1:77)+rvec,2)
call get_crc24(msgbits,101,ncrc24)
write(c24,'(b24.24)') ncrc24
@@ -68,8 +79,9 @@ subroutine genfst4(msg0,ichk,msgsent,msgbits,i4tone,iwspr)
if(ichk.eq.1) go to 999
if(unpk77_success) go to 2
- msgbits=0
- itone=0
+1 msgbits=0
+ i4tone=0
+ if(requested_wspr) iwspr=1
msgsent='*** bad message *** '
go to 999
diff --git a/lib/fst4/get_fst4_bitmetrics.f90 b/lib/fst4/get_fst4_bitmetrics.f90
index 0ae747c5..762daa25 100644
--- a/lib/fst4/get_fst4_bitmetrics.f90
+++ b/lib/fst4/get_fst4_bitmetrics.f90
@@ -15,7 +15,7 @@ subroutine get_fst4_bitmetrics(cd,nss,bitmetrics,s4,nsync_qual,badsync)
logical first
logical badsync
real bitmetrics(2*NN,4)
- real s2(0:65535)
+ real, save :: s2(0:65535)
real s4(0:3,NN)
data isyncword1/0,1,3,2,1,0,2,3/
data isyncword2/2,3,1,0,3,2,0,1/
diff --git a/lib/fst4/ldpcsim240_101.f90 b/lib/fst4/ldpcsim240_101.f90
index e201ac41..b886d6ae 100644
--- a/lib/fst4/ldpcsim240_101.f90
+++ b/lib/fst4/ldpcsim240_101.f90
@@ -14,6 +14,7 @@ program ldpcsim240_101
integer*1 cw(240)
integer*1 codeword(N),message101(101)
integer ncrc24
+ integer pack_status
real rxdata(N),llr(N)
logical first,unpk77_success
data first/.true./
@@ -41,7 +42,17 @@ program ldpcsim240_101
read(arg,*) Keff
msg0='K9AN K1JT FN20 '
if(nargs.eq.6) call getarg(6,msg0)
- call pack77(msg0,i3,n3,c77)
+ call pack77_legacy_truncating_fallback(msg0,i3,n3,c77, &
+ status=pack_status)
+ if(pack_status.ne.PACK77_STATUS_ENCODED) then
+ print*,'Cannot encode message: ',trim(msg0)
+ stop 1
+ endif
+ call unpack77(c77,0,msg,unpk77_success)
+ if(.not.unpk77_success) then
+ print*,'Cannot encode message: ',trim(msg0)
+ stop 1
+ endif
rate=real(Keff)/real(N)
@@ -50,6 +61,7 @@ program ldpcsim240_101
write(*,*) "norder : ",norder
write(*,*) "s : ",s
write(*,*) "K : ",Keff
+ write(*,*) 'Message sent: ',trim(msg)
msgbits=0
read(c77,'(77i1)') msgbits(1:77)
diff --git a/lib/fst4/osd240_101.f90 b/lib/fst4/osd240_101.f90
index 9d97e8b6..199b27a8 100644
--- a/lib/fst4/osd240_101.f90
+++ b/lib/fst4/osd240_101.f90
@@ -130,7 +130,8 @@ subroutine osd240_101(llr,k,apmask,ndeep,message101,cw,nhardmin,dmin)
npre2=0
nt=0
- if(ndeep.eq.0) goto 998 ! norder=0
+ nord=0
+ if(ndeep.le.0) goto 998 ! norder=0
if(ndeep.gt.6) ndeep=6
if( ndeep.eq. 1) then
nord=1
@@ -401,4 +402,3 @@ subroutine fetchit101(reset,e2,ntau,i1,i2)
lastpat=ipat
return
end subroutine fetchit101
-
diff --git a/lib/fst4/osd240_74.f90 b/lib/fst4/osd240_74.f90
index a54e767b..74cb1a0e 100644
--- a/lib/fst4/osd240_74.f90
+++ b/lib/fst4/osd240_74.f90
@@ -130,7 +130,8 @@ subroutine osd240_74(llr,k,apmask,ndeep,message74,cw,nhardmin,dmin)
npre2=0
nt=0
- if(ndeep.eq.0) goto 998 ! norder=0
+ nord=0
+ if(ndeep.le.0) goto 998 ! norder=0
if(ndeep.gt.6) ndeep=6
if( ndeep.eq. 1) then
nord=1
@@ -401,4 +402,3 @@ subroutine fetchit74(reset,e2,ntau,i1,i2)
lastpat=ipat
return
end subroutine fetchit74
-
diff --git a/lib/fst4_decode.f90 b/lib/fst4_decode.f90
index 0e7d8d67..83cf11f9 100644
--- a/lib/fst4_decode.f90
+++ b/lib/fst4_decode.f90
@@ -80,7 +80,8 @@ contains
data rvec/0,1,0,0,1,0,1,0,0,1,0,1,1,1,1,0,1,0,0,0,1,0,0,1,1,0,1,1,0, &
1,0,0,1,0,1,1,0,0,0,0,1,0,0,0,1,0,1,0,0,1,1,1,1,0,0,1,0,1, &
0,1,0,1,0,1,1,0,1,1,1,1,1,0,0,0,1,0,1/
- data first/.true./,hmod/1/
+ data first/.true./,hmod/1/,fcbest/0.0/
+
save first,apbits,nappasses,naptypes,mycall0,hiscall0
save wcalls,nwcalls
@@ -327,7 +328,8 @@ contains
call timer('dwnsmpl ',1)
call timer('sync240 ',0)
- call fst4_sync_search(c2,nfft2,hmod,fs2,nss,ntrperiod,nsyncoh,emedelay,sbest,fcbest,isbest)
+ call fst4_sync_search(c2,nfft2,hmod,fs2,nss,ntrperiod,nsyncoh, &
+ emedelay,sbest,fcbest,isbest)
call timer('sync240 ',1)
fc_synced = fc0 + fcbest
@@ -876,9 +878,11 @@ contains
return
end subroutine get_candidates_fst4
- subroutine fst4_sync_search(c2,nfft2,hmod,fs2,nss,ntrperiod,nsyncoh,emedelay,sbest,fcbest,isbest)
+ subroutine fst4_sync_search(c2,nfft2,hmod,fs2,nss,ntrperiod,nsyncoh, &
+ emedelay,sbest,fcbest,isbest)
complex c2(0:nfft2-1)
integer hmod
+
nspsec=int(fs2)
baud=fs2/real(nss)
fc1=0.0
diff --git a/lib/ft2/ft2.f90 b/lib/ft2/ft2.f90
deleted file mode 100644
index e5c389f9..00000000
--- a/lib/ft2/ft2.f90
+++ /dev/null
@@ -1,279 +0,0 @@
-program ft2
-
- use packjt77
- include 'gcom1.f90'
- integer ft2audio,ptt
- logical allok
- character*20 pttport
- character*8 arg
- character*80 fname
- integer*2 id2(30000)
-
- open(12,file='all_ft2.txt',status='unknown',position='append')
- nargs=iargc()
- if(nargs.eq.1) then
- call getarg(1,fname)
- open(10,file=fname,status='old',access='stream')
- read(10) id2(1:22) !Read (and ignore) the header
- read(10) id2 !Read the Rx data
- close(10)
- call ft2_decode(fname(1:17),nfqso,id2,ndecodes,mycall,hiscall,nrx)
- go to 999
- endif
-
- allok=.true.
-! Get home-station details
- open(10,file='ft2.ini',status='old',err=1)
- go to 2
-1 print*,'Cannot open ft2.ini'
- allok=.false.
-2 read(10,*,err=3) mycall,mygrid,ndevin,ndevout,pttport,exch
- go to 4
-3 print*,'Error reading ft2.ini'
- allok=.false.
-4 if(index(pttport,'/').lt.1) read(pttport,*) nport
- hiscall=' '
- hiscall_next=' '
- idevin=ndevin
- idevout=ndevout
- call padevsub(idevin,idevout)
- if(idevin.ne.ndevin .or. idevout.ne.ndevout) allok=.false.
- i1=0
- i1=ptt(nport,1,1,iptt)
- i1=ptt(nport,1,0,iptt)
- if(i1.lt.0 .and. nport.ne.0) allok=.false.
- if(.not.allok) then
- write(*,"('Please fix setup error(s) and restart.')")
- go to 999
- endif
-
- nright=1
- iwrite=0
- iwave=0
- nwave=NTZ
- nfsample=12000
- ngo=1
- npabuf=1152
- ntxok=0
- ntransmitting=0
- tx_once=.false.
- snrdb=99.0
- txmsg='CQ K1JT FN20'
- ltx=.false.
- lrx=.false.
- autoseq=.false.
- QSO_in_progress=.false.
- ntxed=0
-
- if(nargs.eq.3) then
- call getarg(1,txmsg)
- call getarg(2,arg)
- read(arg,*) f0
- call getarg(3,arg)
- read(arg,*) snrdb
- tx_once=.true.
- ftx=1500.0
- call transmit(-1,ftx,iptt)
- snrdb=99.0
- endif
-
-! Start the audio streams
- ierr=ft2audio(idevin,idevout,npabuf,nright,y1,y2,NRING,iwrite,itx, &
- iwave,nwave+3*1152,nfsample,nTxOK,nTransmitting,ngo)
- if(ierr.ne.0) then
- print*,'Error',ierr,' starting audio input and/or output.'
- endif
-
-999 end program ft2
-
-subroutine update(total_time,ic1,ic2)
-
- use wavhdr
- type(hdr) h
- real*8 total_time
- integer*8 count0,count1,clkfreq
- integer ptt
- integer*2 id(30000)
- logical transmitted,level,ok
- character*70 line
- character cdatetime*17,fname*17,mode*8,band*6
- include 'gcom1.f90'
- data nt0/-1/,transmitted/.false./,snr/-99.0/
- data level/.false./
- save nt0,transmitted,level,snr,iptt
-
- if(ic1.ne.0 .or. ic2.ne.0) then
- if(ic1.eq.27 .and. ic2.eq.0) ngo=0 !ESC
- if(nTxOK.eq.0 .and. ntransmitting.eq.0) then
- nfunc=0
- if(ic1.eq.0 .and. ic2.eq.59) nfunc=1 !F1
- if(ic1.eq.0 .and. ic2.eq.60) nfunc=2 !F2
- if(ic1.eq.0 .and. ic2.eq.61) nfunc=3 !F3
- if(ic1.eq.0 .and. ic2.eq.62) nfunc=4 !F4
- if(ic1.eq.0 .and. ic2.eq.63) nfunc=5 !F5
- if(nfunc.eq.1 .or. (nfunc.ge.2 .and. hiscall.ne.' ')) then
- ftx=1500.0
- call transmit(nfunc,ftx,iptt)
- endif
- endif
- if(ic1.eq.13 .and. ic2.eq.0) hiscall=hiscall_next
- if((ic1.eq.97 .or. ic1.eq.65) .and. ic2.eq.0) autoseq=.not.autoseq
- if((ic1.eq.108 .or. ic1.eq.76) .and. ic2.eq.0) level=.not.level
- endif
-
- if(ntransmitting.eq.1) transmitted=.true.
- if(transmitted .and. ntransmitting.eq.0) then
- i1=0
- if(iptt.eq.1 .and. nport.gt.0) i1=ptt(nport,0,1,iptt)
- if(tx_once .and. transmitted) stop
- transmitted=.false.
- endif
-
- nt=2*total_time
- if(nt.gt.nt0 .or. ic1.ne.0 .or. ic2.ne.0) then
- if(level) then
-! Measure and display the average level of signal plus noise in past 0.5 s
- k=iwrite-6000
- if(k.lt.1) k=k+NRING
- sq=0.
- do i=1,6000
- k=k+1
- if(k.gt.NRING) k=k-NRING
- x=y1(k)
- sq=sq + x*x
- enddo
- sigdb=0.
- if(sq.gt.0.0) sigdb=db(sq/6000.0)
- n=sigdb
- if(n.lt.1) n=1
- if(n.gt.70) n=70
- line=' '
- line(n:n)='*'
- write(*,1030) sigdb,ntxed,autoseq,QSO_in_progress,(line(i:i),i=1,n)
-1030 format(f4.1,i3,2L2,1x,70a1)
-! write(*,1020) nt,total_time,iwrite,itx,ntxok,ntransmitting,ndecodes, &
-! snr,sigdb,line
-!1020 format(i6,f9.3,i10,i6,3i3,f6.0,f6.1,1x,a30)
- endif
- k=iwrite-30000
- if(k.lt.1) k=k+NRING
- do i=1,30000
- k=k+1
- if(k.gt.NRING) k=k-NRING
- id(i)=y1(k)
- enddo
- nutc=0
- nfqso=1500
- ndecodes=0
- if(maxval(abs(id)).gt.0) then
- call system_clock(count0,clkfreq)
- nrx=-1
- call ft2_decode(cdatetime(),nfqso,id,ndecodes,mycall,hiscall,nrx)
- call system_clock(count1,clkfreq)
-! tdecode=float(count1-count0)/float(clkfreq)
-
- if(ndecodes.ge.1) then
- fMHz=7.074
- mode='FT2'
- nsubmode=1
- ntrperiod=0
- h=default_header(12000,30000)
- k=0
- do i=1,250
- sq=0
- do n=1,120
- k=k+1
- x=id(k)
- sq=sq + x*x
- enddo
- write(43,3043) i,0.01*i,1.e-4*sq
-3043 format(i7,f12.6,f12.3)
- enddo
- call set_wsjtx_wav_params(fMHz,mode,nsubmode,ntrperiod,id)
- band=""
- mode=""
- nsubmode=-1
- ntrperiod=-1
- call get_wsjtx_wav_params(id,band,mode,nsubmode,ntrperiod,ok)
-! write(*,1010) band,ntrperiod,mode,char(ichar('A')-1+id(3))
-!1010 format('Band: ',a6,' T/R period:',i4,' Mode: ',a8,1x,a1)
-
- fname=cdatetime()
- fname(14:17)='.wav'
- open(13,file=fname,status='unknown',access='stream')
- write(13) h,id
- close(13)
- endif
- if(autoseq .and.nrx.eq.2) QSO_in_progress=.true.
- if(autoseq .and. QSO_in_progress .and. nrx.ge.1 .and. nrx.le.4) then
- lrx(nrx)=.true.
- ftx=1500.0
- if(ntxed.eq.1) then
- if(nrx.eq.2) then
- call transmit(3,ftx,iptt)
- else
- call transmit(1,ftx,iptt)
- endif
- endif
- if(ntxed.eq.2) then
- if(nrx.eq.3) then
- call transmit(4,ftx,iptt)
- QSO_in_progress=.false.
- write(*,1032)
-1032 format('QSO complete: S+P side')
- else
- call transmit(2,ftx,iptt)
- endif
- endif
- if(ntxed.eq.3) then
- if(nrx.eq.4) then
- QSO_in_progress=.false.
- write(*,1034)
-1034 format('QSO complete: CQ side')
- else
- call transmit(3,ftx,iptt)
- endif
- endif
- endif
- endif
- nt0=nt
- endif
-
- return
-end subroutine update
-
-character*17 function cdatetime()
- character cdate*8,ctime*10
- call date_and_time(cdate,ctime)
- cdatetime=cdate(3:8)//'_'//ctime
- return
-end function cdatetime
-
-subroutine transmit(nfunc,ftx,iptt)
- include 'gcom1.f90'
- character*17 cdatetime
- integer ptt
-
- if(nTxOK.eq.1) return
-
- if(nfunc.eq.1) txmsg='CQ '//trim(mycall)//' '//mygrid
- if(nfunc.eq.2) txmsg=trim(hiscall)//' '//trim(mycall)// &
- ' 559 '//trim(exch)
- if(nfunc.eq.3) txmsg=trim(hiscall)//' '//trim(mycall)// &
- ' R 559 '//trim(exch)
- if(nfunc.eq.4) txmsg=trim(hiscall)//' '//trim(mycall)//' RR73'
- if(nfunc.eq.5) txmsg='TNX 73 GL'
- call ft2_iwave(txmsg,ftx,snrdb,iwave)
- iwave(23041:)=0
- i1=ptt(nport,1,1,iptt)
- ntxok=1
- n=len(trim(txmsg))
- write(*,1010) cdatetime(),0,0.0,nint(ftx),(txmsg(i:i),i=1,n)
- write(12,1010) cdatetime(),0,0.0,nint(ftx),(txmsg(i:i),i=1,n)
-1010 format(a17,i4,f6.2,i5,' Tx ',37a1)
- if(nfunc.ge.1 .and. nfunc.le.4) ntxed=nfunc
- if(nfunc.ge.1 .and. nfunc.le.5) ltx(nfunc)=.true.
- if(nfunc.eq.2 .or. nfunc.eq.3) QSO_in_progress=.true.
-
- return
-end subroutine transmit
diff --git a/lib/ft2/ft2.ini b/lib/ft2/ft2.ini
deleted file mode 100644
index d66770d1..00000000
--- a/lib/ft2/ft2.ini
+++ /dev/null
@@ -1,2 +0,0 @@
-K1JT FN20 1 5 0 NJ
-MyCall MyGrid AudioIn AudioOut PTTport Exch
diff --git a/lib/ft2/ft2_decode.f90 b/lib/ft2/ft2_decode.f90
deleted file mode 100644
index 1d1bb6a5..00000000
--- a/lib/ft2/ft2_decode.f90
+++ /dev/null
@@ -1,298 +0,0 @@
-subroutine ft2_decode(cdatetime0,nfqso,iwave,ndecodes,mycall,hiscall,nrx,line)
-
- use crc
- use packjt77
- include 'ft2_params.f90'
- character message*37,c77*77
- character*61 line
- character*37 decodes(100)
- character*120 data_dir
- character*17 cdatetime0,cdatetime
- character*6 mycall,hiscall,hhmmss
- complex c2(0:NMAX/16-1) !Complex waveform
- complex cb(0:NMAX/16-1)
- complex cd(0:144*10-1) !Complex waveform
- complex c1(0:9),c0(0:9)
- complex ccor(0:1,144)
- complex csum,cterm,cc0,cc1,csync1
- real*8 fMHz
-
- real a(5)
- real rxdata(128),llr(128) !Soft symbols
- real llr2(128)
- real sbits(144),sbits1(144),sbits3(144)
- real ps(0:8191),psbest(0:8191)
- real candidate(3,100)
- real savg(NH1)
- integer*2 iwave(NMAX) !Generated full-length waveform
- integer*1 message77(77),apmask(128),cw(128)
- integer*1 hbits(144),hbits1(144),hbits3(144)
- integer*1 s16(16)
- logical unpk77_success
- data s16/0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0/
-
- hhmmss=cdatetime0(8:13)
- fs=12000.0/NDOWN !Sample rate
- dt=1/fs !Sample interval after downsample (s)
- tt=NSPS*dt !Duration of "itone" symbols (s)
- baud=1.0/tt !Keying rate for "itone" symbols (baud)
- txt=NZ*dt !Transmission length (s)
- twopi=8.0*atan(1.0)
- h=0.8 !h=0.8 seems to be optimum for AWGN sensitivity (not for fading)
-
- dphi=twopi/2*baud*h*dt*16 ! dt*16 is samp interval after downsample
- dphi0=-1*dphi
- dphi1=+1*dphi
- phi0=0.0
- phi1=0.0
- do i=0,9
- c1(i)=cmplx(cos(phi1),sin(phi1))
- c0(i)=cmplx(cos(phi0),sin(phi0))
- phi1=mod(phi1+dphi1,twopi)
- phi0=mod(phi0+dphi0,twopi)
- enddo
- the=twopi*h/2.0
- cc1=cmplx(cos(the),-sin(the))
- cc0=cmplx(cos(the),sin(the))
-
- data_dir="."
- fMHz=7.074
- ncoh=1
- candidate=0.0
- ncand=0
- fa=375.0
- fb=3000.0
- syncmin=0.2
- maxcand=100
- nfqso=-1
- call getcandidates2a(iwave,fa,fb,maxcand,savg,candidate,ncand)
- ndecodes=0
- do icand=1,ncand
- f0=candidate(1,icand)
- if( f0.le.375.0 .or. f0.ge.(5000.0-375.0) ) cycle
- call ft2_downsample(iwave,f0,c2) ! downsample from 160s/Symbol to 10s/Symbol
-! 750 samples/second here
- ibest=-1
- sybest=-99.
- dfbest=-1.
-!### do if=-15,+15
- do if=-30,30
- df=if
- a=0.
- a(1)=-df
- call twkfreq1(c2,NMAX/16,fs,a,cb)
- do is=0,374 !DT search range is 0 - 0.5 s
- csync1=0.
- cterm=1
- do ib=1,16
- i1=(ib-1)*10+is
- i2=i1+136*10
- if(s16(ib).eq.1) then
- csync1=csync1+sum(cb(i1:i1+9)*conjg(c1(0:9)))*cterm
- cterm=cterm*cc1
- else
- csync1=csync1+sum(cb(i1:i1+9)*conjg(c0(0:9)))*cterm
- cterm=cterm*cc0
- endif
- enddo
- if(abs(csync1).gt.sybest) then
- ibest=is
- sybest=abs(csync1)
- dfbest=df
- endif
- enddo
- enddo
-
- a=0.
- a(1)=-dfbest
- call twkfreq1(c2,NMAX/16,fs,a,cb)
- ib=ibest
- cd=cb(ib:ib+144*10-1)
- s2=sum(real(cd*conjg(cd)))/(10*144)
- cd=cd/sqrt(s2)
- do nseq=1,5
- if( nseq.eq.1 ) then ! noncoherent single-symbol detection
- sbits1=0.0
- do ibit=1,144
- ib=(ibit-1)*10
- ccor(1,ibit)=sum(cd(ib:ib+9)*conjg(c1(0:9)))
- ccor(0,ibit)=sum(cd(ib:ib+9)*conjg(c0(0:9)))
- sbits1(ibit)=abs(ccor(1,ibit))-abs(ccor(0,ibit))
- hbits1(ibit)=0
- if(sbits1(ibit).gt.0) hbits1(ibit)=1
- enddo
- sbits=sbits1
- hbits=hbits1
- sbits3=sbits1
- hbits3=hbits1
- elseif( nseq.ge.2 ) then
- nbit=2*nseq-1
- numseq=2**(nbit)
- ps=0
- do ibit=nbit/2+1,144-nbit/2
- ps=0.0
- pmax=0.0
- do iseq=0,numseq-1
- csum=0.0
- cterm=1.0
- k=1
- do i=nbit-1,0,-1
- ibb=iand(iseq/(2**i),1)
- csum=csum+ccor(ibb,ibit-(nbit/2+1)+k)*cterm
- if(ibb.eq.0) cterm=cterm*cc0
- if(ibb.eq.1) cterm=cterm*cc1
- k=k+1
- enddo
- ps(iseq)=abs(csum)
- if( ps(iseq) .gt. pmax ) then
- pmax=ps(iseq)
- ibflag=1
- endif
- enddo
- if( ibflag .eq. 1 ) then
- psbest=ps
- ibflag=0
- endif
- call getbitmetric(2**(nbit/2),psbest,numseq,sbits3(ibit))
- hbits3(ibit)=0
- if(sbits3(ibit).gt.0) hbits3(ibit)=1
- enddo
- sbits=sbits3
- hbits=hbits3
- endif
- nsync_qual=count(hbits(1:16).eq.s16)
- if(nsync_qual.lt.10) exit
- rxdata=sbits(17:144)
- rxav=sum(rxdata(1:128))/128.0
- rx2av=sum(rxdata(1:128)*rxdata(1:128))/128.0
- rxsig=sqrt(rx2av-rxav*rxav)
- rxdata=rxdata/rxsig
- sigma=0.80
- llr(1:128)=2*rxdata/(sigma*sigma)
- apmask=0
- max_iterations=40
- do ibias=0,0
- llr2=llr
- if(ibias.eq.1) llr2=llr+0.4
- if(ibias.eq.2) llr2=llr-0.4
- call bpdecode128_90(llr2,apmask,max_iterations,message77,cw,nharderror,niterations)
- if(nharderror.ge.0) exit
- enddo
- nhardmin=-1
- if(sum(message77).eq.0) cycle
- if( nharderror.ge.0 ) then
- write(c77,'(77i1)') message77(1:77)
- call unpack77(c77,nrx,message,unpk77_success)
- idupe=0
- do i=1,ndecodes
- if(decodes(i).eq.message) idupe=1
- enddo
- if(idupe.eq.1) exit
- ndecodes=ndecodes+1
- decodes(ndecodes)=message
- xsnr=db(sybest*sybest) - 115.0 !### Rough estimate of S/N ###
- nsnr=nint(xsnr)
- freq=f0+dfbest
- write(line,1000) hhmmss,nsnr,ibest/750.0,nint(freq),message
-1000 format(a6,i4,f5.2,i5,' + ',1x,a37)
- open(24,file='all_ft2.txt',status='unknown',position='append')
- write(24,1002) cdatetime0,nsnr,ibest/750.0,nint(freq),message, &
- nseq,nharderror,nhardmin
- if(hhmmss.eq.' ') write(*,1002) cdatetime0,nsnr, &
- ibest/750.0,nint(freq),message,nseq,nharderror,nhardmin
-1002 format(a17,i4,f6.2,i5,' Rx ',a37,3i5)
- close(24)
-
-!### Temporary: assume most recent decoded message conveys "hiscall".
- i0=index(message,' ')
- if(i0.ge.3 .and. i0.le.7) then
- hiscall=message(i0+1:i0+6)
- i1=index(hiscall,' ')
- if(i1.gt.0) hiscall=hiscall(1:i1)
- endif
- nrx=-1
- if(index(message,'CQ ').eq.1) nrx=1
- if((index(message,trim(mycall)//' ').eq.1) .and. &
- (index(message,' '//trim(hiscall)//' ').ge.4)) then
- if(index(message,' 559 ').gt.8) nrx=2
- if(index(message,' R 559 ').gt.8) nrx=3
- if(index(message,' RR73 ').gt.8) nrx=4
- endif
-!###
- exit
- endif
- enddo ! nseq
- enddo !candidate list
-
- return
-end subroutine ft2_decode
-
-subroutine getbitmetric(ib,ps,ns,xmet)
- real ps(0:ns-1)
- xm1=0
- xm0=0
- do i=0,ns-1
- if( iand(i/ib,1) .eq. 1 .and. ps(i) .gt. xm1 ) xm1=ps(i)
- if( iand(i/ib,1) .eq. 0 .and. ps(i) .gt. xm0 ) xm0=ps(i)
- enddo
- xmet=xm1-xm0
- return
-end subroutine getbitmetric
-
-subroutine downsample2(ci,f0,co)
- parameter(NI=144*160,NH=NI/2,NO=NI/16) ! downsample from 200 samples per symbol to 10
- complex ci(0:NI-1),ct(0:NI-1)
- complex co(0:NO-1)
- fs=12000.0
- df=fs/NI
- ct=ci
- call four2a(ct,NI,1,-1,1) !c2c FFT to freq domain
- i0=nint(f0/df)
- ct=cshift(ct,i0)
- co=0.0
- co(0)=ct(0)
- b=8.0
- do i=1,NO/2
- arg=(i*df/b)**2
- filt=exp(-arg)
- co(i)=ct(i)*filt
- co(NO-i)=ct(NI-i)*filt
- enddo
- co=co/NO
- call four2a(co,NO,1,1,1) !c2c FFT back to time domain
- return
-end subroutine downsample2
-
-subroutine ft2_downsample(iwave,f0,c)
-
-! Input: i*2 data in iwave() at sample rate 12000 Hz
-! Output: Complex data in c(), sampled at 1200 Hz
-
- include 'ft2_params.f90'
- parameter (NFFT2=NMAX/16)
- integer*2 iwave(NMAX)
- complex c(0:NMAX/16-1)
- complex c1(0:NFFT2-1)
- complex cx(0:NMAX/2)
- real x(NMAX)
- equivalence (x,cx)
-
- BW=4.0*75
- df=12000.0/NMAX
- x=iwave
- call four2a(x,NMAX,1,-1,0) !r2c FFT to freq domain
- ibw=nint(BW/df)
- i0=nint(f0/df)
- c1=0.
- c1(0)=cx(i0)
- do i=1,NFFT2/2
- arg=(i-1)*df/bw
- win=exp(-arg*arg)
- c1(i)=cx(i0+i)*win
- c1(NFFT2-i)=cx(i0-i)*win
- enddo
- c1=c1/NFFT2
- call four2a(c1,NFFT2,1,1,1) !c2c FFT back to time domain
- c=c1(0:NMAX/16-1)
- return
-end subroutine ft2_downsample
diff --git a/lib/ft2/ft2_gfsk_iwave.f90 b/lib/ft2/ft2_gfsk_iwave.f90
deleted file mode 100644
index 2611eca0..00000000
--- a/lib/ft2/ft2_gfsk_iwave.f90
+++ /dev/null
@@ -1,88 +0,0 @@
-subroutine ft2_gfsk_iwave(msg37,f0,snrdb,iwave)
-
-! Generate waveform for experimental "FT2" mode
-
- use packjt77
- include 'ft2_params.f90' !Set various constants
- parameter (NWAVE=(NN+2)*NSPS)
- character msg37*37,msgsent37*37
- real wave(NWAVE),xnoise(NWAVE)
- real dphi(NWAVE)
- real pulse(480)
-
- integer itone(NN)
- integer*2 iwave(NWAVE) !Generated full-length waveform
- logical first
- data first/.true./
- save pulse
-
- twopi=8.0*atan(1.0)
- fs=12000.0 !Sample rate (Hz)
- dt=1.0/fs !Sample interval (s)
- hmod=0.8 !Modulation index (MSK=0.5, FSK=1.0)
- tt=NSPS*dt !Duration of symbols (s)
- baud=1.0/tt !Keying rate (baud)
- bw=1.5*baud !Occupied bandwidth (Hz)
- txt=NZ*dt !Transmission length (s)
- bandwidth_ratio=2500.0/(fs/2.0)
-! sig=sqrt(2*bandwidth_ratio) * 10.0**(0.05*snrdb)
-! if(snrdb.gt.90.0) sig=1.0
- txt=NN*NSPS/12000.0
-
- if(first) then
-! The filtered frequency pulse
- do i=1,480
- tt=(i-240.5)/160.0
- pulse(i)=gfsk_pulse(1.0,tt)
- enddo
- dphi_peak=twopi*(hmod/2.0)/real(NSPS)
- first=.false.
- endif
-
-! Source-encode, then get itone():
- itype=1
- call genft2(msg37,0,msgsent37,itone,itype)
-
-! Create the instantaneous frequency waveform
- dphi=0.0
- do j=1,NN
- ib=(j-1)*160+1
- ie=ib+480-1
- dphi(ib:ie)=dphi(ib:ie)+dphi_peak*pulse*(2*itone(j)-1)
- enddo
-
- phi=0.0
- wave=0.0
- sqrt2=sqrt(2.)
- dphi=dphi+twopi*f0*dt
- do j=1,NWAVE
- wave(j)=sqrt2*sin(phi)
- sqsig=sqsig + wave(j)**2
- phi=mod(phi+dphi(j),twopi)
- enddo
- wave(1:160)=wave(1:160)*(1.0-cos(twopi*(/(i,i=0,159)/)/320.0) )/2.0
- wave(145*160+1:146*160)=wave(145*160+1:146*160)*(1.0+cos(twopi*(/(i,i=0,159)/)/320.0 ))/2.0
- wave(146*160+1:)=0.
-
- if(snrdb.gt.90.0) then
- iwave=nint((32767.0/sqrt(2.0))*wave)
- return
- endif
-
- sqnoise=1.e-30
- if(snrdb.lt.90) then
- do i=1,NWAVE !Add gaussian noise at specified SNR
- xnoise(i)=gran() !Noise has rms = 1.0
- enddo
- endif
- xnoise=xnoise*sqrt(0.5*fs/2500.0)
- fac=30.0
- snr_amplitude=10.0**(0.05*snrdb)
- wave=fac*(snr_amplitude*wave + xnoise)
- datpk=maxval(abs(wave))
- print*,'A',snr_amplitude,datpk
-
- iwave=nint((30000.0/datpk)*wave)
-
- return
-end subroutine ft2_gfsk_iwave
diff --git a/lib/ft2/ft2_iwave.f90 b/lib/ft2/ft2_iwave.f90
deleted file mode 100644
index 10b9908d..00000000
--- a/lib/ft2/ft2_iwave.f90
+++ /dev/null
@@ -1,64 +0,0 @@
-subroutine ft2_iwave(msg37,f0,snrdb,iwave)
-
-! Generate waveform for experimental "FT2" mode
-
- use packjt77
- include 'ft2_params.f90' !Set various constants
- parameter (NWAVE=NN*NSPS)
- character msg37*37,msgsent37*37
- real wave(NWAVE),xnoise(NWAVE)
- integer itone(NN)
- integer*2 iwave(NWAVE) !Generated full-length waveform
-
- twopi=8.0*atan(1.0)
- fs=12000.0 !Sample rate (Hz)
- dt=1.0/fs !Sample interval (s)
- hmod=0.8 !Modulation index (MSK=0.5, FSK=1.0)
- tt=NSPS*dt !Duration of symbols (s)
- baud=1.0/tt !Keying rate (baud)
- bw=1.5*baud !Occupied bandwidth (Hz)
- txt=NZ*dt !Transmission length (s)
- bandwidth_ratio=2500.0/(fs/2.0)
-! sig=sqrt(2*bandwidth_ratio) * 10.0**(0.05*snrdb)
-! if(snrdb.gt.90.0) sig=1.0
- txt=NN*NSPS/12000.0
-
-! Source-encode, then get itone():
- itype=1
- call genft2(msg37,0,msgsent37,itone,itype)
-
- k=0
- phi=0.0
- sqsig=0.
- do j=1,NN !Generate real waveform
- dphi=twopi*(f0*dt+(hmod/2.0)*(2*itone(j)-1)/real(NSPS))
- do i=1,NSPS
- k=k+1
- wave(k)=sqrt(2.0)*sin(phi) !Signal has rms = 1.0
- sqsig=sqsig + wave(k)**2
- phi=mod(phi+dphi,twopi)
- enddo
- enddo
-
- if(snrdb.gt.90.0) then
- iwave=nint((32767.0/sqrt(2.0))*wave)
- return
- endif
-
- sqnoise=1.e-30
- if(snrdb.lt.90) then
- do i=1,NWAVE !Add gaussian noise at specified SNR
- xnoise(i)=gran() !Noise has rms = 1.0
- enddo
- endif
- xnoise=xnoise*sqrt(0.5*fs/2500.0)
- fac=30.0
- snr_amplitude=10.0**(0.05*snrdb)
- wave=fac*(snr_amplitude*wave + xnoise)
- datpk=maxval(abs(wave))
- print*,'A',snr_amplitude,datpk
-
- iwave=nint((30000.0/datpk)*wave)
-
- return
-end subroutine ft2_iwave
diff --git a/lib/ft2/ft2_params.f90 b/lib/ft2/ft2_params.f90
deleted file mode 100644
index 4751e47e..00000000
--- a/lib/ft2/ft2_params.f90
+++ /dev/null
@@ -1,12 +0,0 @@
-! LDPC (128,90) code
-parameter (KK=90) !Information bits (77 + CRC13)
-parameter (ND=128) !Data symbols
-parameter (NS=16) !Sync symbols (2x8)
-parameter (NN=NS+ND) !Total channel symbols (144)
-parameter (NSPS=160) !Samples per symbol at 12000 S/s
-parameter (NZ=NSPS*NN) !Samples in full 1.92 s waveform (23040)
-parameter (NMAX=30000) !Samples in iwave (2.5*12000)
-parameter (NFFT1=400, NH1=NFFT1/2) !Length of FFTs for symbol spectra
-parameter (NSTEP=NSPS/4) !Rough time-sync step size
-parameter (NHSYM=NMAX/NSTEP-3) !Number of symbol spectra (1/4-sym steps)
-parameter (NDOWN=16) !Downsample factor
diff --git a/lib/ft2/g4.cmd b/lib/ft2/g4.cmd
deleted file mode 100644
index 0894dbeb..00000000
--- a/lib/ft2/g4.cmd
+++ /dev/null
@@ -1,7 +0,0 @@
-gcc -c ft2audio.c
-gcc -c ptt.c
-gfortran -c ../77bit/packjt77.f90
-gfortran -c ../wavhdr.f90
-gfortran -c ../crc.f90
-gfortran -o ft2 -fbounds-check -fno-second-underscore -ffpe-trap=invalid,zero -Wall -Wno-conversion -Wno-character-truncation ft2.f90 ft2_iwave.f90 ft2_decode.f90 getcandidates2.f90 ft2audio.o ptt.o /JTSDK/wsjtx-output/qt55/2.1.0/Release/build/libwsjt_fort.a /JTSDK/wsjtx-output/qt55/2.1.0/Release/build/libwsjt_cxx.a libportaudio.a ../libfftw3f_win.a -lwinmm
-rm *.o *.mod
diff --git a/lib/ft2/gcom1.f90 b/lib/ft2/gcom1.f90
deleted file mode 100644
index 9402f9d9..00000000
--- a/lib/ft2/gcom1.f90
+++ /dev/null
@@ -1,34 +0,0 @@
-! Variable Purpose
-!---------------------------------------------------------------------------
-integer NRING !Length of Rx ring buffer
-integer NTZ !Length of Tx waveform in samples
-parameter(NRING=230400) !Ring buffer at 12000 samples/sec
-parameter(NTZ=23040) !144*160
-parameter(NMAX=30000) !2.5*12000
-real snrdb
-integer ndevin !Device# for audio input
-integer ndevout !Device# for audio output
-integer iwrite !Pointer to Rx ring buffer
-integer itx !Pointer to Tx buffer
-integer ngo !Set to 0 to terminate audio streams
-integer nTransmitting !Actually transmitting?
-integer nTxOK !OK to transmit?
-integer nport !COM port for PTT
-logical tx_once !Transmit one message, then exit
-logical ltx !True if msg i has been transmitted
-logical lrx !True if msg i has been received
-logical autoseq
-logical QSO_in_progress
-integer*2 y1 !Ring buffer for audio channel 0
-integer*2 y2 !Ring buffer for audio channel 1
-integer*2 iwave !Data for Tx audio
-character*6 mycall
-character*6 hiscall
-character*6 hiscall_next
-character*4 mygrid
-character*3 exch
-character*37 txmsg
-
-common/gcom1/snrdb,ndevin,ndevout,iwrite,itx,ngo,nTransmitting,nTxOK,nport, &
- ntxed,tx_once,y1(NRING),y2(NRING),iwave(NTZ+3*1152),ltx(5),lrx(5), &
- autoseq,QSO_in_progress,mycall,hiscall,hiscall_next,mygrid,exch,txmsg
diff --git a/lib/ft2/genft2.f90 b/lib/ft2/genft2.f90
deleted file mode 100644
index 2eb36bcc..00000000
--- a/lib/ft2/genft2.f90
+++ /dev/null
@@ -1,86 +0,0 @@
-subroutine genft2(msg0,ichk,msgsent,i4tone,itype)
-! s8 + 48bits + s8 + 80 bits = 144 bits (72ms message duration)
-!
-! Encode an MSK144 message
-! Input:
-! - msg0 requested message to be transmitted
-! - ichk if ichk=1, return only msgsent
-! if ichk.ge.10000, set imsg=ichk-10000 for short msg
-! - msgsent message as it will be decoded
-! - i4tone array of audio tone values, 0 or 1
-! - itype message type
-! 1 = 77 bit message
-! 7 = 16 bit message "<Call_1 Call2> Rpt"
-
- use iso_c_binding, only: c_loc,c_size_t
- use packjt77
- character*37 msg0
- character*37 message !Message to be generated
- character*37 msgsent !Message as it will be received
- character*77 c77
- integer*4 i4tone(144)
- integer*1 codeword(128)
- integer*1 msgbits(77)
- integer*1 bitseq(144) !Tone #s, data and sync (values 0-1)
- integer*1 s16(16)
- real*8 xi(864),xq(864),pi,twopi
- data s16/0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0/
- equivalence (ihash,i1hash)
- logical unpk77_success
-
- nsym=128
- pi=4.0*atan(1.0)
- twopi=8.*atan(1.0)
-
- message(1:37)=' '
- itype=1
- if(msg0(1:1).eq.'@') then !Generate a fixed tone
- read(msg0(2:5),*,end=1,err=1) nfreq !at specified frequency
- go to 2
-1 nfreq=1000
-2 i4tone(1)=nfreq
- else
- message=msg0
-
- do i=1, 37
- if(ichar(message(i:i)).eq.0) then
- message(i:37)=' '
- exit
- endif
- enddo
- do i=1,37 !Strip leading blanks
- if(message(1:1).ne.' ') exit
- message=message(i+1:)
- enddo
-
- if(message(1:1).eq.'<') then
- i2=index(message,'>')
- i1=0
- if(i2.gt.0) i1=index(message(1:i2),' ')
- if(i1.gt.0) then
- call genmsk40(message,msgsent,ichk,i4tone,itype)
- if(itype.lt.0) go to 999
- i4tone(41)=-40
- go to 999
- endif
- endif
-
- i3=-1
- n3=-1
- call pack77(message,i3,n3,c77)
- call unpack77(c77,0,msgsent,unpk77_success) !Unpack to get msgsent
-
- if(ichk.eq.1) go to 999
- read(c77,"(77i1)") msgbits
- call encode_128_90(msgbits,codeword)
-
-!Create 144-bit channel vector:
- bitseq=0
- bitseq(1:16)=s16
- bitseq(17:144)=codeword
-
- i4tone=bitseq
- endif
-
-999 return
-end subroutine genft2
diff --git a/lib/ft2/getcandidates2a.f90 b/lib/ft2/getcandidates2a.f90
deleted file mode 100644
index 8e7209c9..00000000
--- a/lib/ft2/getcandidates2a.f90
+++ /dev/null
@@ -1,64 +0,0 @@
-subroutine getcandidates2a(id,fa,fb,maxcand,savg,candidate,ncand)
-
-! For now, hardwired to find the largest peak in the average spectrum
-
- include 'ft2_params.f90'
- real s(NH1,NHSYM)
- real savg(NH1),savsm(NH1)
- real x(NFFT1)
- complex cx(0:NH1)
- real candidate(3,100)
- integer*2 id(NMAX)
- integer*1 s8(8)
- integer indx(NH1)
- data s8/0,1,1,1,0,0,1,0/
- equivalence (x,cx)
-
-! Compute symbol spectra, stepping by NSTEP steps.
- savg=0.
- tstep=NSTEP/12000.0
- df=12000.0/NFFT1 !3.125 Hz
- fac=1.0/300.0
- do j=1,NHSYM
- ia=(j-1)*NSTEP + 1
- ib=ia+NSPS-1
- x(1:NSPS)=fac*id(ia:ib)
- x(NSPS+1:)=0.
- call four2a(x,NFFT1,1,-1,0) !r2c FFT
- do i=1,NH1
- s(i,j)=real(cx(i))**2 + aimag(cx(i))**2
- enddo
- savg=savg + s(1:NH1,j) !Average spectrum
- enddo
- savsm=0.
- do i=2,NH1-1
- savsm(i)=sum(savg(i-1:i+1))/3.
- enddo
- savsm(1)=savg(1)
- savsm(NH1)=savg(NH1)
-
- nfa=nint(fa/df)
- nfb=nint(fb/df)
- np=nfb-nfa+1
- indx=0
- call indexx(savsm(nfa:nfb),np,indx)
- xn=savsm(nfa+indx(nint(0.3*np)))
- if(xn.ne.0) savsm=savsm/xn
- imax=-1
- xmax=-99.
- do i=2,NH1-1
- if(savsm(i).gt.savsm(i-1).and. &
- savsm(i).gt.savsm(i+1).and. &
- savsm(i).gt.xmax) then
- xmax=savsm(i)
- imax=i
- endif
- enddo
- f0=imax*df
- if(xmax.gt.1.2) then
- if(ncand.lt.maxcand) ncand=ncand+1
- candidate(1,ncand)=f0
- endif
-
- return
-end subroutine getcandidates2a
diff --git a/lib/ft2/libportaudio.a b/lib/ft2/libportaudio.a
deleted file mode 100644
index f20f02c1..00000000
--- a/lib/ft2/libportaudio.a
+++ /dev/null
Binary files differ
diff --git a/lib/ft2/libwsjt_cxx.a b/lib/ft2/libwsjt_cxx.a
deleted file mode 100644
index d10d509c..00000000
--- a/lib/ft2/libwsjt_cxx.a
+++ /dev/null
Binary files differ
diff --git a/lib/ft2/libwsjt_fort.a b/lib/ft2/libwsjt_fort.a
deleted file mode 100644
index 7884c85b..00000000
--- a/lib/ft2/libwsjt_fort.a
+++ /dev/null
Binary files differ
diff --git a/lib/ft2/ptt.c b/lib/ft2/ptt.c
deleted file mode 100644
index fdda4ff9..00000000
--- a/lib/ft2/ptt.c
+++ /dev/null
@@ -1,58 +0,0 @@
-#include <windows.h>
-#include <stdio.h>
-
-int ptt_(int *nport, int *ntx, int *ndtr, int *iptt)
-{
- static HANDLE hFile;
- static int open=0, nhold=0;
- char s[10];
- int i3,i4,i5,i6,i9,i00;
-
- if(*nport==0) {
- *iptt=*ntx;
- return(0);
- }
-
- nhold=0;
- if(*nport>100) nhold=1;
-
- if(*ntx && (!open)) {
- sprintf(s,"\\\\.\\COM%d",*nport%100);
- hFile=CreateFile(
- TEXT(s),
- GENERIC_WRITE,
- 0,
- NULL,
- OPEN_EXISTING,
- FILE_ATTRIBUTE_NORMAL,
- NULL
- );
- if(hFile==INVALID_HANDLE_VALUE) {
- printf("PTT: Cannot open COM port %d.\n",*nport%100);
- return(-1);
- }
- open=1;
- }
-
- if(*ntx && open) {
- if(*ndtr)
- EscapeCommFunction(hFile,5); //set DTR
- else
- EscapeCommFunction(hFile,3); //set RTS
- *iptt=1;
- }
-
- else {
- if(*ndtr)
- EscapeCommFunction(hFile,6); //clear DTR
- else
- EscapeCommFunction(hFile,4); //clear RTS
- EscapeCommFunction(hFile,9); //clear BREAK
- if(nhold==0) {
- i00=CloseHandle(hFile);
- open=0;
- }
- *iptt=0;
- }
- return(0);
-}
diff --git a/lib/ft2/ptt_unix.c b/lib/ft2/ptt_unix.c
deleted file mode 100644
index b1638060..00000000
--- a/lib/ft2/ptt_unix.c
+++ /dev/null
@@ -1,341 +0,0 @@
-#include <stdio.h>
-#include <fcntl.h>
-#include <unistd.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <stddef.h>
-//#include <sys/ioctl.h>
-//#include <linux/ppdev.h>
-//#include <linux/parport.h>
-//#include <dev/ppbus/ppi.h>
-//#include <dev/ppbus/ppbconf.h>
-
-int lp_reset (int fd);
-int lp_ptt (int fd, int onoff);
-
-#ifdef HAVE_SYS_STAT_H
-# include <sys/stat.h>
-#endif
-#if (defined(__unix__) || defined(unix)) && !defined(USG)
-# include <sys/param.h>
-#endif
-
-#include <string.h>
-/* parport functions */
-
-int dev_is_parport(int fd);
-int ptt_parallel(int fd, int *ntx, int *iptt);
-int ptt_serial(int fd, int *ntx, int *iptt);
-
-int fd=-1; /* Used for both serial and parallel */
-
-/*
- * ptt_
- *
- * generic unix PTT routine called from Fortran
- *
- * Inputs
- * unused Unused, to satisfy old windows calling convention
- * ptt_port device name serial or parallel
- * ntx pointer to fortran command on or off
- * iptt pointer to fortran command status on or off
- * Returns - non 0 if error
-*/
-
-/* Tiny state machine */
-#define STATE_PORT_CLOSED 0
-#define STATE_PORT_OPEN_PARALLEL 1
-#define STATE_PORT_OPEN_SERIAL 2
-
-int
-ptt_(int *unused, char *ptt_port, int *ntx, int *ndtr, int *iptt)
-{
- static int state=0;
- char *p;
-
- /* In the very unlikely event of a NULL pointer, just return.
- * Yes, I realise this should not be possible in WSJT.
- */
- if (ptt_port == NULL) {
- *iptt = *ntx;
- return (0);
- }
-
- switch (state) {
- case STATE_PORT_CLOSED:
-
- /* Remove trailing ' ' */
- if ((p = strchr(ptt_port, ' ')) != NULL)
- *p = '\0';
-
- /* If all that is left is a '\0' then also just return */
- if (*ptt_port == '\0') {
- *iptt = *ntx;
- return(0);
- }
-
- if ((fd = open(ptt_port, O_RDWR|O_NONBLOCK)) < 0) {
- fprintf(stderr, "Can't open %s.\n", ptt_port);
- return (1);
- }
-
- if (dev_is_parport(fd)) {
- state = STATE_PORT_OPEN_PARALLEL;
- lp_reset(fd);
- ptt_parallel(fd, ntx, iptt);
- } else {
- state = STATE_PORT_OPEN_SERIAL;
- ptt_serial(fd, ntx, iptt);
- }
- break;
-
- case STATE_PORT_OPEN_PARALLEL:
- ptt_parallel(fd, ntx, iptt);
- break;
-
- case STATE_PORT_OPEN_SERIAL:
- ptt_serial(fd, ntx, iptt);
- break;
-
- default:
- close(fd);
- fd = -1;
- state = STATE_PORT_CLOSED;
- break;
- }
- return(0);
-}
-
-/*
- * ptt_serial
- *
- * generic serial unix PTT routine called indirectly from Fortran
- *
- * fd - already opened file descriptor
- * ntx - pointer to fortran command on or off
- * iptt - pointer to fortran command status on or off
- */
-
-int
-ptt_serial(int fd, int *ntx, int *iptt)
-{
- int control = TIOCM_RTS | TIOCM_DTR;
-
- if(*ntx) {
- ioctl(fd, TIOCMBIS, &control); /* Set DTR and RTS */
- *iptt = 1;
- } else {
- ioctl(fd, TIOCMBIC, &control);
- *iptt = 0;
- }
- return(0);
-}
-
-
-/* parport functions */
-
-/*
- * dev_is_parport(fd):
- *
- * inputs - Already open fd
- * output - 1 if parallel port, 0 if not
- * side effects - Unfortunately, this is platform specific.
- */
-
-#if defined(HAVE_LINUX_PPDEV_H) /* Linux (ppdev) */
-
-int
-dev_is_parport(int fd)
-{
- struct stat st;
- int m;
-
- if ((fstat(fd, &st) == -1) ||
- ((st.st_mode & S_IFMT) != S_IFCHR) ||
- (ioctl(fd, PPGETMODE, &m) == -1))
- return(0);
-
- return(1);
-}
-
-#elif defined(HAVE_DEV_PPBUS_PPI_H) /* FreeBSD (ppbus/ppi) */
-
-int
-dev_is_parport(int fd)
-{
- struct stat st;
- unsigned char c;
-
- if ((fstat(fd, &st) == -1) ||
- ((st.st_mode & S_IFMT) != S_IFCHR) ||
- (ioctl(fd, PPISSTATUS, &c) == -1))
- return(0);
-
- return(1);
-}
-
-#else /* Fallback (nothing) */
-
-int
-dev_is_parport(int fd)
-{
- return(0);
-}
-
-#endif
-/* Linux wrapper around PPFCONTROL */
-#ifdef HAVE_LINUX_PPDEV_H
-static void
-parport_control (int fd, unsigned char controlbits, int values)
-{
- struct ppdev_frob_struct frob;
- frob.mask = controlbits;
- frob.val = values;
-
- if (ioctl (fd, PPFCONTROL, &frob) == -1)
- {
- fprintf(stderr, "Parallel port PPFCONTROL");
- exit (1);
- }
-}
-#endif
-
-/* FreeBSD wrapper around PPISCTRL */
-#ifdef HAVE_DEV_PPBUS_PPI_H
-static void
-parport_control (int fd, unsigned char controlbits, int values)
-{
- unsigned char val;
-
- if (ioctl (fd, PPIGCTRL, &val) == -1)
- {
- fprintf(stderr, "Parallel port PPIGCTRL");
- exit (1);
- }
-
- val &= ~controlbits;
- val |= values;
-
- if (ioctl (fd, PPISCTRL, &val) == -1)
- {
- fprintf(stderr, "Parallel port PPISCTRL");
- exit (1);
- }
-}
-#endif
-
-/* Initialise a parallel port, given open fd */
-int
-lp_init (int fd)
-{
-#ifdef HAVE_LINUX_PPDEV_H
- int mode;
-#endif
-
-#ifdef HAVE_LINUX_PPDEV_H
- mode = PARPORT_MODE_PCSPP;
-
- if (ioctl (fd, PPSETMODE, &mode) == -1)
- {
- fprintf(stderr, "Setting parallel port mode");
- close (fd);
- return(-1);
- }
-
- if (ioctl (fd, PPEXCL, NULL) == -1)
- {
- fprintf(stderr, "Parallel port is already in use.\n");
- close (fd);
- return(-1);
- }
- if (ioctl (fd, PPCLAIM, NULL) == -1)
- {
- fprintf(stderr, "Claiming parallel port.\n");
- fprintf(stderr, "HINT: did you unload the lp kernel module?");
- close (fd);
- return(-1);
- }
-
- /* Enable CW & PTT - /STROBE bit (pin 1) */
- parport_control (fd, PARPORT_CONTROL_STROBE, PARPORT_CONTROL_STROBE);
-#endif
-#ifdef HAVE_DEV_PPBUS_PPI_H
- parport_control (fd, STROBE, STROBE);
-#endif
- lp_reset (fd);
- return(0);
-}
-
-/* release ppdev and close port */
-int
-lp_free (int fd)
-{
-#ifdef HAVE_LINUX_PPDEV_H
- lp_reset (fd);
-
- /* Disable CW & PTT - /STROBE bit (pin 1) */
- parport_control (fd, PARPORT_CONTROL_STROBE, 0);
-
- ioctl (fd, PPRELEASE);
-#endif
-#ifdef HAVE_DEV_PPBUS_PPI_H
- /* Disable CW & PTT - /STROBE bit (pin 1) */
- parport_control (fd, STROBE, 0);
-#endif
- close (fd);
- return(0);
-}
-
-/* set to a known state */
-int
-lp_reset (int fd)
-{
-#if defined (HAVE_LINUX_PPDEV_H) || defined (HAVE_DEV_PPBUS_PPI_H)
- lp_ptt (fd, 0);
-#endif
- return(0);
-}
-
-/* SSB PTT keying - /INIT bit (pin 16) (inverted) */
-int
-lp_ptt (int fd, int onoff)
-{
-#ifdef HAVE_LINUX_PPDEV_H
- if (onoff == 1)
- parport_control (fd, PARPORT_CONTROL_INIT,
- PARPORT_CONTROL_INIT);
- else
- parport_control (fd, PARPORT_CONTROL_INIT, 0);
-#endif
-#ifdef HAVE_DEV_PPBUS_PPI_H
- if (onoff == 1)
- parport_control (fd, nINIT,
- nINIT);
- else
- parport_control (fd, nINIT, 0);
-#endif
- return(0);
-}
-
-/*
- * ptt_parallel
- *
- * generic parallel unix PTT routine called indirectly from Fortran
- *
- * fd - already opened file descriptor
- * ntx - pointer to fortran command on or off
- * iptt - pointer to fortran command status on or off
- */
-
-int
-ptt_parallel(int fd, int *ntx, int *iptt)
-{
- if(*ntx) {
- lp_ptt(fd, 1);
- *iptt=1;
- } else {
- lp_ptt(fd, 0);
- *iptt=0;
- }
- return(0);
-}
diff --git a/lib/ft4/ft4code.f90 b/lib/ft4/ft4code.f90
index 1792d9a2..7ebc10a2 100644
--- a/lib/ft4/ft4code.f90
+++ b/lib/ft4/ft4code.f90
@@ -12,6 +12,7 @@ program ft4code
character*77 c77
character*9 comment
character bad*1,msgtype*18
+ integer pack_status
integer itone(NN)
integer*1 msgbits(77),rvec(77),codeword(174)
data rvec/0,1,0,0,1,0,1,0,0,1,0,1,1,1,1,0,1,0,0,0,1,0,0,1,1,0,1,1,0, &
@@ -46,10 +47,16 @@ program ft4code
if(nmsg.gt.1) msg=testmsg(imsg)
! Generate msgsent, msgbits, and itone
- i3=-1
- n3=-1
- call pack77(msg,i3,n3,c77)
call genft4(msg,0,msgsent,msgbits,itone)
+ if(trim(msgsent).eq.'*** bad message ***') then
+ print*,'Cannot encode message: ',trim(msg)
+ stop 1
+ endif
+ call pack77(msgsent,i3,n3,c77,status=pack_status)
+ if(pack_status.ne.PACK77_STATUS_ENCODED) then
+ print*,'Cannot encode message: ',trim(msg)
+ stop 1
+ endif
call encode174_91(msgbits,codeword)
msgtype=""
if(i3.eq.0) then
diff --git a/lib/ft4/ft4sim.f90 b/lib/ft4/ft4sim.f90
index cef22303..bc9337e2 100644
--- a/lib/ft4/ft4sim.f90
+++ b/lib/ft4/ft4sim.f90
@@ -13,6 +13,7 @@ program ft4sim
complex c(0:NMAX-1)
real wave(NMAX)
integer itone(NN)
+ integer pack_status
integer*1 msgbits(77)
integer*2 iwave(NMAX) !Generated full-length waveform
integer icos4(4)
@@ -54,11 +55,16 @@ program ft4sim
if(snrdb.gt.90.0) sig=1.0
! Source-encode, then get itone()
- i3=-1
- n3=-1
- call pack77(msg37,i3,n3,c77)
- read(c77,'(77i1)') msgbits
call genft4(msg37,0,msgsent37,msgbits,itone)
+ if(trim(msgsent37).eq.'*** bad message ***') then
+ print*,'Cannot encode message: ',trim(msg37)
+ stop 1
+ endif
+ call pack77(msgsent37,i3,n3,c77,status=pack_status)
+ if(pack_status.ne.PACK77_STATUS_ENCODED) then
+ print*,'Cannot encode message: ',trim(msg37)
+ stop 1
+ endif
write(*,*)
write(*,'(a9,a37,3x,a7,i1,a1,i1)') 'Message: ',msgsent37,'i3.n3: ',i3,'.',n3
write(*,1000) f0,xdt,txt,snrdb
@@ -115,7 +121,7 @@ program ft4sim
h=default_header(12000,NMAX)
write(fname,1102) ifile
1102 format('000000_',i6.6,'.wav')
- open(10,file=fname,status='unknown',access='stream')
+ open(10,file=fname,status='replace',access='stream')
write(10) h,iwave !Save to *.wav file
close(10)
write(*,1110) ifile,xdt,f0,snrdb,fname
diff --git a/lib/ft4/ft4sim_mult.f90 b/lib/ft4/ft4sim_mult.f90
index d93978e5..437946ad 100644
--- a/lib/ft4/ft4sim_mult.f90
+++ b/lib/ft4/ft4sim_mult.f90
@@ -91,7 +91,7 @@ program ft4sim_mult
if(any(abs(wave).gt.32767.0)) print*,"Warning - data will be clipped."
iwave=nint(wave)
h=default_header(12000,NZZ)
- open(12,file=fname,status='unknown',access='stream')
+ open(12,file=fname,status='replace',access='stream')
write(12) h,iwave !Save to *.wav file
close(12)
print*,' '
diff --git a/lib/ft4/gen_ft4wave.f90 b/lib/ft4/gen_ft4wave.f90
index 13018242..885c690b 100644
--- a/lib/ft4/gen_ft4wave.f90
+++ b/lib/ft4/gen_ft4wave.f90
@@ -3,12 +3,14 @@ subroutine gen_ft4wave(itone,nsym,nsps,fsample,f0,cwave,wave,icmplx,nwave)
real wave(nwave)
complex cwave(nwave)
real pulse(6912) !576*4*3
- real dphi(0:250000-1)
+ real, allocatable :: dphi(:)
integer itone(nsym)
logical first
data first/.true./
save pulse,first,twopi,dt,hmod
+ allocate(dphi(0:(nsym+2)*nsps-1))
+
if(first) then
twopi=8.0*atan(1.0)
dt=1.0/fsample
diff --git a/lib/ft4/genft4.f90 b/lib/ft4/genft4.f90
index 66e70a61..2fdd478a 100644
--- a/lib/ft4/genft4.f90
+++ b/lib/ft4/genft4.f90
@@ -48,14 +48,17 @@ subroutine genft4(msg0,ichk,msgsent,msgbits,i4tone)
i3=-1
n3=-1
- call pack77(message,i3,n3,c77)
+ c77=' '
+ unpk77_success=.false.
+ call pack77_legacy_truncating_fallback(message,i3,n3,c77)
+ if(i3.lt.0 .or. n3.lt.0) go to 1
call unpack77(c77,0,msgsent,unpk77_success) !Unpack to get msgsent
if(ichk.eq.1) go to 999
read(c77,'(77i1)',err=1) msgbits
if(unpk77_success) go to 2
1 msgbits=0
- itone=0
+ i4tone=0
msgsent='*** bad message *** '
go to 999
diff --git a/lib/ft4_decode.f90 b/lib/ft4_decode.f90
index 7d68e17a..540c3911 100644
--- a/lib/ft4_decode.f90
+++ b/lib/ft4_decode.f90
@@ -35,10 +35,8 @@ contains
character message*37,msgsent*37
character c77*77
character*37 decodes(100)
- character*17 cdatetime0
character*12 mycall,hiscall
character*12 mycall0,hiscall0
- character*6 hhmmss
complex cd2(0:NDMAX-1) !Complex waveform
complex cb(0:NDMAX-1)
@@ -82,11 +80,10 @@ contains
data rvec/0,1,0,0,1,0,1,0,0,1,0,1,1,1,1,0,1,0,0,0,1,0,0,1,1,0,1,1,0, &
1,0,0,1,0,1,1,0,0,0,0,1,0,0,0,1,0,1,0,0,1,1,1,1,0,0,1,0,1, &
0,1,0,1,0,1,1,0,1,1,1,1,1,0,0,0,1,0,1/
- save fs,dt,tt,txt,twopi,h,first,apbits,nappasses,naptypes, &
+ save dd,fs,dt,tt,txt,twopi,h,first,apbits,nappasses,naptypes, &
mycall0,hiscall0,ctwk2
this%callback => callback
- hhmmss=cdatetime0(8:13)
dxcall13=hiscall ! initialize for use in packjt77
mycall13=mycall
@@ -418,12 +415,12 @@ contains
maxosd=3
endif
if(.not.doosd) maxosd = -1
- call timer('dec174_91 ',0)
+ call timer('dec174_9',0)
Keff=91
call decode174_91(llr,Keff,maxosd,ndeep,apmask,message91,cw, &
ntype,nharderror,dmin)
message77=message91(1:77)
- call timer('dec174_91 ',1)
+ call timer('dec174_9',1)
if(sum(message77).eq.0) cycle
if( nharderror.ge.0 ) then
diff --git a/lib/ft8/compress.f90 b/lib/ft8/compress.f90
index 683fc4d8..ece1d3ef 100644
--- a/lib/ft8/compress.f90
+++ b/lib/ft8/compress.f90
@@ -3,6 +3,7 @@ subroutine compress(c)
parameter (NMAX=15*12000) !Samples in iwave (180,000)
complex c(0:NMAX-1)
real xr(0:NMAX-1),xi(0:NMAX-1)
+ save xr,xi
xr=real(c)
call wavestats(xr,NMAX,rms,pk,pwr_pk,pwr_ave)
diff --git a/lib/ft8/foxgen.f90 b/lib/ft8/foxgen.f90
index 89383e71..0d50761a 100644
--- a/lib/ft8/foxgen.f90
+++ b/lib/ft8/foxgen.f90
@@ -38,7 +38,7 @@ subroutine foxgen(bSuperFox,fname)
n=nslots
if(bMoreCQs) cmsg(1)(40:40)='1' !Set flag to include a CQ
if(bSendMsg) then
- n=min(nslots+1,3)
+ n=min(nslots+1,5)
cmsg(n)=textMsg
cmsg(n)(39:39)='1' !Set flag for text message
nslots=n
diff --git a/lib/ft8/ft8_a7.f90 b/lib/ft8/ft8_a7.f90
index 7c7f0288..09a3837f 100644
--- a/lib/ft8/ft8_a7.f90
+++ b/lib/ft8/ft8_a7.f90
@@ -211,8 +211,11 @@ subroutine ft8_a7d(dd0,newdat,call_1,call_2,grid4,xdt,f1,xbase,nharderrors,dmin,
nt=2**(3*nsym)
do ihalf=1,2
do k=1,29,nsym
- if(ihalf.eq.1) ks=k+7
- if(ihalf.eq.2) ks=k+43
+ if(ihalf.eq.1) then
+ ks=k+7
+ else
+ ks=k+43
+ endif
amax=-1.0
do i=0,nt-1
i1=i/64
@@ -364,9 +367,9 @@ subroutine ft8_a7d(dd0,newdat,call_1,call_2,grid4,xdt,f1,xbase,nharderrors,dmin,
xsnr=-25.
arg=pbest/xbase/3.0e6-1.0
if(arg.gt.0.0) xsnr=max(-25.0,db(arg)-27.0)
-! write(41,3041) nharderrors,dmin,dmin2,dmin2/dmin,xsnr,trim(msgbest)
+! write(41,3041) nharderrors,dmin,dmin2,dmin2/(dmin+1e-6),xsnr,trim(msgbest)
!3041 format(i3,2f7.1,f7.2,f7.1,1x,a)
- if(dmin.gt.100.0 .or. dmin2/dmin.lt.1.3) nharderrors=-1
+ if(dmin.gt.100.0 .or. dmin2/(dmin+1e-6).lt.1.3) nharderrors=-1
msg37=msgbest
if(msg37(1:3).eq.'CQ ' .and. std_2 .and. grid4.eq.' ') nharderrors=-1
if(msg37(1:6).eq.'QU1RK ') nharderrors=-1
diff --git a/lib/ft8/ft8_a8_test.f90 b/lib/ft8/ft8_a8_test.f90
index 50ebc5c2..33d5b91a 100644
--- a/lib/ft8/ft8_a8_test.f90
+++ b/lib/ft8/ft8_a8_test.f90
@@ -35,7 +35,7 @@ program ft8_a8_test
fac=1.0/32767.0
dd=fac*iwave
- call ft8_a8d(dd,mycall,dxcall,dxgrid,f1,xdt,fbest,xsnr,plog,msgbest)
+ call ft8_a8d(dd,mycall,dxcall,dxgrid,f1,xdt,fbest,xsnr,plog,msgbest,0)
apflag=' a8'
if(plog.lt.-155) apflag(1:1)='?'
diff --git a/lib/ft8/ft8_a8d.f90 b/lib/ft8/ft8_a8d.f90
index 3fb1a073..5d05fef1 100644
--- a/lib/ft8/ft8_a8d.f90
+++ b/lib/ft8/ft8_a8d.f90
@@ -1,4 +1,5 @@
-subroutine ft8_a8d(dd,mycall,dxcall,dxgrid,f1a,xdt,fbest,xsnr,plog,msgbest)
+subroutine ft8_a8d(dd,mycall,dxcall,dxgrid,f1a,xdt,fbest,xsnr,plog,msgbest, &
+ progress_generation)
! List decoding for FT8, activated only at nfqso (Rx Freq) +/- 10 Hz and when
! DxCall and DxGrid are populated. Returns xdt, fbest, and msgbest.
@@ -6,6 +7,7 @@ subroutine ft8_a8d(dd,mycall,dxcall,dxgrid,f1a,xdt,fbest,xsnr,plog,msgbest)
use packjt77
use ft8_a7
use timer_module, only: timer
+ use decode_completion_module, only: write_decode_progress
include 'ft8_params.f90' !Set various constants
parameter (NWAVE=NN*NSPS/NDOWN) !Length of generated cwave = 2528
parameter (NZZ=3200) !Length of downsampled arrays
@@ -30,6 +32,7 @@ subroutine ft8_a8d(dd,mycall,dxcall,dxgrid,f1a,xdt,fbest,xsnr,plog,msgbest)
complex csymb(0:31)
integer itone(NN)
integer itone_best(NN)
+ integer, intent(in) :: progress_generation
integer ipk(1)
logical newdat
@@ -54,6 +57,7 @@ subroutine ft8_a8d(dd,mycall,dxcall,dxgrid,f1a,xdt,fbest,xsnr,plog,msgbest)
msgbest=''
itone_best=0
do imsg=1,NMSGS
+ call write_decode_progress(progress_generation)
call getmsg(imsg,mycall,dxcall,dxgrid,msg)
! Source-encode the message, get itone(), and generate complex FT8 waveform.
diff --git a/lib/ft8/ft8b.f90 b/lib/ft8/ft8b.f90
index 43ac33bf..8934e399 100644
--- a/lib/ft8/ft8b.f90
+++ b/lib/ft8/ft8b.f90
@@ -187,8 +187,11 @@ subroutine ft8b(dd0,newdat,nQSOProgress,nfqso,nftx,ndepth,nzhsym,lapon, &
nt=2**(3*nsym)
do ihalf=1,2
do k=1,29,nsym
- if(ihalf.eq.1) ks=k+7
- if(ihalf.eq.2) ks=k+43
+ if(ihalf.eq.1) then
+ ks=k+7
+ else
+ ks=k+43
+ endif
amax=-1.0
do i=0,nt-1
i1=i/64
@@ -204,7 +207,7 @@ subroutine ft8b(dd0,newdat,nQSOProgress,nfqso,nftx,ndepth,nzhsym,lapon, &
print*,"Error - nsym must be 1, 2, or 3."
endif
enddo
- if(imetric.eq.2) s2=s2**2
+ if(imetric.eq.2) s2(0:nt-1)=s2(0:nt-1)**2
i32=1+(k-1)*3+(ihalf-1)*87
if(nsym.eq.1) ibmax=2
if(nsym.eq.2) ibmax=5
@@ -432,12 +435,12 @@ subroutine ft8b(dd0,newdat,nQSOProgress,nfqso,nftx,ndepth,nzhsym,lapon, &
(abs(nfqso-f1).le.napwid .or. abs(nftx-f1).le.napwid .or. ncontest.eq.7)) then
maxosd=2
endif
- call timer('dec174_91 ',0)
+ call timer('dec174_9',0)
Keff=91
call decode174_91(llrz,Keff,maxosd,norder,apmask,message91,cw, &
ntype,nharderrors,dmin)
if(nharderrors.ge.0) message77=message91(1:77)
- call timer('dec174_91 ',1)
+ call timer('dec174_9',1)
msg37=' '
nbadcrc=1
diff --git a/lib/ft8/ft8c.f90 b/lib/ft8/ft8c.f90
index a7d1ccb9..4e2e8d72 100644
--- a/lib/ft8/ft8c.f90
+++ b/lib/ft8/ft8c.f90
@@ -136,8 +136,11 @@ subroutine ft8c(dd0,newdat,call_1,call_2,grid4,xdt,f1,nharderrors,dmin, &
nt=2**(3*nsym)
do ihalf=1,2
do k=1,29,nsym
- if(ihalf.eq.1) ks=k+7
- if(ihalf.eq.2) ks=k+43
+ if(ihalf.eq.1) then
+ ks=k+7
+ else
+ ks=k+43
+ endif
amax=-1.0
do i=0,nt-1
i1=i/64
diff --git a/lib/ft8/ft8sim.f90 b/lib/ft8/ft8sim.f90
index 4897814b..2ee9bd5d 100644
--- a/lib/ft8/ft8sim.f90
+++ b/lib/ft8/ft8sim.f90
@@ -5,12 +5,15 @@ program ft8sim_gfsk
use wavhdr
use packjt77
+ use, intrinsic :: iso_c_binding
+
include 'ft8_params.f90' !Set various constants
parameter (NWAVE=NN*NSPS)
type(hdr) h !Header for .wav file
character arg*12,fname*17
character msg37*37,msgsent37*37
character c77*77
+ character(len=7) :: prog_name='ft8sim'//char(0)
complex c0(0:NMAX-1)
complex c(0:NMAX-1)
complex cwave(0:NWAVE-1)
@@ -20,9 +23,17 @@ program ft8sim_gfsk
integer*1 msgbits(77)
integer*2 iwave(NMAX) !Generated full-length waveform
+ interface
+ subroutine print_version(prog_name) bind(C, name='print_version')
+ use, intrinsic :: iso_c_binding
+ character(kind=c_char, len=1), intent(in) :: prog_name(*)
+ end subroutine print_version
+ end interface
+
! Get command-line argument(s)
nargs=iargc()
if(nargs.ne.7) then
+ call print_version(prog_name)
print*,'Usage: ft8sim "message" f0 DT fdop del nfiles snr'
print*,'Examples: ft8sim "K1ABC W9XYZ EN37" 1500.0 0.0 0.5 1.0 10 -18'
print*,' ft8sim "K1ABC W9XYZ EN37" 1500.0 0.0 MM 1.0 10 -18'
@@ -164,7 +175,7 @@ program ft8sim_gfsk
h=default_header(12000,NMAX)
write(fname,1102) ifile
1102 format('000000_',i6.6,'.wav')
- open(10,file=fname,status='unknown',access='stream')
+ open(10,file=fname,status='replace',access='stream')
write(10) h,iwave !Save to *.wav file
close(10)
write(*,1110) ifile,xdt,f0,snrdb,fname,snr_2500
diff --git a/lib/ft8/genft8.f90 b/lib/ft8/genft8.f90
index a03c3e58..ce866451 100644
--- a/lib/ft8/genft8.f90
+++ b/lib/ft8/genft8.f90
@@ -16,10 +16,12 @@ subroutine genft8(msg,i3,n3,msgsent,msgbits,itone)
i3=-1
n3=-1
- call pack77(msg,i3,n3,c77)
- call unpack77(c77,0,msgsent,unpk77_success)
+ c77=' '
+ unpk77_success=.false.
+ call pack77_legacy_truncating_fallback(msg,i3,n3,c77)
+ if(i3.ge.0) call unpack77(c77,0,msgsent,unpk77_success)
read(c77,'(77i1)',err=1) msgbits
- if(unpk77_success) go to 2
+ if(i3.ge.0 .and. unpk77_success) go to 2
1 msgbits=0
itone=0
msgsent='*** bad message *** '
diff --git a/lib/ft8/ldpcsim174_91.f90 b/lib/ft8/ldpcsim174_91.f90
index 4e30859a..9a286649 100644
--- a/lib/ft8/ldpcsim174_91.f90
+++ b/lib/ft8/ldpcsim174_91.f90
@@ -75,7 +75,7 @@ program ldpcsim174_91
msg="K9ABC K1ABC FN20"
i3=0
n3=1
- call pack77(msg,i3,n3,c77) !Pack into 12 6-bit bytes
+ call pack77(msg,i3,n3,c77)
call unpack77(c77,1,msgsent,unpk77_success) !Unpack to get msgsent
write(*,*) "message sent ",msgsent
diff --git a/lib/ft8/sync8.f90 b/lib/ft8/sync8.f90
index 57af21a8..b14300ab 100644
--- a/lib/ft8/sync8.f90
+++ b/lib/ft8/sync8.f90
@@ -14,6 +14,7 @@ subroutine sync8(dd,npts,nfa,nfb,syncmin,nfqso,maxcand,candidate,ncand,sbase)
real red(NH1)
real red2(NH1)
real candidate0(3,MAXPRECAND)
+ real candidate_sync(MAXPRECAND)
real candidate(3,maxcand)
real dd(npts)
integer jpeak(NH1)
@@ -151,7 +152,8 @@ subroutine sync8(dd,npts,nfa,nfb,syncmin,nfqso,maxcand,candidate,ncand,sbase)
s=fac*s
! Sort by sync
- call indexx(candidate0(3,1:ncand),ncand,indx)
+ candidate_sync(1:ncand)=candidate0(3,1:ncand)
+ call indexx(candidate_sync,ncand,indx)
! Place candidates within 10 Hz of nfqso at the top of the list
k=1
do i=1,ncand
diff --git a/lib/ft8_decode.f90 b/lib/ft8_decode.f90
index 5402cc6c..e23df118 100644
--- a/lib/ft8_decode.f90
+++ b/lib/ft8_decode.f90
@@ -37,7 +37,6 @@ contains
ltry_a8,lapcqonly,napwid,mycall12,hiscall12,hisgrid,ldiskdat)
use iso_c_binding, only: c_bool, c_int
use timer_module, only: timer
- use shmem, only: shmem_lock, shmem_unlock
use ft8_a7
include 'ft8/ft8_params.f90'
@@ -291,7 +290,7 @@ contains
! Try for an a8 decode at nfqso
f1=nfqso
call timer('ft8_a8d ',0)
- call ft8_a8d(dd,mycall12,hiscall12,hisgrid,f1,xdt,fbest,xsnr,plog,msg37)
+ call ft8_a8d(dd,mycall12,hiscall12,hisgrid,f1,xdt,fbest,xsnr,plog,msg37,0)
call timer('ft8_a8d ',1)
if(msg37(1:1).ne.' ') then
diff --git a/lib/ft8var/agccft8.f90 b/lib/ft8var/agccft8.f90
index 1b88ca84..be39347f 100644
--- a/lib/ft8var/agccft8.f90
+++ b/lib/ft8var/agccft8.f90
@@ -1,4 +1,4 @@
-subroutine agccft8(nfa,nfb,forcedt)
+subroutine agccft8(nfa,nfb)
use ft8_mod1, only : dd8,twopi,lagccbail
integer, parameter :: NFFT=1024,NSZ=426,NHSYM=178,NHSTEP=960 !3413 = NFFT*5000/12000
diff --git a/lib/ft8var/cwfilter.f90 b/lib/ft8var/cwfilter.f90
index 913c7e3e..e305047d 100644
--- a/lib/ft8var/cwfilter.f90
+++ b/lib/ft8var/cwfilter.f90
@@ -1,13 +1,14 @@
subroutine cwfilter(first)
use ft8_mod1, only : cw,windowc1,windowx,pivalue,facx,mcq,m73,mrr73,mrrr,one,twopi,facc1,dt,csync,idtone25,csynccq, &
+ idtone25_valid, &
NFILT1,NFILT2,endcorr,ctwkw,ctwkn,ctwk256
use jt65_mod9 ! callsign DB to memory
use prog_args ! path to files
parameter (NFFT=180000)
- complex csig0(151680)
- real*4 window1(-NFILT1/2:NFILT1/2),window2(-NFILT2/2:NFILT2/2)
+ complex, allocatable :: csig0(:)
+ real*4 window1(-NFILT1/2:NFILT1/2)
character*37 msgcq25(25),msgsent37
integer itone(79)
integer*1 msgbits(77)
@@ -17,7 +18,13 @@ subroutine cwfilter(first)
!note that with new, larger ALLCALL7.TXT files, dimensions of various ncall arrays may need to be increased in jt65_mod9.f90
!on 20250709 callj dim was increased from 9000 to 10000 when updated ALLCALL7.TXT file was added
if(first) then
- open(24,file='ALLCALL7.TXT',status='unknown') ! accepting Australian 7-char callsigns
+ allocate(csig0(151680))
+ ! Open the shipped read-only ALLCALL7.TXT for reading only. status='old' with
+ ! action='read' makes a missing/unreadable file degrade cleanly to an empty
+ ! callsign DB (handled by the count check below) instead of status='unknown'
+ ! attempting a create in the read-only app bundle, which aborts the decoder.
+ open(24,file=trim(share_dir)//'/ALLCALL7.TXT',status='old',action='read',iostat=ios) ! accepting Australian 7-char callsigns
+ if(ios.ne.0) go to 20
do i=1,MAXC
read(24,1004,end=20) line
1004 format(a80)
@@ -107,9 +114,12 @@ subroutine cwfilter(first)
msgcq25(23)='CQ SM2GSH KP05'
msgcq25(24)='CQ UA9OHX NO15'
msgcq25(25)='CQ JA W0YH EN12'
+ idtone25(2:25,1:58)=0
+ idtone25_valid(2:25)=.false.
do i=2,25
i3=-1; n3=-1
call genft8sdvar(msgcq25(i),i3,n3,msgsent37,msgbits,itone)
+ if(i3.lt.0) cycle
if(i.eq.2) then
call gen_ft8wave(itone,79,1920,2.0,12000.0,0.0,csig0,xjunk,1,151680)
m=1
@@ -122,6 +132,7 @@ subroutine cwfilter(first)
endif
idtone25(i,1:29)=itone(8:36)
idtone25(i,30:58)=itone(44:72)
+ idtone25_valid(i)=.true.
enddo
dt2=0.005 ! fs2=200 Hz
k=1
@@ -177,4 +188,3 @@ subroutine cwfilter(first)
return
end subroutine cwfilter
- \ No newline at end of file
diff --git a/lib/ft8var/fillhashvar.f90 b/lib/ft8var/fillhashvar.f90
index edab5e30..851ddc13 100644
--- a/lib/ft8var/fillhashvar.f90
+++ b/lib/ft8var/fillhashvar.f90
@@ -1,67 +1,30 @@
subroutine fillhashvar(numthreads,lfill)
- use packjt77 ! also setting mycall13var,dxcall13var
+ use packjt77
use ft8_mod1, only : mycall,hiscall
integer, intent(in) :: numthreads
logical, intent(in) :: lfill
character*13 cw
if(lfill) then
+ ! End of a configured/var decode pass: merge per-thread successful decode
+ ! effects into the shared callsign hash and recent-call state.
do i=1,numthreads
- do m=1,nlast_callsvar(i)
- nposition=nthrindexvar(i)+m
- cw=last_callsvar(nposition)
+ do m=1,nqueued_calls_by_thread(i)
+ nposition=thread_call_index(i)+m
+ cw=queued_calls_by_thread(nposition)
!print *,i,m,cw
- n10=ihashcallvar(cw,10)
- if(n10.ge.0 .and. n10 .le. 1023 .and. cw.ne.mycall13var) calls10var(n10)=cw
-
- n12=ihashcallvar(cw,12)
- if(n12.ge.0 .and. n12 .le. 4095 .and. cw.ne.mycall13var) calls12var(n12)=cw
-
- n22=ihashcallvar(cw,22)
- if(any(ihash22var.eq.n22)) then ! If entry exists, make sure callsign is the most recently received one
- where(ihash22var.eq.n22) calls22var=cw
- go to 900
- endif
-
-! New entry: move table down, making room for new one at the top
- ihash22var(nzhashvar:2:-1)=ihash22var(nzhashvar-1:1:-1)
-
-! Add the new entry
- calls22var(nzhashvar:2:-1)=calls22var(nzhashvar-1:1:-1)
- ihash22var(1)=n22
- calls22var(1)=cw
- if(nzhashvar.lt.MAXHASHvar) nzhashvar=nzhashvar+1
-900 continue
+ call save_hash_call(cw,n10,n12,n22)
enddo
enddo
+ call fold_queued_recent_calls(numthreads)
else
- nlast_callsvar=0
- mycall13var=mycall//' '; dxcall13var=hiscall//' '
- if(mycall13var.ne.mycall13_0var) then
- if(len(trim(mycall13var)).gt.2) then
- mycall13_setvar=.true.
- mycall13_0var=mycall13var
- call save_hash_mycallvar(mycall13var,hashmy10var,hashmy12var,hashmy22var)
-!print *,mycall13var,hashmy10var,hashmy12var,hashmy22var
- else
- mycall13_setvar=.false.
- endif
- endif
-
- if(dxcall13var.ne.dxcall13_0var) then
- if(len(trim(dxcall13var)).gt.2) then
- dxcall13_setvar=.true.
- dxcall13_0var=dxcall13var
- hashdx10var=ihashcallvar(dxcall13var,10)
-! make sure new DX Call is stored in hash tables prior to decoding
-! it is needed if manually callsign set in DX Call window was not decoded before
- call save_hash_callvar(dxcall13var,1)
-!print *,dxcall13var,hashdx10var
- else
- dxcall13_setvar=.false.
- endif
- endif
+ ! Start of a configured/var decode pass: clear staged worker effects and
+ ! snapshot the operator-configured calls used by hash-only decode guards.
+ nqueued_calls_by_thread=0
+ nqueued_recent_calls_by_thread=0
+ mycall13=mycall//' '; dxcall13=hiscall//' '
+ call sync_configured_calls_for_decode_start()
endif
return
diff --git a/lib/ft8var/four2avar.f90 b/lib/ft8var/four2avar.f90
index 3ed44f22..1653955b 100644
--- a/lib/ft8var/four2avar.f90
+++ b/lib/ft8var/four2avar.f90
@@ -32,11 +32,20 @@ subroutine four2avar(a,nfft,ndim,isign,iform)
include '/lib/fftw3.f90' !FFTW definitions
save plan,nplan,nn,ns,nf,nl
+ interface
+ subroutine wsjt_tsan_acquire_four2avar_setup() bind(C)
+ end subroutine wsjt_tsan_acquire_four2avar_setup
+ subroutine wsjt_tsan_release_four2avar_setup() bind(C)
+ end subroutine wsjt_tsan_release_four2avar_setup
+ end interface
+
if(nfft.lt.0) go to 999
nloc=loc(a)
found_plan = .false.
+ !$omp critical(four2avar_setup)
+ call wsjt_tsan_acquire_four2avar_setup()
do i=1,nplan
if(nfft.eq.nn(i) .and. isign.eq.ns(i) .and. &
iform.eq.nf(i) .and. nloc.eq.nl(i)) then
@@ -48,7 +57,6 @@ subroutine four2avar(a,nfft,ndim,isign,iform)
if(i.ge.NPMAX) stop 'Too many FFTW plans requested.'
if (.not. found_plan) then
- !$omp critical(four2avar_setup)
nplan=nplan+1
i=nplan
@@ -90,8 +98,9 @@ subroutine four2avar(a,nfft,ndim,isign,iform)
if(iform.le.0) jz=nfft/2+1
a(1:jz)=aa(1:jz)
endif
- !$omp end critical(four2avar_setup)
end if
+ call wsjt_tsan_release_four2avar_setup()
+ !$omp end critical(four2avar_setup)
call sfftw_execute(plan(i))
return
diff --git a/lib/ft8var/ft4_mod1.f90 b/lib/ft8var/ft4_mod1.f90
index 9bdf2a94..e3cb7619 100644
--- a/lib/ft8var/ft4_mod1.f90
+++ b/lib/ft8var/ft4_mod1.f90
@@ -3,5 +3,6 @@ module ft4_mod1
real*4 dd4(73728)
logical(1) llagcc,lfilter,lhidetest,lhidetelemetry
integer nFT4decd,nfafilt,nfbfilt
+ save dd4
-end module ft4_mod1 \ No newline at end of file
+end module ft4_mod1
diff --git a/lib/ft8var/ft8_decode_ranges.f90 b/lib/ft8var/ft8_decode_ranges.f90
new file mode 100644
index 00000000..40c6b171
--- /dev/null
+++ b/lib/ft8var/ft8_decode_ranges.f90
@@ -0,0 +1,38 @@
+module ft8_decode_ranges
+ implicit none
+ private
+
+ integer, parameter, public :: max_ft8_decode_ranges = 12
+ public :: partition_ft8_decode_range
+
+contains
+
+ pure subroutine partition_ft8_decode_range(nfa,nfb,requested_ranges,range_low,range_high,nranges)
+ integer, intent(in) :: nfa,nfb,requested_ranges
+ integer, intent(out) :: range_low(max_ft8_decode_ranges)
+ integer, intent(out) :: range_high(max_ft8_decode_ranges)
+ integer, intent(out) :: nranges
+ integer :: base_width,extra,i,next_low,range_width,total_width
+
+ range_low=0
+ range_high=-1
+ nranges=0
+
+ if(nfa.gt.nfb) return
+
+ total_width=nfb-nfa+1
+ nranges=min(max(1,requested_ranges),max_ft8_decode_ranges,total_width)
+ base_width=total_width/nranges
+ extra=mod(total_width,nranges)
+ next_low=nfa
+
+ do i=1,nranges
+ range_width=base_width
+ if(i.le.extra) range_width=range_width+1
+ range_low(i)=next_low
+ range_high(i)=next_low+range_width-1
+ next_low=range_high(i)+1
+ enddo
+ end subroutine partition_ft8_decode_range
+
+end module ft8_decode_ranges
diff --git a/lib/ft8var/ft8_decodevar.f90 b/lib/ft8var/ft8_decodevar.f90
index 521ab6da..d7324216 100644
--- a/lib/ft8var/ft8_decodevar.f90
+++ b/lib/ft8var/ft8_decodevar.f90
@@ -21,42 +21,51 @@ module ft8_decodevar
contains
- subroutine decodevar(this,callback,nQSOProgress,nfqso,nft8rxfsens,nftx,nutc, &
+ subroutine decodevar(this,nQSOProgress,nfqso,nft8rxfsens,nftx, &
nfa,nfb,ncandthin,ndtcenter,nsec,napwid,lmycallstd,lhiscallstd, &
stophint,nthr,numthreads,nagainfil,lft8lowth,lft8subpass,lhideft8dupes, &
- lft8apon,ncontest)
+ progress_generation,residual,spectrum)
- use timer_module, only: timer
use omp_lib
- use ft8_a7
+ use ft8_mtd_residual, only : mtd_publish_worker,mtd_transform_phase
+ use decode_completion_module, only : write_decode_progress
use ft8_mod1, only : ndecodes,allmessages,allsnrs,allfreq,odd,even,nmsg, &
- lastrxmsg,lasthcall,calldteven,calldtodd,incall,oddcopy,evencopy, &
- avexdt,mycall,hiscall,dd8,nft8cycles,ncandallthr,nincallthr,evencq, &
+ lastrxmsg,calldteven,calldtodd,incall,oddcopy,evencopy, &
+ avexdt,mycall,hiscall,nft8cycles,ncandallthr,nincallthr,evencq, &
oddcq,numcqsig,numdeccq,evenmyc,oddmyc,nummycsig,numdecmyc,lapmyc, &
evenqso,oddqso,lqsomsgdcd,hisgrid4
+ interface
+ subroutine wsjt_tsan_acquire_ft8_find_dupes() bind(C)
+ end subroutine wsjt_tsan_acquire_ft8_find_dupes
+ subroutine wsjt_tsan_release_ft8_find_dupes() bind(C)
+ end subroutine wsjt_tsan_release_ft8_find_dupes
+ subroutine wsjt_tsan_acquire_ft8_update_structures() bind(C)
+ end subroutine wsjt_tsan_acquire_ft8_update_structures
+ subroutine wsjt_tsan_release_ft8_update_structures() bind(C)
+ end subroutine wsjt_tsan_release_ft8_update_structures
+ end interface
+
include 'ft8_params.f90'
class(ft8_decodervar), intent(inout) :: this
- procedure(ft8_decodevar_callback) :: callback
- real, DIMENSION(:), ALLOCATABLE :: dd8m
- real candidate(4,460),freqsub(200)
+ real, intent(inout) :: residual(180000)
+ complex, intent(inout) :: spectrum(0:96000)
+ real candidate(4,460)
real qual !ft8md
integer, intent(in) :: nQSOProgress,nfqso,nft8rxfsens,nftx,nfa,nfb, &
- ncandthin,ndtcenter,nsec,napwid,nthr,numthreads
+ ncandthin,ndtcenter,nsec,napwid,nthr,numthreads,progress_generation
logical, intent(in) :: nagainfil
logical(1), intent(in) :: stophint,lft8lowth,lft8subpass,lhideft8dupes, &
- lmycallstd,lhiscallstd,lft8apon
+ lmycallstd,lhiscallstd
logical newdat1,lsubtract,ldupe,lFreeText,lspecial
logical(1) lft8sdec,lft8s,lft8sd,lrepliedother,lhashmsg,lqsothread, &
- lhidemsg,lhighsens,lcqcand,lsubtracted,levenint,loddint,lnohiscall, &
+ lhidemsg,lhighsens,lcqcand,levenint,loddint,lnohiscall, &
lnomycall,lnohisgrid
character msg37*37,msg37_2*37,msg26*37,call2*12 !ft8md msg26 was *26
character*37 msgsrcvd(130)
- logical la8
integer nsnr
- character*6 dxgrid
type oddtmp_struct
real freq
@@ -85,7 +94,7 @@ contains
real xdt
complex cs(0:7,79)
end type tmpcqsig_struct
- type(tmpcqsig_struct) tmpcqsig(numcqsig) ! 20 sigs
+ type(tmpcqsig_struct), allocatable :: tmpcqsig(:) ! 20 sigs
type tmpmyc_struct
real freq
@@ -107,9 +116,7 @@ contains
end type tmpqsosig_struct
type(tmpqsosig_struct) tmpqsosig(1)
- this%callback => callback
- la8=.true.
-
+ allocate(tmpcqsig(numcqsig))
oddtmp%lstate=.false.
eventmp%lstate=.false.
nmsgloc=0
@@ -121,13 +128,6 @@ contains
tmpcqsig(:)%freq=6000.0
tmpmycsig(:)%freq=6000.0
tmpqsosig(1)%freq=6000.0
- if(hiscall.eq.'') then
- lastrxmsg(1)%lstate=.false.
- else if(lastrxmsg(1)%lstate .and. lasthcall.ne.hiscall .and. &
- index(lastrxmsg(1)%lastmsg,trim(hiscall)).le.0) then
- lastrxmsg(1)%lstate=.false.
- endif
-
levenint=.false.
loddint=.false.
if(nsec.eq.0 .or. nsec.eq.30) then
@@ -139,11 +139,9 @@ contains
lrepliedother=.false.
lft8sdec=.false.
lqsothread=.false.
- lsubtracted=.false.
ncount=0
mycalllen1=len_trim(mycall)+1
nincallthr(nthr)=0
- nallocthr=0
ncqsignal=0
nmycsignal=0
@@ -212,9 +210,15 @@ contains
syncmin=1.3
do ipass=1,npass
+ if(ipass.eq.4 .or. ipass.eq.7) then
+!$omp barrier
+!$omp single
+ call mtd_transform_phase(ipass)
+!$omp end single
+ endif
+ call mtd_publish_worker(nthr)
newdat1=.true.
lsubtract=.true.
- npos=0
if(ipass.eq.1 .or. ipass.eq.4 .or. ipass.eq.7) then
if(lft8lowth) syncmin=1.225
elseif(ipass.eq.2 .or. ipass.eq.5 .or. ipass.eq.8) then
@@ -224,36 +228,12 @@ contains
endif
if(ipass.gt.5 .or. (ipass.eq.3 .and. npass.eq.3)) lsubtract=.false.
- if(ipass.eq.4) then
-!$omp barrier
-!$omp single
- if(npass.eq.9) then ! 3 decoding cycles
- nallocthr=nthr
- allocate(dd8m(180000), STAT = nAllocateStatus1)
- if(nAllocateStatus1.ne.0) STOP "Not enough memory"
- dd8m=dd8
- endif
- do i=1,179999
- dd8(i)=(dd8(i)+dd8(i+1))/2
- enddo
-!$omp end single
-!$omp barrier
- else if(ipass.eq.7) then
-!$omp barrier
- if(nthr.eq.nallocthr) then
- dd8(1)=dd8m(1)
- do i=2,180000
- dd8(i)=(dd8m(i-1)+dd8m(i))/2
- enddo
- deallocate (dd8m, STAT = nDeAllocateStatus1)
- if (nDeAllocateStatus1.ne.0) print *, 'failed to release memory'
- endif
-!$omp barrier
- endif
-
- call sync8var(nfa,nfb,syncmin,nfqso,candidate,ncand,jzb,jzt,ipass, &
- lqsothread,ncandthin,ndtcenter)
+ call write_decode_progress(progress_generation)
+ call sync8var(residual,nfa,nfb,syncmin,nfqso,candidate,ncand,jzb,jzt, &
+ ipass,lqsothread,ncandthin,ndtcenter,progress_generation)
+ call write_decode_progress(progress_generation)
do icand=1,ncand
+ if(mod(icand,8).eq.0) call write_decode_progress(progress_generation)
sync=candidate(3,icand)
f1=candidate(1,icand)
xdt=candidate(2,icand)
@@ -273,14 +253,16 @@ contains
i3=16
n3=16
- call ft8bvar(newdat1,nQSOProgress,nfqso,nftx,napwid,lsubtract,npos, &
- freqsub,tmpcqdec,tmpmyc,nagainfil,iaptype,f1,xdt,nbadcrc, &
+ call ft8bvar(residual,spectrum,newdat1,nQSOProgress,nfqso,nftx, &
+ napwid,lsubtract,tmpcqdec,tmpmyc,nagainfil,iaptype,f1,xdt, &
+ nbadcrc, &
lft8sdec,msg37,msg37_2,xsnr,stophint,nthr,lFreeText,ipass, &
lft8subpass,lspecial,lcqcand,ncqsignal,nmycsignal,npass,i3bit, &
lft8s,lmycallstd,lhiscallstd,levenint,loddint,lft8sd,i3,n3, &
nft8rxfsens,ncount,msgsrcvd,lrepliedother,lhashmsg,lqsothread, &
- lft8lowth,lhighsens,lsubtracted,tmpcqsig,tmpmycsig,tmpqsosig, &
- lnohiscall,lnomycall,lnohisgrid,qual,iaptype2)
+ lft8lowth,lhighsens,tmpcqsig,tmpmycsig,tmpqsosig, &
+ lnohiscall,lnomycall,lnohisgrid,qual,iaptype2, &
+ progress_generation)
nsnr=nint(xsnr)
xdt=xdt-0.5
if(nbadcrc.eq.0) then
@@ -292,6 +274,7 @@ contains
endif
!$omp critical(find_dupes)
+ call wsjt_tsan_acquire_ft8_find_dupes()
do k=1,nspecial
!ft8md if(k.eq.2) msg37=msg37_2 ! this splits DXpedition mode msg into 2 lines
ldupe=.false.
@@ -417,9 +400,11 @@ contains
endif
4 continue
enddo !do k
+ call wsjt_tsan_release_ft8_find_dupes()
!$omp end critical(find_dupes)
endif
enddo !icand
+ call write_decode_progress(progress_generation)
ncandthr=ncandthr+ncand
enddo !ipass
@@ -468,6 +453,7 @@ contains
if(nmsgloc.gt.0) then
!$omp critical(update_structures)
+ call wsjt_tsan_acquire_ft8_update_structures()
if(levenint) then
even(nmsg+1:nmsg+nmsgloc)%msg=eventmp(1:nmsgloc)%msg
even(nmsg+1:nmsg+nmsgloc)%freq=eventmp(1:nmsgloc)%freq
@@ -481,34 +467,11 @@ contains
odd(nmsg+1:nmsg+nmsgloc)%lstate=oddtmp(1:nmsgloc)%lstate
nmsg=nmsg+nmsgloc
endif
+ call wsjt_tsan_release_ft8_update_structures()
!$omp end critical(update_structures)
endif
-!$omp single
-! test code for a8 start
- if(lft8apon .and. ncontest.ne.6 .and. ncontest.ne.7 .and. la8 .and. &
- len(trim(hiscall)).ge.3 .and. &
- len(trim(hisgrid4)).ge.4 .and. ltry_a8) then
-! Try for an a8 decode at nfqso
- f1=nfqso
- dxgrid=hisgrid4
- call timer('ft8_a8d ',0)
- call ft8_a8d(dd8,mycall,hiscall,dxgrid,f1,xdt,fbest,xsnr,plog,msg37) !w3sz was dd
- call timer('ft8_a8d ',1)
- if(msg37(1:1).ne.' ') then
- if(associated(this%callback)) then
- sync=10.0 !### ??? !URUR was 10, tried 15
- nsnr=nint(xsnr)
- iaptype=8
- qual=1.0
- if(plog.lt.-147.0) qual=0.16
- call this%callback(nsnr,xdt,fbest,msg37,iaptype,qual)
- endif
- endif
- endif
-! test code for a8 stop
-!$omp end single nowait
-
return
+
end subroutine decodevar
end module ft8_decodevar
diff --git a/lib/ft8var/ft8_downsamplevar.f90 b/lib/ft8var/ft8_downsamplevar.f90
index 7253075e..6e7293f4 100644
--- a/lib/ft8var/ft8_downsamplevar.f90
+++ b/lib/ft8var/ft8_downsamplevar.f90
@@ -1,34 +1,26 @@
-subroutine ft8_downsamplevar(newdat1,f0,nqso,c0,c2,c3,lhighsens,lsubtracted,npos,freqsub)
+subroutine ft8_downsamplevar(residual,cxx,newdat1,f0,nqso,c0,c2,c3,lhighsens)
! Downconvert to complex data sampled at 200 Hz ==> 32 samples/symbol
- use ft8_mod1, only : dd8,windowc1,facc1
+ use ft8_mod1, only : windowc1,facc1
parameter (NFFT1=192000,NFFT2=3200) !192000/60 = 3200
logical newdat1
complex, intent(out) :: c0(-800:4000),c2(-800:4000),c3(-800:4000)
- complex cx(0:96000),cxx(0:96000),c1(0:3199) ! 0:NFFT1/2
+ real, intent(in) :: residual(180000)
+ complex, intent(inout) :: cxx(0:96000)
+ complex cx(0:96000),c1(0:3199) ! 0:NFFT1/2
real x(NFFT1)
real, intent(in) :: f0
integer, intent(in) :: nqso
- real freqsub(200)
logical(1), intent(in) :: lhighsens
- logical(1) lsubtracted,ldofft
equivalence (x,cx)
- save cxx
- ldofft=.false.
- if(lsubtracted) then
- do i=1,npos
- if(abs(f0-freqsub(i)).lt.50.) then; ldofft=.true.; lsubtracted=.false.; exit; endif
- enddo
- endif
-
- if(newdat1 .or. ldofft) then
-! Data in dd have changed, recompute the long FFT
- x(1:180000)=dd8
+ if(newdat1) then
+! Residual has changed, recompute the long FFT
+ x(1:180000)=residual
x(180001:NFFT1)=0. !Zero-pad the x array
call four2avar(cx,NFFT1,1,-1,0) !r2c FFT to freq domain
- newdat1=.false.; ldofft=.false.; npos=0
+ newdat1=.false.
cxx=cx
endif
diff --git a/lib/ft8var/ft8_mod1.f90 b/lib/ft8var/ft8_mod1.f90
index 8bfe3027..cd1f0d2c 100644
--- a/lib/ft8var/ft8_mod1.f90
+++ b/lib/ft8var/ft8_mod1.f90
@@ -1,5 +1,7 @@
module ft8_mod1
+ save
+
parameter (NPS=180000,NFR=151680,NFILT1=4000,NFILT2=3400,numcqsig=20, &
numdeccq=40,nummycsig=5,numdecmyc=25,nmaxthreads=24)
real*4 dd8(nps)
@@ -29,6 +31,8 @@ module ft8_mod1
logical one(0:511,0:8),lqsomsgdcd,first_osd
logical(1) lapmyc,lagcc,lagccbail,lhound,lenabledxcsearch, &
lwidedxcsearch,lmultinst,lskiptx1,ltxing
+ logical(1) idtone25_valid(25),idtone56_valid(56),idtone76_valid(76)
+ logical(1) csyncsd_valid,csyncsdcq_valid
data maskincallthr/0,30,45,55,65,75,85,90,95,100,105,110,115,120,125, &
130,135,140,145,150,155,160,165,170,175/
data mcq/0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0/
@@ -99,6 +103,11 @@ module ft8_mod1
data nintcount/0/
data avexdt/0.0/
data first_osd/.true./
+ data idtone25_valid/25*.false./
+ data idtone56_valid/56*.false./
+ data idtone76_valid/76*.false./
+ data csyncsd_valid/.false./
+ data csyncsdcq_valid/.false./
type odd_struct
real freq
diff --git a/lib/ft8var/ft8_mtd_residual.f90 b/lib/ft8var/ft8_mtd_residual.f90
new file mode 100644
index 00000000..2d4dea8d
--- /dev/null
+++ b/lib/ft8var/ft8_mtd_residual.f90
@@ -0,0 +1,459 @@
+module ft8_mtd_residual
+
+ use iso_fortran_env, only : int64
+
+ implicit none
+
+ integer, parameter, public :: mtd_residual_samples=180000
+ integer, parameter, public :: mtd_spectrum_bins=96001
+ integer, parameter, public :: mtd_max_subtractions_per_worker=460
+ integer, parameter, public :: mtd_subtraction_passes=5
+ integer, parameter, public :: mtd_commit_current=1
+ integer, parameter, public :: mtd_commit_independent=2
+ integer, parameter, public :: mtd_commit_conflict=3
+ integer, parameter, public :: mtd_commit_duplicate=4
+ integer, parameter, public :: mtd_commit_fallback=5
+ integer, parameter :: mtd_frame_samples=151680
+ real, parameter :: mtd_interaction_bandwidth=50.0
+
+ type, public :: ft8_subtraction_descriptor
+ integer :: tones(79)=0
+ real :: frequency=0.0
+ real :: dt=0.0
+ integer :: frequency_bin=0
+ integer :: start_sample=0
+ integer :: clipped_start=0
+ integer :: clipped_end=-1
+ integer(int64) :: epoch=0_int64
+ integer :: pass=0
+ integer(int64) :: commit_generation=0_int64
+ end type ft8_subtraction_descriptor
+
+ real, allocatable, save, public :: mtd_worker_residual(:,:)
+ complex, allocatable, save, public :: mtd_worker_spectrum(:,:)
+
+ real, allocatable, save :: canonical_residual(:)
+ real, allocatable, save :: post_pass3_residual(:)
+ real, allocatable, save :: subtraction_delta(:,:)
+ type(ft8_subtraction_descriptor), allocatable, save :: history(:)
+ integer(int64), allocatable, save :: worker_generation(:)
+ integer(int64), allocatable, save :: worker_epoch(:)
+ integer(int64), allocatable, save :: worker_spectrum_generation(:)
+ integer(int64), allocatable, save :: worker_spectrum_epoch(:)
+ integer, save :: active_workers=0
+ integer(int64), save :: canonical_generation=0_int64
+ integer(int64), save :: current_epoch=0_int64
+ integer, save :: history_count=0
+
+ interface
+ subroutine subtractft8var(residual,itone,f0,dt,delta)
+ real, intent(inout) :: residual(180000)
+ integer, intent(in) :: itone(79)
+ real, intent(in) :: f0,dt
+ real, intent(out), optional :: delta(151680)
+ end subroutine subtractft8var
+ subroutine wsjt_tsan_acquire_ft8_mtd() bind(C)
+ end subroutine wsjt_tsan_acquire_ft8_mtd
+ subroutine wsjt_tsan_release_ft8_mtd() bind(C)
+ end subroutine wsjt_tsan_release_ft8_mtd
+ end interface
+
+contains
+
+ subroutine mtd_prepare(input_residual,nworkers)
+ real, intent(in) :: input_residual(:)
+ integer, intent(in) :: nworkers
+
+ if(size(input_residual).ne.mtd_residual_samples) error stop &
+ 'MTD residual has an unexpected sample count'
+ if(nworkers.lt.1) error stop 'MTD requires at least one worker'
+
+ call ensure_capacity(nworkers)
+!$omp critical(ft8_mtd_canonical)
+ call wsjt_tsan_acquire_ft8_mtd()
+ active_workers=nworkers
+ current_epoch=current_epoch+1_int64
+ canonical_generation=0_int64
+ history_count=0
+ canonical_residual=input_residual
+ post_pass3_residual=input_residual
+ worker_generation(1:active_workers)=-1_int64
+ worker_epoch(1:active_workers)=current_epoch
+ worker_spectrum_generation(1:active_workers)=-1_int64
+ worker_spectrum_epoch(1:active_workers)=current_epoch
+ call wsjt_tsan_release_ft8_mtd()
+!$omp end critical(ft8_mtd_canonical)
+ end subroutine mtd_prepare
+
+ subroutine ensure_capacity(nworkers)
+ integer, intent(in) :: nworkers
+ integer :: current_workers,history_capacity
+
+ current_workers=0
+ if(allocated(mtd_worker_residual)) current_workers=size(mtd_worker_residual,2)
+ if(current_workers.ge.nworkers) return
+
+ if(allocated(mtd_worker_residual)) deallocate(mtd_worker_residual)
+ if(allocated(mtd_worker_spectrum)) deallocate(mtd_worker_spectrum)
+ if(allocated(subtraction_delta)) deallocate(subtraction_delta)
+ if(allocated(history)) deallocate(history)
+ if(allocated(worker_generation)) deallocate(worker_generation)
+ if(allocated(worker_epoch)) deallocate(worker_epoch)
+ if(allocated(worker_spectrum_generation)) deallocate(worker_spectrum_generation)
+ if(allocated(worker_spectrum_epoch)) deallocate(worker_spectrum_epoch)
+ if(.not.allocated(canonical_residual)) allocate(canonical_residual(mtd_residual_samples))
+ if(.not.allocated(post_pass3_residual)) allocate(post_pass3_residual(mtd_residual_samples))
+
+ history_capacity=mtd_subtraction_passes*mtd_max_subtractions_per_worker*nworkers
+ allocate(mtd_worker_residual(mtd_residual_samples,nworkers))
+ allocate(mtd_worker_spectrum(0:mtd_spectrum_bins-1,nworkers))
+ allocate(subtraction_delta(mtd_frame_samples,nworkers))
+ allocate(history(history_capacity))
+ allocate(worker_generation(nworkers))
+ allocate(worker_epoch(nworkers))
+ allocate(worker_spectrum_generation(nworkers))
+ allocate(worker_spectrum_epoch(nworkers))
+ end subroutine ensure_capacity
+
+ subroutine mtd_publish_worker(worker)
+ integer, intent(in) :: worker
+
+ call assert_worker(worker)
+!$omp critical(ft8_mtd_canonical)
+ call wsjt_tsan_acquire_ft8_mtd()
+ mtd_worker_residual(:,worker)=canonical_residual
+ worker_generation(worker)=canonical_generation
+ worker_epoch(worker)=current_epoch
+ worker_spectrum_generation(worker)=-1_int64
+ worker_spectrum_epoch(worker)=current_epoch
+ call wsjt_tsan_release_ft8_mtd()
+!$omp end critical(ft8_mtd_canonical)
+ end subroutine mtd_publish_worker
+
+ subroutine mtd_refresh_candidate(worker,frequency,newdat1,rebuild_spectrum)
+ integer, intent(in) :: worker
+ real, intent(in) :: frequency
+ logical, intent(inout) :: newdat1
+ logical, intent(out) :: rebuild_spectrum
+ integer :: i
+ logical :: refresh_residual
+
+ call assert_worker(worker)
+!$omp critical(ft8_mtd_canonical)
+ call wsjt_tsan_acquire_ft8_mtd()
+ refresh_residual=worker_epoch(worker).ne.current_epoch
+ if(.not.refresh_residual) then
+ do i=1,history_count
+ if(history(i)%epoch.ne.current_epoch .or. &
+ history(i)%commit_generation.le.worker_generation(worker)) cycle
+ if(abs(history(i)%frequency-frequency).lt.mtd_interaction_bandwidth) then
+ refresh_residual=.true.
+ exit
+ endif
+ enddo
+ endif
+ if(refresh_residual) then
+ mtd_worker_residual(:,worker)=canonical_residual
+ worker_generation(worker)=canonical_generation
+ worker_epoch(worker)=current_epoch
+ newdat1=.true.
+ endif
+ if(worker_spectrum_epoch(worker).ne.worker_epoch(worker)) newdat1=.true.
+ if(.not.newdat1) then
+ do i=1,history_count
+ if(history(i)%epoch.ne.worker_epoch(worker) .or. &
+ history(i)%commit_generation.le.worker_spectrum_generation(worker) .or. &
+ history(i)%commit_generation.gt.worker_generation(worker)) cycle
+ if(abs(history(i)%frequency-frequency).lt.mtd_interaction_bandwidth) then
+ newdat1=.true.
+ exit
+ endif
+ enddo
+ endif
+ rebuild_spectrum=newdat1
+ call wsjt_tsan_release_ft8_mtd()
+!$omp end critical(ft8_mtd_canonical)
+ end subroutine mtd_refresh_candidate
+
+ subroutine mtd_mark_spectrum_current(worker)
+ integer, intent(in) :: worker
+
+ call assert_worker(worker)
+ worker_spectrum_generation(worker)=worker_generation(worker)
+ worker_spectrum_epoch(worker)=worker_epoch(worker)
+ end subroutine mtd_mark_spectrum_current
+
+ subroutine mtd_commit_subtraction(worker,ipass,itone,f0,dt,residual,final_outcome)
+ integer, intent(in) :: worker,ipass,itone(79)
+ real, intent(in) :: f0,dt
+ real, intent(inout) :: residual(mtd_residual_samples)
+ integer, intent(out), optional :: final_outcome
+ type(ft8_subtraction_descriptor) :: descriptor
+ integer(int64) :: base_generation,base_epoch
+ integer :: outcome
+
+ call assert_worker(worker)
+ call mtd_make_descriptor(descriptor,ipass,itone,f0,dt)
+ base_generation=worker_generation(worker)
+ base_epoch=worker_epoch(worker)
+ descriptor%epoch=base_epoch
+ call fit_subtraction(worker,residual,descriptor)
+ call mtd_try_commit_delta(worker,residual,descriptor,base_epoch, &
+ base_generation,subtraction_delta(:,worker),outcome)
+ if(outcome.ne.mtd_commit_conflict) then
+ if(present(final_outcome)) final_outcome=outcome
+ return
+ endif
+
+ base_generation=worker_generation(worker)
+ base_epoch=worker_epoch(worker)
+ descriptor%epoch=base_epoch
+ call fit_subtraction(worker,residual,descriptor)
+ call mtd_try_commit_delta(worker,residual,descriptor,base_epoch, &
+ base_generation,subtraction_delta(:,worker),outcome)
+ if(outcome.ne.mtd_commit_conflict) then
+ if(present(final_outcome)) final_outcome=outcome
+ return
+ endif
+
+!$omp critical(ft8_mtd_canonical)
+ call wsjt_tsan_acquire_ft8_mtd()
+ descriptor%epoch=current_epoch
+ if(history_contains_duplicate(descriptor)) then
+ outcome=mtd_commit_duplicate
+ else
+ ! No caller holds an FFT lock while entering this transaction region.
+ call subtractft8var(canonical_residual,descriptor%tones, &
+ descriptor%frequency,descriptor%dt)
+ call record_commit(descriptor)
+ outcome=mtd_commit_fallback
+ endif
+ residual=canonical_residual
+ worker_generation(worker)=canonical_generation
+ worker_epoch(worker)=current_epoch
+ call wsjt_tsan_release_ft8_mtd()
+!$omp end critical(ft8_mtd_canonical)
+ if(present(final_outcome)) final_outcome=outcome
+ end subroutine mtd_commit_subtraction
+
+ subroutine mtd_capture_generation(worker,epoch,generation)
+ integer, intent(in) :: worker
+ integer(int64), intent(out) :: epoch,generation
+
+ call assert_worker(worker)
+ epoch=worker_epoch(worker)
+ generation=worker_generation(worker)
+ end subroutine mtd_capture_generation
+
+ subroutine mtd_try_commit_delta(worker,residual,descriptor,base_epoch, &
+ base_generation,delta,outcome)
+ integer, intent(in) :: worker
+ real, intent(inout) :: residual(mtd_residual_samples)
+ type(ft8_subtraction_descriptor), intent(in) :: descriptor
+ integer(int64), intent(in) :: base_epoch,base_generation
+ real, intent(in) :: delta(mtd_frame_samples)
+ integer, intent(out) :: outcome
+ logical :: stale
+
+ call assert_worker(worker)
+!$omp critical(ft8_mtd_canonical)
+ call wsjt_tsan_acquire_ft8_mtd()
+ if(history_contains_duplicate(descriptor)) then
+ outcome=mtd_commit_duplicate
+ else if(history_has_conflict(base_epoch,base_generation,descriptor)) then
+ outcome=mtd_commit_conflict
+ else
+ stale=base_epoch.ne.current_epoch .or. base_generation.ne.canonical_generation
+ call apply_fitted_subtraction(delta,descriptor)
+ if(stale) then
+ outcome=mtd_commit_independent
+ else
+ outcome=mtd_commit_current
+ endif
+ endif
+ if(outcome.eq.mtd_commit_conflict .or. outcome.eq.mtd_commit_duplicate .or. &
+ outcome.eq.mtd_commit_independent) residual=canonical_residual
+ worker_generation(worker)=canonical_generation
+ worker_epoch(worker)=current_epoch
+ call wsjt_tsan_release_ft8_mtd()
+!$omp end critical(ft8_mtd_canonical)
+ end subroutine mtd_try_commit_delta
+
+ subroutine fit_subtraction(worker,residual,descriptor)
+ integer, intent(in) :: worker
+ real, intent(inout) :: residual(mtd_residual_samples)
+ type(ft8_subtraction_descriptor), intent(in) :: descriptor
+
+ call subtractft8var(residual,descriptor%tones, &
+ descriptor%frequency,descriptor%dt,subtraction_delta(:,worker))
+ end subroutine fit_subtraction
+
+ subroutine apply_fitted_subtraction(delta,descriptor)
+ real, intent(in) :: delta(mtd_frame_samples)
+ type(ft8_subtraction_descriptor), intent(in) :: descriptor
+
+ integer :: i,j
+
+ do i=1,mtd_frame_samples
+ j=descriptor%start_sample+i-1
+ if(j.ge.1 .and. j.le.mtd_residual_samples) &
+ canonical_residual(j)=canonical_residual(j)+delta(i)
+ enddo
+ call record_commit(descriptor)
+ end subroutine apply_fitted_subtraction
+
+ subroutine record_commit(descriptor)
+ type(ft8_subtraction_descriptor), intent(in) :: descriptor
+
+ history_count=history_count+1
+ if(history_count.gt.size(history)) error stop 'MTD transaction history capacity exceeded'
+ canonical_generation=canonical_generation+1_int64
+ history(history_count)=descriptor
+ history(history_count)%commit_generation=canonical_generation
+ end subroutine record_commit
+
+ logical function history_contains_duplicate(descriptor)
+ type(ft8_subtraction_descriptor), intent(in) :: descriptor
+ integer :: i
+
+ history_contains_duplicate=.false.
+ do i=1,history_count
+ if(history(i)%epoch.ne.descriptor%epoch .or. &
+ history(i)%pass.ne.descriptor%pass) cycle
+ if(mtd_same_signal(history(i),descriptor)) then
+ history_contains_duplicate=.true.
+ return
+ endif
+ enddo
+ end function history_contains_duplicate
+
+ logical function history_has_conflict(base_epoch,base_generation,descriptor)
+ integer(int64), intent(in) :: base_epoch,base_generation
+ type(ft8_subtraction_descriptor), intent(in) :: descriptor
+ integer :: i
+
+ history_has_conflict=base_epoch.ne.current_epoch .or. &
+ descriptor%epoch.ne.current_epoch
+ if(history_has_conflict) return
+ do i=1,history_count
+ if(history(i)%epoch.ne.descriptor%epoch .or. &
+ history(i)%commit_generation.le.base_generation) cycle
+ if(mtd_descriptors_conflict(history(i),descriptor)) then
+ history_has_conflict=.true.
+ return
+ endif
+ enddo
+ end function history_has_conflict
+
+ subroutine mtd_make_descriptor(descriptor,ipass,itone,f0,dt)
+ type(ft8_subtraction_descriptor), intent(out) :: descriptor
+ integer, intent(in) :: ipass,itone(79)
+ real, intent(in) :: f0,dt
+
+ descriptor%tones=itone
+ descriptor%frequency=f0
+ descriptor%dt=dt
+ descriptor%frequency_bin=nint(f0/0.0625)
+ descriptor%start_sample=mtd_start_sample(dt)
+ call mtd_clipped_interval(dt,descriptor%clipped_start,descriptor%clipped_end)
+ descriptor%epoch=current_epoch
+ descriptor%pass=ipass
+ descriptor%commit_generation=0_int64
+ end subroutine mtd_make_descriptor
+
+ integer function mtd_start_sample(dt)
+ real, intent(in) :: dt
+
+ mtd_start_sample=int(dt*12000.0+1.0)
+ end function mtd_start_sample
+
+ subroutine mtd_clipped_interval(dt,first_sample,last_sample)
+ real, intent(in) :: dt
+ integer, intent(out) :: first_sample,last_sample
+ integer :: start_sample
+
+ start_sample=mtd_start_sample(dt)
+ first_sample=max(1,start_sample)
+ last_sample=min(mtd_residual_samples,start_sample+mtd_frame_samples-1)
+ end subroutine mtd_clipped_interval
+
+ logical function mtd_same_signal(left,right)
+ type(ft8_subtraction_descriptor), intent(in) :: left,right
+
+ mtd_same_signal=left%frequency_bin.eq.right%frequency_bin .and. &
+ left%start_sample.eq.right%start_sample .and. all(left%tones.eq.right%tones)
+ end function mtd_same_signal
+
+ logical function mtd_descriptors_conflict(left,right)
+ type(ft8_subtraction_descriptor), intent(in) :: left,right
+ logical :: overlap
+
+ overlap=left%clipped_start.le.left%clipped_end .and. &
+ right%clipped_start.le.right%clipped_end .and. &
+ left%clipped_start.le.right%clipped_end .and. &
+ right%clipped_start.le.left%clipped_end
+ mtd_descriptors_conflict=overlap .and. &
+ abs(left%frequency-right%frequency).lt.mtd_interaction_bandwidth
+ end function mtd_descriptors_conflict
+
+ subroutine mtd_transform_phase(ipass)
+ integer, intent(in) :: ipass
+
+!$omp critical(ft8_mtd_canonical)
+ call wsjt_tsan_acquire_ft8_mtd()
+ if(ipass.eq.4) then
+ post_pass3_residual=canonical_residual
+ call mtd_forward_half_sample(canonical_residual)
+ else if(ipass.eq.7) then
+ canonical_residual=post_pass3_residual
+ call mtd_backward_half_sample(canonical_residual)
+ else
+ error stop 'Invalid MTD transform pass'
+ endif
+ current_epoch=current_epoch+1_int64
+ canonical_generation=canonical_generation+1_int64
+ call wsjt_tsan_release_ft8_mtd()
+!$omp end critical(ft8_mtd_canonical)
+ end subroutine mtd_transform_phase
+
+ subroutine mtd_finish(output_residual)
+ real, intent(out) :: output_residual(:)
+
+ if(size(output_residual).ne.mtd_residual_samples) error stop &
+ 'MTD output residual has an unexpected sample count'
+!$omp critical(ft8_mtd_canonical)
+ call wsjt_tsan_acquire_ft8_mtd()
+ output_residual=canonical_residual
+ call wsjt_tsan_release_ft8_mtd()
+!$omp end critical(ft8_mtd_canonical)
+ end subroutine mtd_finish
+
+ subroutine mtd_forward_half_sample(residual)
+ real, intent(inout) :: residual(:)
+ integer :: i
+
+ if(size(residual).ne.mtd_residual_samples) error stop &
+ 'MTD forward transform has an unexpected sample count'
+ do i=1,mtd_residual_samples-1
+ residual(i)=(residual(i)+residual(i+1))/2.0
+ enddo
+ end subroutine mtd_forward_half_sample
+
+ subroutine mtd_backward_half_sample(residual)
+ real, intent(inout) :: residual(:)
+ integer :: i
+
+ if(size(residual).ne.mtd_residual_samples) error stop &
+ 'MTD backward transform has an unexpected sample count'
+ do i=mtd_residual_samples,2,-1
+ residual(i)=(residual(i-1)+residual(i))/2.0
+ enddo
+ end subroutine mtd_backward_half_sample
+
+ subroutine assert_worker(worker)
+ integer, intent(in) :: worker
+
+ if(worker.lt.1 .or. worker.gt.active_workers) error stop 'Invalid MTD worker index'
+ end subroutine assert_worker
+
+end module ft8_mtd_residual
diff --git a/lib/ft8var/ft8_tsan.c b/lib/ft8var/ft8_tsan.c
new file mode 100644
index 00000000..1905ca07
--- /dev/null
+++ b/lib/ft8var/ft8_tsan.c
@@ -0,0 +1,30 @@
+#if defined(__SANITIZE_THREAD__)
+#include <sanitizer/tsan_interface.h>
+#endif
+
+// GCC TSan does not observe libgomp synchronization. Stable tokens mirror the
+// OpenMP edges without changing production synchronization.
+#if defined(__SANITIZE_THREAD__)
+#define WSJT_TSAN_SYNC(name) \
+ static unsigned char name##_token; \
+ void wsjt_tsan_acquire_##name(void) \
+ { \
+ __tsan_acquire(&name##_token); \
+ } \
+ void wsjt_tsan_release_##name(void) \
+ { \
+ __tsan_release(&name##_token); \
+ }
+#else
+#define WSJT_TSAN_SYNC(name) \
+ void wsjt_tsan_acquire_##name(void) {} \
+ void wsjt_tsan_release_##name(void) {}
+#endif
+
+WSJT_TSAN_SYNC(ft8_mtd)
+WSJT_TSAN_SYNC(four2avar_setup)
+WSJT_TSAN_SYNC(ft8_find_dupes)
+WSJT_TSAN_SYNC(ft8_update_structures)
+WSJT_TSAN_SYNC(decoder_section_primary)
+WSJT_TSAN_SYNC(decoder_section_secondary)
+WSJT_TSAN_SYNC(msk40_sync)
diff --git a/lib/ft8var/ft8apsetvar.f90 b/lib/ft8var/ft8apsetvar.f90
index 6a247a38..f23d604e 100644
--- a/lib/ft8var/ft8apsetvar.f90
+++ b/lib/ft8var/ft8apsetvar.f90
@@ -7,15 +7,28 @@ subroutine ft8apsetvar(lmycallstd,lhiscallstd,numthreads)
character*77 c77
character*37 msg,msgchk
character*12 hiscallt,mycallprev,hiscallprev
+ integer :: i1,i3,n3,nlenmyc
logical lnohiscall,unpk77_successvar,first
logical(1) lhoundprev
logical(1), intent(in) :: lmycallstd,lhiscallstd
+ type(unpack77_options) :: no_record_options
+ type(pack77_options) :: no_tx_hash_options
data mycallprev/'QQ2QQ'/
data hiscallprev/'QQ1QQ'/
data lhoundprev/.false./
data first/.true./
save hiscallprev,mycallprev,lhoundprev,first
+ i1=0
+ i3=-1
+ n3=-1
+ nlenmyc=0
+! AP mask generation packs and unpacks synthetic messages only to derive symbol
+! masks; it must not teach those calls to the shared hash or recent-call state.
+ no_record_options=unpack77_options(record_hashes=.false., &
+ record_recent_calls=.false.)
+ no_tx_hash_options=pack77_options(record_tx_hashes=.false.)
+
if(hiscall.ne.hiscallprev .or. mycall.ne.mycallprev .or. (lhound.neqv.lhoundprev) .or. first) then ! first for lhound triggered
first=.false.; mycallprev=mycall; lhoundprev=lhound
@@ -38,8 +51,8 @@ subroutine ft8apsetvar(lmycallstd,lhiscallstd,numthreads)
else; msg='CQ '//trim(hiscall)
endif
- call pack77var(msg,i3,n3,c77,0)
- call unpack77var(c77,1,msgchk,unpk77_successvar,25)
+ call pack77(msg,i3,n3,c77,no_tx_hash_options)
+ call unpack77_configured(c77,1,msgchk,unpk77_successvar,no_record_options)
!read(c77(75:77),'(b3)') k3; print *,'i3 =',k3; print *,msgchk
if(lhiscallstd .and. i3.ne.1 .or. .not.lhiscallstd .and. i3.ne.4 .or. (msg.ne.msgchk) .or. .not.unpk77_successvar) go to 1
read(c77,'(77i1)',err=1) apcqsym(1:77)
@@ -49,8 +62,8 @@ subroutine ft8apsetvar(lmycallstd,lhiscallstd,numthreads)
if(lhiscallstd .and. .not.lmycallstd) then
msg=trim(hiscall)//' '//trim(hiscall)//' RRR'
i3=0; n3=0
- call pack77var(msg,i3,n3,c77,0)
- call unpack77var(c77,1,msgchk,unpk77_successvar,25)
+ call pack77(msg,i3,n3,c77,no_tx_hash_options)
+ call unpack77_configured(c77,1,msgchk,unpk77_successvar,no_record_options)
!read(c77(75:77),'(b3)') k3; print *,'i3 =',k3; print *,msgchk
if(i3.ne.1 .or. (msg.ne.msgchk) .or. .not.unpk77_successvar) go to 2
read(c77,'(58i1)',err=2) apsymdxstd(1:58)
@@ -60,16 +73,16 @@ subroutine ft8apsetvar(lmycallstd,lhiscallstd,numthreads)
if(.not.lhound .and. .not.lhiscallstd .and. len_trim(hiscall).gt.2) then
! nonstandard DXCall searching
msg='<W9XYZ> '//trim(hiscall)//' RR73'
- call pack77var(msg,i3,n3,c77,0)
- call unpack77var(c77,1,msgchk,unpk77_successvar,25)
+ call pack77(msg,i3,n3,c77,no_tx_hash_options)
+ call unpack77_configured(c77,1,msgchk,unpk77_successvar,no_record_options)
!read(c77(75:77),'(b3)') k3; print *,'i3 =',k3; print *,msgchk
if(i3.ne.4 .or. .not.unpk77_successvar) go to 3
read(c77,'(77i1)',err=3) apsymdxnsrr73(1:77)
apsymdxnsrr73=2*apsymdxnsrr73-1
msg='<W9XYZ> '//trim(hiscall)//' 73'
- call pack77var(msg,i3,n3,c77,0)
- call unpack77var(c77,1,msgchk,unpk77_successvar,25)
+ call pack77(msg,i3,n3,c77,no_tx_hash_options)
+ call unpack77_configured(c77,1,msgchk,unpk77_successvar,no_record_options)
!read(c77(75:77),'(b3)') k3; print *,'i3 =',k3; print *,msgchk
if(i3.ne.4 .or. .not.unpk77_successvar) go to 4
read(c77,'(77i1)',err=4) apsymdxns73(1:77)
@@ -80,28 +93,28 @@ subroutine ft8apsetvar(lmycallstd,lhiscallstd,numthreads)
if(.not.lhound .and. .not.lmycallstd .and. len_trim(mycall).gt.2) then
if(lhiscallstd) then
msg='<'//trim(mycall)//'> '//trim(hiscall)//' -15'
- call pack77var(msg,i3,n3,c77,0)
- call unpack77var(c77,1,msgchk,unpk77_successvar,25)
+ call pack77(msg,i3,n3,c77,no_tx_hash_options)
+ call unpack77_configured(c77,1,msgchk,unpk77_successvar,no_record_options)
if(i3.ne.1 .or. msg.ne.msgchk .or. .not.unpk77_successvar) go to 5
read(c77,'(58i1)',err=5) apsymmyns2(1:58)
apsymmyns2=2*apsymmyns2-1
nlenmyc=len_trim(mycall)
msg=trim(mycall)//' <'//trim(hiscall)//'> RR73'
- call pack77var(msg,i3,n3,c77,0)
- call unpack77var(c77,1,msgchk,unpk77_successvar,25)
+ call pack77(msg,i3,n3,c77,no_tx_hash_options)
+ call unpack77_configured(c77,1,msgchk,unpk77_successvar,no_record_options)
if(i3.ne.4 .or. msg.ne.msgchk .or. .not.unpk77_successvar) go to 6
read(c77,'(77i1)',err=6) apsymmynsrr73(1:77)
apsymmynsrr73=2*apsymmynsrr73-1
msg=trim(mycall)//' <'//trim(hiscall)//'> 73'
- call pack77var(msg,i3,n3,c77,0)
- call unpack77var(c77,1,msgchk,unpk77_successvar,25)
+ call pack77(msg,i3,n3,c77,no_tx_hash_options)
+ call unpack77_configured(c77,1,msgchk,unpk77_successvar,no_record_options)
if(i3.ne.4 .or. msg.ne.msgchk .or. .not.unpk77_successvar) go to 7
read(c77,'(77i1)',err=7) apsymmyns73(1:77)
apsymmyns73=2*apsymmyns73-1
msg=trim(mycall)//' <'//trim(hiscall)//'> RRR'
- call pack77var(msg,i3,n3,c77,0)
- call unpack77var(c77,1,msgchk,unpk77_successvar,25)
+ call pack77(msg,i3,n3,c77,no_tx_hash_options)
+ call unpack77_configured(c77,1,msgchk,unpk77_successvar,no_record_options)
if(i3.ne.4 .or. msg.ne.msgchk .or. .not.unpk77_successvar) go to 15
read(c77,'(77i1)',err=15) apsymmynsrrr(1:77)
apsymmynsrrr=2*apsymmynsrrr-1
@@ -109,8 +122,8 @@ subroutine ft8apsetvar(lmycallstd,lhiscallstd,numthreads)
else if(lnohiscall) then
msg='<'//trim(mycall)//'> ZZ1ZZZ -15'
- call pack77var(msg,i3,n3,c77,0)
- call unpack77var(c77,1,msgchk,unpk77_successvar,25)
+ call pack77(msg,i3,n3,c77,no_tx_hash_options)
+ call unpack77_configured(c77,1,msgchk,unpk77_successvar,no_record_options)
if(i3.ne.1 .or. msgchk.ne.msg .or. .not.unpk77_successvar) go to 8
read(c77,'(29i1)',err=8) apsymmyns1(1:29)
apsymmyns1=2*apsymmyns1-1
@@ -122,8 +135,8 @@ subroutine ft8apsetvar(lmycallstd,lhiscallstd,numthreads)
if(.not.lhound .and. lmycallstd .and. (lhiscallstd .or. lnohiscall)) then
msg=trim(mycall)//' '//trim(hiscallt)//' RRR'
i3=0; n3=0
- call pack77var(msg,i3,n3,c77,0)
- call unpack77var(c77,1,msgchk,unpk77_successvar,25)
+ call pack77(msg,i3,n3,c77,no_tx_hash_options)
+ call unpack77_configured(c77,1,msgchk,unpk77_successvar,no_record_options)
!read(c77(75:77),'(b3)') k3; print *,'i3 =',k3; print *,msgchk
if(i3.ne.1 .or. (msg.ne.msgchk) .or. .not.unpk77_successvar) go to 9
read(c77,'(58i1)',err=9) apsym(1:58)
@@ -134,8 +147,8 @@ subroutine ft8apsetvar(lmycallstd,lhiscallstd,numthreads)
! standard messages from Fox, always base callsigns
if(len_trim(hisbcall).gt.2 .and. len_trim(mybcall).gt.2) then
msg=trim(mybcall)//' '//trim(hisbcall)//' -15'
- call pack77var(msg,i3,n3,c77,0)
- call unpack77var(c77,1,msgchk,unpk77_successvar,25)
+ call pack77(msg,i3,n3,c77,no_tx_hash_options)
+ call unpack77_configured(c77,1,msgchk,unpk77_successvar,no_record_options)
!read(c77(75:77),'(b3)') k3; print *,'i3 =',k3; print *,msgchk
if(i3.ne.1 .or. (msg.ne.msgchk) .or. .not.unpk77_successvar) go to 9
read(c77,'(58i1)',err=9) apsym(1:58)
@@ -147,8 +160,8 @@ subroutine ft8apsetvar(lmycallstd,lhiscallstd,numthreads)
! special messages
msg=trim(mycall)//' RR73; '//trim(mycall)//' <'//trim(hiscallt)//'> -16'
i3=0; n3=1
- call pack77var(msg,i3,n3,c77,0)
- call unpack77var(c77,1,msgchk,unpk77_successvar,25)
+ call pack77(msg,i3,n3,c77,no_tx_hash_options)
+ call unpack77_configured(c77,1,msgchk,unpk77_successvar,no_record_options)
!read(c77(75:77),'(b3)') k3; print *,'i3 =',k3; print *,msgchk
i1=0; i1=index(msgchk,'<'); if(i1.lt.15) return
if(i3.ne.0 .or. msg(1:i1).ne.msgchk(1:i1) .or. .not.unpk77_successvar) go to 10
@@ -158,32 +171,32 @@ subroutine ft8apsetvar(lmycallstd,lhiscallstd,numthreads)
if(.not.lhound .and. lmycallstd .and. .not.lhiscallstd .and. len_trim(hiscall).gt.2) then
msg=trim(mycall)//' <'//trim(hiscall)//'> -16' ! report, rreport
- call pack77var(msg,i3,n3,c77,0)
- call unpack77var(c77,1,msgchk,unpk77_successvar,25)
+ call pack77(msg,i3,n3,c77,no_tx_hash_options)
+ call unpack77_configured(c77,1,msgchk,unpk77_successvar,no_record_options)
!read(c77(75:77),'(b3)') k3; print *,'i3 =',k3; print *,msgchk
if(i3.ne.1 .or. msg.ne.msgchk .or. .not.unpk77_successvar) go to 11
read(c77,'(58i1)',err=11) apsymdxns1(1:58)
apsymdxns1=2*apsymdxns1-1
msg='<'//trim(mycall)//'> '//trim(hiscall)//' RRR'
- call pack77var(msg,i3,n3,c77,0)
- call unpack77var(c77,1,msgchk,unpk77_successvar,25)
+ call pack77(msg,i3,n3,c77,no_tx_hash_options)
+ call unpack77_configured(c77,1,msgchk,unpk77_successvar,no_record_options)
!read(c77(75:77),'(b3)') k3; print *,'i3 =',k3; print *,msgchk
if(i3.ne.4 .or. msg.ne.msgchk .or. .not.unpk77_successvar) go to 12
read(c77,'(77i1)',err=12) apsymdxnsrrr(1:77)
apsymdxnsrrr=2*apsymdxnsrrr-1
msg='<'//trim(mycall)//'> '//trim(hiscall)//' RR73'
- call pack77var(msg,i3,n3,c77,0)
- call unpack77var(c77,1,msgchk,unpk77_successvar,25)
+ call pack77(msg,i3,n3,c77,no_tx_hash_options)
+ call unpack77_configured(c77,1,msgchk,unpk77_successvar,no_record_options)
!read(c77(75:77),'(b3)') k3; print *,'i3 =',k3; print *,msgchk
if(i3.ne.4 .or. msg.ne.msgchk .or. .not.unpk77_successvar) go to 13
read(c77,'(77i1)',err=13) apsymdxnsr73(1:77)
apsymdxnsr73=2*apsymdxnsr73-1
msg='<'//trim(mycall)//'> '//trim(hiscall)//' 73'
- call pack77var(msg,i3,n3,c77,0)
- call unpack77var(c77,1,msgchk,unpk77_successvar,25)
+ call pack77(msg,i3,n3,c77,no_tx_hash_options)
+ call unpack77_configured(c77,1,msgchk,unpk77_successvar,no_record_options)
!read(c77(75:77),'(b3)') k3; print *,'i3 =',k3; print *,msgchk
if(i3.ne.4 .or. msg.ne.msgchk .or. .not.unpk77_successvar) go to 14
read(c77,'(77i1)',err=14) apsymdxns732(1:77)
diff --git a/lib/ft8var/ft8bvar.f90 b/lib/ft8var/ft8bvar.f90
index 6a12b933..caf1d94c 100644
--- a/lib/ft8var/ft8bvar.f90
+++ b/lib/ft8var/ft8bvar.f90
@@ -1,47 +1,57 @@
-subroutine ft8bvar(newdat1,nQSOProgress,nfqso,nftx,napwid,lsubtract,npos,freqsub, &
- tmpcqdec,tmpmyc,nagainfil,iaptype,f1,xdt,nbadcrc,lft8sdec,msg37,msg37_2, &
+subroutine ft8bvar(residual,spectrum,newdat1,nQSOProgress,nfqso,nftx,napwid, &
+ lsubtract,tmpcqdec,tmpmyc,nagainfil,iaptype,f1,xdt,nbadcrc,lft8sdec, &
+ msg37,msg37_2, &
xsnr,stophint,nthr,lFreeText,ipass,lft8subpass,lspecial,lcqcand,ncqsignal, &
nmycsignal,npass,i3bit,lft8s,lmycallstd,lhiscallstd,levenint,loddint,lft8sd, &
i3,n3,nft8rxfsens,ncount,msgsrcvd,lrepliedother,lhashmsg,lqsothread, &
- lft8lowth,lhighsens,lsubtracted,tmpcqsig,tmpmycsig,tmpqsosig,lnohiscall, &
- lnomycall,lnohisgrid,qual,iaptype2)
+ lft8lowth,lhighsens,tmpcqsig,tmpmycsig,tmpqsosig,lnohiscall, &
+ lnomycall,lnohisgrid,qual,iaptype2,progress_generation)
- use packjt77, only : unpack77var
+ use packjt77, only : unpack77, unpack77_configured, unpack77_options
+ use ft8_mtd_residual, only : mtd_commit_subtraction,mtd_mark_spectrum_current, &
+ mtd_refresh_candidate
+ use decode_completion_module, only : write_decode_progress
use ft8_mod1, only : allmessages,ndecodes,apsym,mcq,m73,mrr73,mrrr,icos7, &
naptypes,nhaptypes,one,graymap,oddcopy,evencopy,lastrxmsg,lasthcall, &
nlasttx,calldteven,calldtodd,lqsomsgdcd,mycalllen1,msgroot,msgrootlen, &
- allfreq,idtone25,lapmyc,idtonemyc,mycall,hiscall,lhound,apsymsp, &
+ allfreq,idtone25,idtone25_valid,lapmyc,idtonemyc,mycall,hiscall,lhound,apsymsp, &
ndxnsaptypes,apsymdxns1,apsymdxnsrrr,lenabledxcsearch,lwidedxcsearch, &
apcqsym,apsymdxnsrr73,apsymdxns73,mybcall,hisbcall,lskiptx1,nft8cycles, &
ctwkw,ctwkn,nincallthr,msgincall,xdtincall,maskincallthr,ctwk256,numcqsig, &
numdeccq,evencq,oddcq,nummycsig,numdecmyc,evenmyc,oddmyc,idtone56, &
+ idtone56_valid, &
idtonecqdxcns,evenqso,oddqso,nmycnsaptypes,apsymmyns1,apsymmyns2, &
apsymmynsrr73,apsymmyns73,apsymdxstd,apsymdxnsr73,apsymdxns732,ltxing, &
apsymmynsrrr,idtonedxcns73,idtonefox73,idtonespec !ft8md added
include 'ft8_params.f90'
+ real, intent(inout) :: residual(180000)
+ complex, intent(inout) :: spectrum(0:96000)
character c77*77,msg37*37,msg37_2*37,msgd*37,msgbase37*37,call_a*12,call_b*12
character callsign*12,grid*12
character*37 msgsrcvd(130)
complex cd0(-800:4000),cd1(-800:4000),cd2(-800:4000),cd3(-800:4000),ctwk(32), &
- csymb(32),cs(0:7,79),csymbr(32),csr(0:7,79),csig(32),csig0(151680),z1, &
+ csymb(32),cs(0:7,79),csymbr(32),csr(0:7,79),csig(32),z1, &
csymb256(256),cstmp2(0:7,79),csold(0:7,79),cscs(0:7,79)
+ complex, allocatable :: csig0(:)
real a(5),s8(0:7,79),s82(0:7,79),s2(0:511),sp(0:7),s81(0:7),snrsync(21), &
- syncw(7),sumkw(7),scoreratiow(7),freqsub(200),s256(0:8),s2563(0:26), &
+ syncw(7),sumkw(7),scoreratiow(7),s256(0:8),s2563(0:26), &
syncavpart(3)
real bmeta(174),bmetb(174),bmetc(174),bmetd(174)
real llra(174),llrb(174),llrc(174),llrd(174),llrz(174)
real qual !ft8md
integer*1 message77(77),apmask(174),cw(174),nsmax(8)
integer itone(79),ip(1),ka(1),nqsoend(3)
- integer, intent(in) :: nQSOProgress,nfqso,nftx,napwid,nthr,ipass,nft8rxfsens
+ integer, intent(in) :: nQSOProgress,nfqso,nftx,napwid,nthr,ipass,nft8rxfsens, &
+ progress_generation
logical newdat1,lsubtract,lFreeText,nagainfil,lspecial,unpk77_successvar
+ logical rebuild_spectrum
logical(1), intent(in) :: stophint,lft8subpass,lmycallstd,lhiscallstd, &
lqsothread,lft8lowth,lhighsens,lcqcand,levenint,loddint,lnohiscall, &
lnomycall,lnohisgrid
logical(1) falsedec,lastsync,ldupemsg,lft8s,lft8sdec,lft8sd,lsdone,ldupeft8sd, &
lrepliedother,lhashmsg,lvirtual2,lvirtual3,lsd,lcq,ldeepsync,lcallsstd, &
- lfound,lsubptxfreq,lreverse,lchkcall,lgvalid,lwrongcall,lsubtracted, &
+ lfound,lsubptxfreq,lreverse,lchkcall,lgvalid,lwrongcall, &
lcqsignal,loutapwid,lfoundcq,lmycsignal,lfoundmyc,lqsosig,ldxcsig, &
lcqdxcsig,lcqdxcnssig,lqsocandave,lcall1hash,lqsosigtype3,lqso73,lqsorr73, &
lqsorrr,lfoxspecrpt,lfoxstdr73,lapcqonly,lcall2hash,lskipnotap
@@ -185,8 +195,10 @@ subroutine ft8bvar(newdat1,nQSOProgress,nfqso,nftx,napwid,lsubtract,npos,freqsub
endif
endif
- call ft8_downsamplevar(newdat1,f1,nqso,cd0,cd2,cd3,lhighsens,lsubtracted,npos, &
- freqsub) !Mix f1 to baseband and downsample
+ call mtd_refresh_candidate(nthr,f1,newdat1,rebuild_spectrum)
+ call ft8_downsamplevar(residual,spectrum,newdat1,f1,nqso,cd0,cd2,cd3, &
+ lhighsens) !Mix f1 to baseband and downsample
+ if(rebuild_spectrum) call mtd_mark_spectrum_current(nthr)
lsd=.false.
isd=1
@@ -847,16 +859,18 @@ subroutine ft8bvar(newdat1,nQSOProgress,nfqso,nftx,napwid,lsubtract,npos,freqsub
if(.not.lqsomsgdcd .and. (dfqso.lt.napwid .or. abs(nftx-f1).lt.napwid) .and. &
lapmyc .and. len_trim(hiscall).gt.2) then
nqsot=0
- do i=1,19
- ip=maxloc(s8(:,i+7))
- if(ip(1).eq.idtone56(1,i)+1) nqsot=nqsot+1
- enddo
- if(nqsot.gt.6) lqsosig=.true. ! decoding depth only
- do i=20,22
- ip=maxloc(s8(:,i+7))
- if(ip(1).eq.idtone56(1,i)+1) nqsot=nqsot+1
- enddo
- if(nqsot.gt.3) lqsosigtype3=.true.
+ if(idtone56_valid(1)) then
+ do i=1,19
+ ip=maxloc(s8(:,i+7))
+ if(ip(1).eq.idtone56(1,i)+1) nqsot=nqsot+1
+ enddo
+ if(nqsot.gt.6) lqsosig=.true. ! decoding depth only
+ do i=20,22
+ ip=maxloc(s8(:,i+7))
+ if(ip(1).eq.idtone56(1,i)+1) nqsot=nqsot+1
+ enddo
+ if(nqsot.gt.3) lqsosigtype3=.true.
+ endif
nqsoend=0 ! array 73,rr73,rrr
if(dfqso.lt.napwid .and. (nQSOProgress.eq.3 .or. nQSOProgress.eq.4)) then
! QSO RX freq only
@@ -866,9 +880,9 @@ subroutine ft8bvar(newdat1,nQSOProgress,nfqso,nftx,napwid,lsubtract,npos,freqsub
else
ip=maxloc(s8(:,i+14))
endif
- if(ip(1).eq.idtone56(56,i)+1) nqsoend(1)=nqsoend(1)+1
- if(ip(1).eq.idtone56(55,i)+1) nqsoend(2)=nqsoend(2)+1
- if(ip(1).eq.idtone56(54,i)+1) nqsoend(3)=nqsoend(3)+1
+ if(idtone56_valid(56) .and. ip(1).eq.idtone56(56,i)+1) nqsoend(1)=nqsoend(1)+1
+ if(idtone56_valid(55) .and. ip(1).eq.idtone56(55,i)+1) nqsoend(2)=nqsoend(2)+1
+ if(idtone56_valid(54) .and. ip(1).eq.idtone56(54,i)+1) nqsoend(3)=nqsoend(3)+1
enddo
ip=maxloc(nqsoend)
if(nqsoend(ip(1)).gt.6) then
@@ -900,10 +914,12 @@ subroutine ft8bvar(newdat1,nQSOProgress,nfqso,nftx,napwid,lsubtract,npos,freqsub
lcqdxcnssig=.false.
ndxt=0
if(lhiscallstd) then
- do k11=17,26
- ip=maxloc(s8(:,k11))
- if(ip(1).eq.idtone56(1,k11-7)+1) ndxt=ndxt+1
- enddo
+ if(idtone56_valid(1)) then
+ do k11=17,26
+ ip=maxloc(s8(:,k11))
+ if(ip(1).eq.idtone56(1,k11-7)+1) ndxt=ndxt+1
+ enddo
+ endif
if(ndxt.gt.3) ldxcsig=.true.
if(lcqsignal .and. ldxcsig) lcqdxcsig=.true.
endif
@@ -1056,6 +1072,7 @@ subroutine ft8bvar(newdat1,nQSOProgress,nfqso,nftx,napwid,lsubtract,npos,freqsub
endif
do isubp1=1,nsubpasses
+ call write_decode_progress(progress_generation)
if(nweak.eq.1 .and. isubp1.eq.2) cycle
! skip if it is lmycsignal, can be both lcq and lmy
@@ -1307,6 +1324,7 @@ subroutine ft8bvar(newdat1,nQSOProgress,nfqso,nftx,napwid,lsubtract,npos,freqsub
! print*,'hisgrid is ',hisgrid
do isubp2=1,31
+ call write_decode_progress(progress_generation)
if(isubp2.lt.5) then
if(lapcqonly .or. lskipnotap) cycle
if(ltxing) then
@@ -1381,6 +1399,7 @@ subroutine ft8bvar(newdat1,nQSOProgress,nfqso,nftx,napwid,lsubtract,npos,freqsub
if(iaptype.eq.1) then
if(isubp2.eq.20) then
+ if(.not.idtone25_valid(2)) cycle
scqlev=0.
do i4=1,9
scqlev=scqlev+s8(idtone25(2,i4),i4+7)
@@ -1553,6 +1572,7 @@ subroutine ft8bvar(newdat1,nQSOProgress,nfqso,nftx,napwid,lsubtract,npos,freqsub
if(iaptype.eq.1) then
if(isubp2.eq.20) then
+ if(.not.idtone25_valid(2)) cycle
scqlev=0.
do i4=1,9
scqlev=scqlev+s8(idtone25(2,i4),i4+7)
@@ -1703,6 +1723,7 @@ subroutine ft8bvar(newdat1,nQSOProgress,nfqso,nftx,napwid,lsubtract,npos,freqsub
if(iaptype.eq.1) then
if(isubp2.eq.20) then
+ if(.not.idtone25_valid(2)) cycle
scqlev=0.
do i4=1,9
scqlev=scqlev+s8(idtone25(2,i4),i4+7)
@@ -2091,7 +2112,8 @@ subroutine ft8bvar(newdat1,nQSOProgress,nfqso,nftx,napwid,lsubtract,npos,freqsub
if(nagainfil) ndeep=5
!print *,omp_get_nested(),OMP_get_num_threads()
- call osd174_91var(llrz,apmask,ndeep,message77,cw,nharderrors,dmin,nthr)
+ call osd174_91var(llrz,apmask,ndeep,message77,cw,nharderrors,dmin, &
+ nthr,progress_generation)
endif
nbadcrc=1
@@ -2253,7 +2275,8 @@ subroutine ft8bvar(newdat1,nQSOProgress,nfqso,nftx,napwid,lsubtract,npos,freqsub
! and n3.eq.5 for USA calls with EU VHF
! added .or. n3.eq.2 .or. n3.eq.8 .or. n3.eq.9 as test for EU VHF
!print*,'did not cycle at line 2248'
- call unpack77var(c77,1,msg37,unpk77_successvar,nthr)
+ call unpack77_configured(c77,1,msg37,unpk77_successvar, &
+ unpack77_options(thread_index=nthr))
if(.not.unpk77_successvar) then
if(lqsothread .and. (.not.lhound .and. iaptype.ge.3 .or. lhound .and. &
(iaptype.eq.21 .or. iaptype.eq.23)) .and. .not.lsdone) then
@@ -2901,6 +2924,7 @@ subroutine ft8bvar(newdat1,nQSOProgress,nfqso,nftx,napwid,lsubtract,npos,freqsub
syncp=0.
syncm=0.
k=1
+ allocate(csig0(151680))
call gen_ft8wavevar(itone,79,1920,2.0,12000.0,0.0,csig0,xjunk,1,151680)
do i=0,78
do j=1,32
@@ -2920,6 +2944,7 @@ subroutine ft8bvar(newdat1,nQSOProgress,nfqso,nftx,napwid,lsubtract,npos,freqsub
z1=sum(cd0(i21:i21+31)*conjg(csig))
syncm = syncm + real(z1)**2 + aimag(z1)**2
enddo
+ deallocate(csig0)
call peakup(syncm,sync0,syncp,dx)
if(abs(dx).gt.1.0) then
scorr=0.
@@ -2927,12 +2952,7 @@ subroutine ft8bvar(newdat1,nQSOProgress,nfqso,nftx,napwid,lsubtract,npos,freqsub
scorr=real(noff)*(dx) ! was * dx ft8md
endif
xdt3=xdt+scorr*dt2
- call subtractft8var(itone,f1,xdt3)
- lsubtracted=.true. ! inside current thread
- if(npos.lt.200) then
- npos=npos+1
- freqsub(npos)=f1
- endif
+ call mtd_commit_subtraction(nthr,ipass,itone,f1,xdt3,residual)
endif
endif
diff --git a/lib/ft8var/ft8mf1var.f90 b/lib/ft8var/ft8mf1var.f90
index eff9f236..df4400bd 100644
--- a/lib/ft8var/ft8mf1var.f90
+++ b/lib/ft8var/ft8mf1var.f90
@@ -1,7 +1,7 @@
subroutine ft8mf1var(s8,itone,msgd,msg37,lft8sd)
- use ft8_mod1, only : itone76,idtone76,msgsd76
+ use ft8_mod1, only : itone76,idtone76,msgsd76,idtone76_valid
real, intent(in) :: s8(0:7,79)
real s8d(0:7,58)
character msgd*37,msg37*37,msggrid*37,c1*12,c2*12,grid*4
@@ -37,6 +37,7 @@ subroutine ft8mf1var(s8,itone,msgd,msg37,lft8sd)
ipk=0; u1=0.0; u2=0.0
do k=1,76
+ if(.not.idtone76_valid(k)) cycle
psum=0.; ref=ref0
do j=1,58; i3=idtone76(k,j); psum=psum + s8d(i3,j); if(i3.eq.mrs(j)) ref=ref - s8d(i3,j) + s8d(mrs2(j),j); enddo
p=psum/ref
diff --git a/lib/ft8var/ft8mfcqvar.f90 b/lib/ft8var/ft8mfcqvar.f90
index 092493da..bd58058e 100644
--- a/lib/ft8var/ft8mfcqvar.f90
+++ b/lib/ft8var/ft8mfcqvar.f90
@@ -1,7 +1,7 @@
subroutine ft8mfcqvar(s8,itone,msgd,msg37,lft8sd)
- use ft8_mod1, only : idtone25
+ use ft8_mod1, only : idtone25,idtone25_valid
real, intent(in) :: s8(0:7,79)
real s8d(0:7,58)
character*37 msgd,msg37,msgsent37
@@ -10,10 +10,14 @@ subroutine ft8mfcqvar(s8,itone,msgd,msg37,lft8sd)
logical(1) lft8sd
if(len_trim(msgd).lt.6) return
+ idtone25(1,1:58)=0
+ idtone25_valid(1)=.false.
i3=-1; n3=-1
call genft8sdvar(msgd,i3,n3,msgsent37,msgbits,itone)
+ if(i3.lt.0) return
idtone25(1,1:29)=itone(8:36)
idtone25(1,30:58)=itone(44:72)
+ idtone25_valid(1)=.true.
thresh=0.0; i1=0; i2=0
do i=1,58; if(i.le.29) then; s8d(0:7,i)=s8(0:7,i+7); else; s8d(0:7,i)=s8(0:7,i+14); endif; enddo
@@ -28,6 +32,7 @@ subroutine ft8mfcqvar(s8,itone,msgd,msg37,lft8sd)
ipk=0; u1=0.0; u2=0.0
do k=1,25
+ if(.not.idtone25_valid(k)) cycle
psum=0.; ref=ref0
do j=1,58; i3=idtone25(k,j); psum=psum + s8d(i3,j); if(i3.eq.mrs(j)) ref=ref - s8d(i3,j) + s8d(mrs2(j),j); enddo
p=psum/ref
diff --git a/lib/ft8var/ft8sd1var.f90 b/lib/ft8var/ft8sd1var.f90
index 7436e586..3c6fd2c5 100644
--- a/lib/ft8var/ft8sd1var.f90
+++ b/lib/ft8var/ft8sd1var.f90
@@ -9,7 +9,7 @@ subroutine ft8sd1var(s8,itone,msgd,msg37,lft8sd,lcq)
integer itone(79),itonedem(58),idtone(58),ip1(1)
integer*1 msgbits(77)
logical(1), intent(in) :: lcq
- logical(1) lft8sd,lr73,lgrid,lmatched(58)
+ logical(1) lft8sd,lr73,lgrid,lmatched(58),valid4(4)
lmatched=.false.; lr73=.false.; lgrid=.false.
itonedem=11
@@ -41,13 +41,17 @@ subroutine ft8sd1var(s8,itone,msgd,msg37,lft8sd,lcq)
i3=-1; n3=-1
msg372=msgd
call genft8sdvar(msg372,i3,n3,msgsent37,msgbits,itone)
+ if(i3.lt.0) return
idtone(1:29)=itone(8:36)
idtone(30:58)=itone(44:72)
else
+ valid4=.false.
do i=1,4
msg372=msg4(i)
i3=-1; n3=-1
call genft8sdvar(msg372,i3,n3,msgsent37,msgbits,itone)
+ if(i3.lt.0) cycle
+ valid4(i)=.true.
idtone4(i,1:29)=itone(8:36)
idtone4(i,30:58)=itone(44:72)
itone4(i,1:79)=itone(1:79)
@@ -70,6 +74,7 @@ subroutine ft8sd1var(s8,itone,msgd,msg37,lft8sd,lcq)
else
nmatchditer1=0; ncrcpatyiter1=0
do i=1,4
+ if(.not.valid4(i)) cycle
nmatch1=0; ncrcpaty1=0
do k=1,58
if(idtone4(i,k).eq.itonedem(k)) then; nmatch1=nmatch1+1; if(k.gt.25) ncrcpaty1=ncrcpaty1+1; endif
diff --git a/lib/ft8var/ft8sdvar.f90 b/lib/ft8var/ft8sdvar.f90
index 202aa711..f6332e64 100644
--- a/lib/ft8var/ft8sdvar.f90
+++ b/lib/ft8var/ft8sdvar.f90
@@ -9,7 +9,7 @@ subroutine ft8sdvar(s8,srr,itone,msgd,msg37,lft8sd,lcq)
integer itone(79),itonedem(58),idtone(58),ip1(1)
integer*1 msgbits(77)
logical(1), intent(in) :: lcq
- logical(1) lft8sd,lmatched(58)
+ logical(1) lft8sd,lmatched(58),valid4(4)
if(index(msgd,' RR73').gt.0 .or. index(msgd,' 73').gt.0) return ! do not process 73 messages
! do not process messages with grid
@@ -39,13 +39,17 @@ subroutine ft8sdvar(s8,srr,itone,msgd,msg37,lft8sd,lcq)
i3=-1; n3=-1
msg372=msgd
call genft8sdvar(msg372,i3,n3,msgsent37,msgbits,itone)
+ if(i3.lt.0) return
idtone(1:29)=itone(8:36)
idtone(30:58)=itone(44:72)
else
+ valid4=.false.
do i=1,4
msg372=msg4(i)
i3=-1; n3=-1
call genft8sdvar(msg372,i3,n3,msgsent37,msgbits,itone)
+ if(i3.lt.0) cycle
+ valid4(i)=.true.
idtone4(i,1:29)=itone(8:36)
idtone4(i,30:58)=itone(44:72)
itone4(i,1:79)=itone(1:79)
@@ -67,6 +71,7 @@ subroutine ft8sdvar(s8,srr,itone,msgd,msg37,lft8sd,lcq)
else
nmatchditer1=0; nbaseiter1=0; ncrcpatyiter1=0;
do i=1,4
+ if(.not.valid4(i)) cycle
nmatch1=0; nbase1=0; ncrcpaty1=0
do k=1,58
if(idtone4(i,k).eq.itonedem(k)) then
diff --git a/lib/ft8var/ft8svar.f90 b/lib/ft8var/ft8svar.f90
index 17aa58f7..1d0cc4fc 100644
--- a/lib/ft8var/ft8svar.f90
+++ b/lib/ft8var/ft8svar.f90
@@ -1,7 +1,8 @@
subroutine ft8svar(s8,srr,itone,msg37,lft8s,nft8rxfsens,stophint)
- use ft8_mod1, only : itone56,idtone56,msg,nlasttx,lastrxmsg,mycall,hiscall
+ use ft8_mod1, only : itone56,idtone56,msg,nlasttx,lastrxmsg,mycall,hiscall, &
+ idtone56_valid
real, intent(in) :: s8(0:7,79),srr
real s8_1(0:7,79),s8d(0:7,58),xsync(21),xmsync(21),xdata(58),xmdata(58),xnoise(79),xmnoise(79)
character, intent(out) :: msg37*37
@@ -9,6 +10,7 @@ subroutine ft8svar(s8,srr,itone,msg37,lft8s,nft8rxfsens,stophint)
integer, intent(out) :: itone(79)
integer, intent(in) :: nft8rxfsens
integer itonedem(58),idtone(58),mrs(58),mrs2(58),mrs3(58),mrs4(58),ip1(1)
+ integer*1 msgbits(77)
logical(1), intent(in) :: stophint
logical(1), intent(out) :: lft8s
logical(1) lmatched(58),lmycall,lhiscall,lrrr,lr73,lcallingrprt,lastrrprt,lastreport,lgrid
@@ -53,12 +55,18 @@ subroutine ft8svar(s8,srr,itone,msg37,lft8s,nft8rxfsens,stophint)
if(lastrxmsg(1)%lstate .and. .not.lmycall .and. lhiscall .and. nlasttx.eq.2) lcallingrprt=.true. ! calling with REPORT
if(lgrid .and. index(msg(53),trim(mycall)//' '//trim(hiscall)//' AA00').eq.1) then ! standard callsigns
+ idtone56(53,1:58)=0
+ itone56(53,1:79)=0
+ idtone56_valid(53)=.false.
i3=-1; n3=-1
- msg(53)=lastrxmsg(1)%lastmsg
- call genft8sdvar(msg(53),i3,n3,msgsent37,msgbits,itone)
- idtone56(53,1:29)=itone(8:36)
- idtone56(53,30:58)=itone(44:72)
- itone56(53,1:79)=itone(1:79)
+ call genft8sdvar(lastrxmsg(1)%lastmsg,i3,n3,msgsent37,msgbits,itone)
+ if(i3.ge.0) then
+ msg(53)=lastrxmsg(1)%lastmsg
+ idtone56(53,1:29)=itone(8:36)
+ idtone56(53,30:58)=itone(44:72)
+ itone56(53,1:79)=itone(1:79)
+ idtone56_valid(53)=.true.
+ endif
endif
do i=1,58
@@ -67,9 +75,11 @@ subroutine ft8svar(s8,srr,itone,msg37,lft8s,nft8rxfsens,stophint)
enddo
nmycall1=0; nbase1=0
- do k=1,19
- if(idtone56(1,k).eq.itonedem(k)) then; if(k.lt.10) nmycall1=nmycall1+1; nbase1=nbase1+1; endif
- enddo
+ if(idtone56_valid(1)) then
+ do k=1,19
+ if(idtone56(1,k).eq.itonedem(k)) then; if(k.lt.10) nmycall1=nmycall1+1; nbase1=nbase1+1; endif
+ enddo
+ endif
! /'-01 ','-02 ','-03 ','-04 ','-05 ','-06 ','-07 ','-08 ','-09 ','-10 ',
! '-11 ','-12 ','-13 ','-14 ','-15 ','-16 ','-17 ','-18 ','-19 ','-20 ',
@@ -89,6 +99,7 @@ subroutine ft8svar(s8,srr,itone,msg37,lft8s,nft8rxfsens,stophint)
nmatchditer1=0; ncrcpatyiter1=0; imax=0
do i=ilow,ihigh
+ if(.not.idtone56_valid(i)) cycle
if(lastreport .and. i.gt.26 .and. i.lt.54) cycle ! RREPORT is not a valid msg, direction change is not allowed
nmatch1=0; ncrcpaty1=0
do k=1,58
@@ -132,6 +143,7 @@ subroutine ft8svar(s8,srr,itone,msg37,lft8s,nft8rxfsens,stophint)
ref0oth=ref0mycl+ref0paty
ipk=0; u1=0.; u2=0.; u1paty=0.; u2paty=0.; u1oth=0.; u2oth=0.
do k=ilow,ihigh
+ if(.not.idtone56_valid(k)) cycle
if(lastreport .and. k.gt.26 .and. k.lt.54) cycle ! GRID, RREPORT is not a valid msg, direction change is not allowed
psum=0.0; ref=ref0; psumpaty=0.; refpaty=ref0paty; psumoth=0.; refoth=ref0oth
do j=1,58; i=idtone56(k,j); psum=psum + s8d(i,j)
diff --git a/lib/ft8var/gen_ft8wavevar.f90 b/lib/ft8var/gen_ft8wavevar.f90
index 2920332a..187e487a 100644
--- a/lib/ft8var/gen_ft8wavevar.f90
+++ b/lib/ft8var/gen_ft8wavevar.f90
@@ -10,6 +10,7 @@ subroutine gen_ft8wavevar(itone,nsym,nsps,bt,fsample,f0,cwave,wave,icmplx,nwave)
integer itone(nsym)
data ibt0/0/
save pulse,twopi,dt,hmod,ibt0,ctab
+!$omp threadprivate(pulse,twopi,dt,hmod,ibt0,ctab)
ibt=nint(10*bt)
if(ibt0.ne.ibt) then
diff --git a/lib/ft8var/genft8sdvar.f90 b/lib/ft8var/genft8sdvar.f90
index 57d1560e..ae2ca408 100644
--- a/lib/ft8var/genft8sdvar.f90
+++ b/lib/ft8var/genft8sdvar.f90
@@ -3,7 +3,7 @@ subroutine genft8sdvar(msg,i3,n3,msgsent,msgbits,itone)
! Encode an FT8 message, producing array itone().
- use packjt77sdvar
+ use packjt77
use ft8_mod1, only : icos7,graymap
character msg*37,msgsent*37,c77*77
integer*1 msgbits(77),codeword(174)
@@ -12,8 +12,16 @@ subroutine genft8sdvar(msg,i3,n3,msgsent,msgbits,itone)
i3=-1
n3=-1
- call pack77sdvar(msg,i3,n3,c77)
- call unpack77sdvar(c77,msgsent,unpk77_successvar)
+ call pack77(msg,i3,n3,c77,pack77_options(record_tx_hashes=.false.))
+ ! SD thresholds are calibrated for classic Type 1/2 templates only.
+ if(.not.(i3.ge.0 .and. (i3.eq.1 .or. i3.eq.2) .and. &
+ index(msg,'<').eq.0)) then
+ i3=-1
+ n3=-1
+ endif
+ if(i3.lt.0) go to 1
+ call unpack77_configured(c77,0,msgsent,unpk77_successvar, &
+ unpack77_options(record_hashes=.false.,record_recent_calls=.false.))
read(c77,'(77i1)',err=1) msgbits
if(unpk77_successvar) go to 2
1 msgbits=0
diff --git a/lib/ft8var/genft8var.f90 b/lib/ft8var/genft8var.f90
index 5166e580..86defc7e 100644
--- a/lib/ft8var/genft8var.f90
+++ b/lib/ft8var/genft8var.f90
@@ -9,14 +9,10 @@ subroutine genft8var(msg,i3,n3,ntxhash,msgsent,msgbits,itone)
integer itone(79)
logical unpk77_successvar
- i3=-1
- n3=-1
- call pack77var(msg,i3,n3,c77,ntxhash)
- if(ntxhash.eq.1) then
- call unpack77var(c77,0,msgsent,unpk77_successvar,26) !TX message, unpack to get msgsent, use TX hash tables and do not save RX hash values
- else
- call unpack77var(c77,0,msgsent,unpk77_successvar,27) !service message, unpack to get msgsent. Do not save hash values
- endif
+ call pack77(msg,i3,n3,c77, &
+ pack77_options(record_tx_hashes=ntxhash.eq.1))
+ call unpack77_configured(c77,0,msgsent,unpk77_successvar, &
+ unpack77_options(record_hashes=.false.,record_recent_calls=.false.))
read(c77,'(77i1)',err=1) msgbits
if(unpk77_successvar) go to 2
1 msgbits=0
diff --git a/lib/ft8var/jt65_mod9.f90 b/lib/ft8var/jt65_mod9.f90
index 6fc3413d..b116dc08 100644
--- a/lib/ft8var/jt65_mod9.f90
+++ b/lib/ft8var/jt65_mod9.f90
@@ -1,5 +1,7 @@
module jt65_mod9
! stores callsign DB in memory for false decodes checking
+
+ save
parameter (MAXC=200000)
! supporting 7-char Australian callsigns
diff --git a/lib/ft8var/osd174_91var.f90 b/lib/ft8var/osd174_91var.f90
index d46fd377..16aa6667 100644
--- a/lib/ft8var/osd174_91var.f90
+++ b/lib/ft8var/osd174_91var.f90
@@ -1,8 +1,10 @@
-subroutine osd174_91var(llr,apmask,ndeep,message77,cw,nhardmin,dmin,nthr)
+subroutine osd174_91var(llr,apmask,ndeep,message77,cw,nhardmin,dmin,nthr, &
+ progress_generation)
!
! An ordered-statistics decoder for the (174,91) code.
!
use ft8_mod1, only : first_osd,gen
+use decode_completion_module, only : write_decode_progress
integer, parameter:: N=174, K=91, M=N-K
integer*1 apmask(N),apmaskr(N)
integer*1 genmrb(K,N),g2(N,K)
@@ -12,7 +14,8 @@ integer indices(N),nxor(N)
integer*1 cw(N),ce(N),c0(N),hdec(N)
integer*1 decoded(K)
integer*1 message77(77)
-integer indx(N)
+integer indx(N),progress_work
+integer, intent(in) :: progress_generation
real llr(N),rx(N),absrx(N)
include '/lib/ft8/ldpc_174_91_c_generator.f90'
logical reset
@@ -37,8 +40,8 @@ interface
end interface
npre1=0; npre2=0; d1=0.
-if(first_osd) then ! fill the generator matrix
!$omp critical(first_osd)
+if(first_osd) then ! fill the generator matrix
gen=0
do i=1,M
do j=1,23
@@ -55,8 +58,8 @@ if(first_osd) then ! fill the generator matrix
gen(irow,irow)=1
enddo
first_osd=.false.
-!$omp end critical(first_osd)
endif
+!$omp end critical(first_osd)
rx=llr
apmaskr=apmask
@@ -161,10 +164,13 @@ elseif(ndeep.eq.5) then
endif
do iorder=1,nord
+ progress_work=0
misub(1:K-iorder)=0
misub(K-iorder+1:K)=1
iflag=K-iorder+1
do while(iflag .ge.0)
+ progress_work=progress_work+1
+ if(mod(progress_work,32).eq.0) call write_decode_progress(progress_generation)
if(iorder.eq.nord .and. npre1.eq.0) then
iend=iflag
else
@@ -220,6 +226,7 @@ if(npre2.eq.1) then
reset=.true.
ntotal=0
do i1=K,1,-1
+ if(mod(i1,8).eq.0) call write_decode_progress(progress_generation)
do i2=i1-1,1,-1
ntotal=ntotal+1
mi(1:ntau)=ieor(g2(K+1:K+ntau,i1),g2(K+1:K+ntau,i2))
@@ -234,7 +241,10 @@ if(npre2.eq.1) then
misub(1:K-nord)=0
misub(K-nord+1:K)=1
iflag=K-nord+1
+ progress_work=0
do while(iflag .ge.0)
+ progress_work=progress_work+1
+ if(mod(progress_work,32).eq.0) call write_decode_progress(progress_generation)
me=ieor(m0,misub)
call mrbencode91var(me,ce,g2,N,K)
e2sub=ieor(ce(K+1:N),hdec(K+1:N))
@@ -397,4 +407,4 @@ subroutine fetchit91var(indexes,fp,np,reset,e2,ntau,i1,i2,nthr)
lastpat(nthr)=ipat
return
-end subroutine fetchit91var \ No newline at end of file
+end subroutine fetchit91var
diff --git a/lib/ft8var/packjt77sdvar.f90 b/lib/ft8var/packjt77sdvar.f90
deleted file mode 100644
index 5d02407c..00000000
--- a/lib/ft8var/packjt77sdvar.f90
+++ /dev/null
@@ -1,558 +0,0 @@
-
-module packjt77sdvar
-
-! These variables are accessible from outside via "use packjt77sdvar":
-! integer n28avar,n28bvar
-
- contains
-
-subroutine pack77sdvar(msg0,i3,n3,c77)
-
- use packjt
- character*37 msg,msg0
- character*13 w(19)
- character*77 c77
- integer nw(19)
-
- msg=msg0
-
-! Convert msg to upper case; collapse multiple blanks; parse into words.
- call split77var(msg,nwords,nw,w)
- i3=-1
- n3=-1
- if(msg(1:3).eq.'CQ ' .or. msg(1:3).eq.'DE ' .or. msg(1:4).eq.'QRZ ') go to 100
-
-! Check Type 1 (Standard 77-bit message) or Type 2, with optional "/P"
-100 call pack77_1var(nwords,w,i3,n3,c77)
- if(i3.ge.0) go to 900
-
-! It defaults to free text
- i3=0
- n3=0
- msg(14:)=' '
- call packtext77var(msg(1:13),c77(1:71))
- write(c77(72:77),'(2b3.3)') n3,i3
-
-900 return
-end subroutine pack77sdvar
-
-subroutine unpack77sdvar(c77,msg,unpk77_successvar)
-
- parameter (MAXGRID4=32400)
- integer*8 n58
- character*77 c77*77,msg*37,c*38,call_1*13,call_2*13,c11*11,grid4*4,crpt*3
- logical unpk28_success,unpk77_successvar
-
- data c/' 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ/'/
-
- unpk77_successvar=.true.
-
-! Check for bad data
- do i=1,77
- if(c77(i:i).ne.'0' .and. c77(i:i).ne.'1') then
- msg='failed unpack'
- unpk77_successvar=.false.
- return
- endif
- enddo
-
- read(c77(72:77),'(2b3)') n3,i3
- msg=repeat(' ',37)
- if(i3.eq.0 .and. n3.eq.0) then
-! 0.0 Free text
- call unpacktext77var(c77(1:71),msg(1:13))
- msg(14:)=' '
- msg=adjustl(msg)
-
- else if(i3.eq.1 .or. i3.eq.2) then
-! Type 1 (standard message) or Type 2 ("/P" form for EU VHF contest)
- read(c77,1000) n28avar,ipa,n28bvar,ipb,ir,igrid4,i3
-1000 format(2(b28,b1),b1,b15,b3)
- call unpack28var(n28avar,call_1,unpk28_success)
- if(.not.unpk28_success) unpk77_successvar=.false.
- call unpack28var(n28bvar,call_2,unpk28_success)
- if(.not.unpk28_success) unpk77_successvar=.false.
- if(call_1(1:3).eq.'CQ_') call_1(3:3)=' '
- if(index(call_1,'<').le.0) then
- i=index(call_1,' ')
- if(i.ge.4 .and. ipa.eq.1 .and. i3.eq.1) call_1(i:i+1)='/R'
- if(i.ge.4 .and. ipa.eq.1 .and. i3.eq.2) call_1(i:i+1)='/P'
- endif
- if(index(call_2,'<').le.0) then
- i=index(call_2,' ')
- if(i.ge.4 .and. ipb.eq.1 .and. i3.eq.1) call_2(i:i+1)='/R'
- if(i.ge.4 .and. ipb.eq.1 .and. i3.eq.2) call_2(i:i+1)='/P'
- endif
- if(igrid4.le.MAXGRID4) then
- n=igrid4
- j1=n/(18*10*10)
- n=n-j1*18*10*10
- j2=n/(10*10)
- n=n-j2*10*10
- j3=n/10
- j4=n-j3*10
- grid4(1:1)=char(j1+ichar('A'))
- grid4(2:2)=char(j2+ichar('A'))
- grid4(3:3)=char(j3+ichar('0'))
- grid4(4:4)=char(j4+ichar('0'))
- if(ir.eq.0) msg=trim(call_1)//' '//trim(call_2)//' '//grid4
- if(ir.eq.1) msg=trim(call_1)//' '//trim(call_2)//' R '//grid4
- if(msg(1:3).eq.'CQ ' .and. ir.eq.1) unpk77_successvar=.false.
- else
- irpt=igrid4-MAXGRID4
- if(irpt.eq.1) msg=trim(call_1)//' '//trim(call_2)
- if(irpt.eq.2) msg=trim(call_1)//' '//trim(call_2)//' RRR'
- if(irpt.eq.3) msg=trim(call_1)//' '//trim(call_2)//' RR73'
- if(irpt.eq.4) msg=trim(call_1)//' '//trim(call_2)//' 73'
- if(irpt.ge.5) then
- write(crpt,'(i3.2)') irpt-35
- if(crpt(1:1).eq.' ') crpt(1:1)='+'
- if(ir.eq.0) msg=trim(call_1)//' '//trim(call_2)//' '//crpt
- if(ir.eq.1) msg=trim(call_1)//' '//trim(call_2)//' R'//crpt
- endif
- if(msg(1:3).eq.'CQ ' .and. irpt.ge.2) unpk77_successvar=.false.
- endif
-
- else if(i3.eq.4) then
- read(c77,1050) n12,n58,iflip,nrpt,icq
-1050 format(b12,b58,b1,b2,b1)
- if(icq.eq.1) then
- do i=11,1,-1
- j=mod(n58,38)+1
- c11(i:i)=c(j:j)
- n58=n58/38
- enddo
- call_2=adjustl(c11)//' '
- msg='CQ '//trim(call_2)
- if(msg(1:4).eq.'CQ <') unpk77_successvar=.false.
- else
- unpk77_successvar=.false.
- endif
- endif
-
- return
-end subroutine unpack77sdvar
-
-subroutine pack28var(c13,n28)
-
-! Pack a special token, a 22-bit hash code, or a valid base call into a 28-bit
-! integer.
-
- parameter (NTOKENS=2063592,MAX22=4194304)
- logical is_digit,is_letter
- character*13 c13
- character*6 callsign
- character*1 c
- character*4 c4
- character*37 a1
- character*36 a2
- character*10 a3
- character*27 a4
- data a1/' 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'/
- data a2/'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'/
- data a3/'0123456789'/
- data a4/' ABCDEFGHIJKLMNOPQRSTUVWXYZ'/
-
- is_digit(c)=c.ge.'0' .and. c.le.'9'
- is_letter(c)=c.ge.'A' .and. c.le.'Z'
-
- n28=-1
-! Work-around for Swaziland prefix:
- if(c13(1:4).eq.'3DA0') callsign='3D0'//c13(5:7)
-! Work-around for Guinea prefixes:
- if(c13(1:2).eq.'3X' .and. c13(3:3).ge.'A' .and. &
- c13(3:3).le.'Z') callsign='Q'//c13(3:6)
-
-! Check for special tokens first
- if(c13(1:3).eq.'DE ') then
- n28=0
- go to 900
- endif
-
- if(c13(1:4).eq.'QRZ ') then
- n28=1
- go to 900
- endif
-
- if(c13(1:3).eq.'CQ ') then
- n28=2
- go to 900
- endif
-
- if(c13(1:3).eq.'CQ_') then
- n=len(trim(c13))
- if(n.ge.4 .and. n.le.7) then
- nlet=0
- nnum=0
- do i=4,n
- c=c13(i:i)
- if(c.ge.'A' .and. c.le.'Z') nlet=nlet+1
- if(c.ge.'0' .and. c.le.'9') nnum=nnum+1
- enddo
- if(nnum.eq.3 .and. nlet.eq.0) then
- read(c13(4:3+nnum),*) nqsy
- n28=3+nqsy
- go to 900
- endif
- if(nlet.ge.1 .and. nlet.le.4 .and. nnum.eq.0) then
- c4=c13(4:n)
- c4=adjustr(c4)
- m=0
- do i=1,4
- j=0
- c=c4(i:i)
- if(c.ge.'A' .and. c.le.'Z') j=ichar(c)-ichar('A')+1
- m=27*m + j
- enddo
- n28=3+1000+m
- go to 900
- endif
- endif
- endif
-
-! Check for standard callsign
- iarea=-1
- n=len(trim(c13))
- do i=n,2,-1
- if(is_digit(c13(i:i))) exit
- enddo
- iarea=i !Call-area digit
- npdig=0 !Digits before call area
- nplet=0 !Letters before call area
- do i=1,iarea-1
- if(is_digit(c13(i:i))) npdig=npdig+1
- if(is_letter(c13(i:i))) nplet=nplet+1
- enddo
- nslet=0
- do i=iarea+1,n
- if(is_letter(c13(i:i))) nslet=nslet+1
- enddo
-
- n=len(trim(c13))
-! This is a standard callsign
- if(iarea.eq.2) callsign=' '//c13(1:5)
- if(iarea.eq.3) callsign=c13(1:6)
- i1=index(a1,callsign(1:1))-1
- i2=index(a2,callsign(2:2))-1
- i3=index(a3,callsign(3:3))-1
- i4=index(a4,callsign(4:4))-1
- i5=index(a4,callsign(5:5))-1
- i6=index(a4,callsign(6:6))-1
- n28=36*10*27*27*27*i1 + 10*27*27*27*i2 + 27*27*27*i3 + 27*27*i4 + &
- 27*i5 + i6
- n28=n28 + NTOKENS + MAX22
-
-900 n28=iand(n28,ishft(1,28)-1)
- return
-end subroutine pack28var
-
-
-subroutine unpack28var(n28_0,c13,success)
-
- parameter (NTOKENS=2063592,MAX22=4194304)
- logical success
- character*13 c13
- character*37 c1
- character*36 c2
- character*10 c3
- character*27 c4
- data c1/' 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'/
- data c2/'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'/
- data c3/'0123456789'/
- data c4/' ABCDEFGHIJKLMNOPQRSTUVWXYZ'/
-
- success=.true.
- n28=n28_0
- if(n28.lt.NTOKENS) then
-! Special tokens DE, QRZ, CQ, CQ_nnn, CQ_aaaa
- if(n28.eq.0) c13='DE '
- if(n28.eq.1) c13='QRZ '
- if(n28.eq.2) c13='CQ '
- if(n28.le.2) go to 900
- if(n28.le.1002) then
- write(c13,1002) n28-3
-1002 format('CQ_',i3.3)
- go to 900
- endif
- if(n28.le.532443) then
- n=n28-1003
- n0=n
- i1=n/(27*27*27)
- n=n-27*27*27*i1
- i2=n/(27*27)
- n=n-27*27*i2
- i3=n/27
- i4=n-27*i3
- c13=c4(i1+1:i1+1)//c4(i2+1:i2+1)//c4(i3+1:i3+1)//c4(i4+1:i4+1)
- c13=adjustl(c13)
- c13='CQ_'//c13(1:10)
- go to 900
- endif
- endif
- n28=n28-NTOKENS
-
-! Standard callsign
- n=n28 - MAX22
- i1=n/(36*10*27*27*27)
- n=n-36*10*27*27*27*i1
- i2=n/(10*27*27*27)
- n=n-10*27*27*27*i2
- i3=n/(27*27*27)
- n=n-27*27*27*i3
- i4=n/(27*27)
- n=n-27*27*i4
- i5=n/27
- i6=n-27*i5
- c13=c1(i1+1:i1+1)//c2(i2+1:i2+1)//c3(i3+1:i3+1)//c4(i4+1:i4+1)// &
- c4(i5+1:i5+1)//c4(i6+1:i6+1)
- c13=adjustl(c13)
-
-900 i0=index(c13,' ')
- if(i0.ne.0 .and. i0.lt.len(trim(c13))) then
- c13='QU1RK'
- success=.false.
- endif
- return
-end subroutine unpack28var
-
-subroutine split77var(msg,nwords,nw,w)
-
-! Convert msg to upper case; collapse multiple blanks; parse into words.
-
- character*37 msg
- character*13 w(19)
- character*1 c,c0
- character*6 bcall_1
- logical ok1
- integer nw(19)
-
- iz=len(trim(msg))
- j=0
- k=0
- n=0
- c0=' '
- w=' '
- do i=1,iz
- if(ichar(msg(i:i)).eq.0) msg(i:i)=' '
- c=msg(i:i) !Single character
- if(c.eq.' ' .and. c0.eq.' ') cycle !Skip leading/repeated blanks
- if(c.ne.' ' .and. c0.eq.' ') then
- k=k+1 !New word
- n=0
- endif
- j=j+1 !Index in msg
- n=n+1 !Index in word
- if(c.ge.'a' .and. c.le.'z') c=char(ichar(c)-32) !Force upper case
- msg(j:j)=c
- if(n.le.13) w(k)(n:n)=c !Copy character c into word
- c0=c
- enddo
- iz=j !Message length
- nwords=k !Number of words in msg
- if(nwords.le.0) go to 900
- nw(k)=len(trim(w(k)))
- msg(iz+1:)=' '
- if(nwords.lt.3) go to 900
- call chkcall(w(3),bcall_1,ok1)
- if(ok1 .and. w(1)(1:3).eq.'CQ ') then
- w(1)='CQ_'//w(2)(1:10) !Make "CQ " into "CQ_"
- w(2:12)=w(3:13) !Move all remeining words down by one
- nwords=nwords-1
- endif
-
-900 return
-end subroutine split77var
-
-subroutine pack77_1var(nwords,w,i3,n3,c77)
-! Check Type 1 (Standard 77-bit message) and Type 2 (ditto, with a "/P" call)
-
- parameter (MAXGRID4=32400)
- character*13 w(19),c13
- character*77 c77
- character*6 bcall_1,bcall_2
- character*4 grid4
- character c1*1,c2*2
- logical is_grid4
- logical ok1,ok2
- is_grid4(grid4)=len(trim(grid4)).eq.4 .and. &
- grid4(1:1).ge.'A' .and. grid4(1:1).le.'R' .and. &
- grid4(2:2).ge.'A' .and. grid4(2:2).le.'R' .and. &
- grid4(3:3).ge.'0' .and. grid4(3:3).le.'9' .and. &
- grid4(4:4).ge.'0' .and. grid4(4:4).le.'9'
-
- if(nwords.lt.2 .or. nwords.gt.4) return
- call chkcall(w(1),bcall_1,ok1)
- call chkcall(w(2),bcall_2,ok2)
- if(w(1)(1:3).eq.'DE ' .or. w(1)(1:3).eq.'CQ_' .or. w(1)(1:3).eq.'CQ ' .or. &
- w(1)(1:4).eq.'QRZ ') ok1=.true.
- if(w(1)(1:1).eq.'<' .and. index(w(1),'>').ge.5) ok1=.true.
- if(w(2)(1:1).eq.'<' .and. index(w(2),'>').ge.5) ok2=.true.
- if(.not.ok1 .or. .not.ok2) return
- if(w(1)(1:1).eq.'<' .and. index(w(2),'/').gt.0) return
- if(w(2)(1:1).eq.'<' .and. index(w(1),'/').gt.0) return
- if(nwords.eq.2 .and. (.not.ok2 .or. index(w(2),'/').ge.2)) return
- if(nwords.eq.2) go to 10
-
- c1=w(nwords)(1:1)
- c2=w(nwords)(1:2)
- if(.not.is_grid4(w(nwords)(1:4)) .and. c1.ne.'+' .and. c1.ne.'-' &
- .and. c2.ne.'R+' .and. c2.ne.'R-' .and. trim(w(nwords)).ne.'RRR' .and. &
- trim(w(nwords)).ne.'RR73' .and. trim(w(nwords)).ne.'73') return
- if(c1.eq.'+' .or. c1.eq.'-') then
- ir=0
- read(w(nwords),*,err=900) irpt
- irpt=irpt+35
- else if(c2.eq.'R+' .or. c2.eq.'R-') then
- ir=1
- read(w(nwords)(2:),*) irpt
- irpt=irpt+35
- else if(trim(w(nwords)).eq.'RRR') then
- ir=0
- irpt=2
- else if(trim(w(nwords)).eq.'RR73') then
- ir=0
- irpt=3
- else if(trim(w(nwords)).eq.'73') then
- ir=0
- irpt=4
- endif
-
-! 1 WA9XYZ/R KA1ABC/R R FN42 28 1 28 1 1 15 74 Standard msg
-! 2 PA3XYZ/P GM4ABC/P R JO22 28 1 28 1 1 15 74 EU VHF contest
-
-10 i1psuffix=index(w(1)//' ' ,'/P ')
- i2psuffix=index(w(2)//' ','/P ')
- if(nwords.eq.2 .or. nwords.eq.3 .or. (nwords.eq.4 .and. &
- w(3)(1:2).eq.'R ')) then
- n3=0
- i3=1 !Type 1: Standard message, possibly with "/R"
- if (i1psuffix.ge.4.or.i2psuffix.ge.4) i3=2 !Type 2, with "/P"
- endif
- c13=bcall_1
- if(c13(1:3).eq.'CQ_' .or. w(1)(1:1).eq.'<') c13=w(1)
- call pack28var(c13,n28avar)
- c13=bcall_2
- if(w(2)(1:1).eq.'<') c13=w(2)
- call pack28var(c13,n28bvar)
- ipa=0
- ipb=0
- if(i1psuffix.ge.4.or.index(w(1)//' ','/R ').ge.4) ipa=1
- if(i2psuffix.ge.4.or.index(w(2)//' ','/R ').ge.4) ipb=1
-
- grid4=w(nwords)(1:4)
- if(is_grid4(grid4)) then
- ir=0
- if(w(3).eq.'R ') ir=1
- j1=(ichar(grid4(1:1))-ichar('A'))*18*10*10
- j2=(ichar(grid4(2:2))-ichar('A'))*10*10
- j3=(ichar(grid4(3:3))-ichar('0'))*10
- j4=(ichar(grid4(4:4))-ichar('0'))
- igrid4=j1+j2+j3+j4
- else
- igrid4=MAXGRID4 + irpt
- endif
- if(nwords.eq.2) then
- ir=0
- irpt=1
- igrid4=MAXGRID4+irpt
- endif
- write(c77,1000) n28avar,ipa,n28bvar,ipb,ir,igrid4,i3
-1000 format(2(b28.28,b1),b1,b15.15,b3.3)
- return
-
-900 return
-end subroutine pack77_1var
-
-subroutine packtext77var(c13,c71)
-
- character*13 c13,w
- character*71 c71
- character*42 c
- character*1 qa(10),qb(10)
- data c/' 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ+-./?'/
-
- call mp_short_init
- qa=char(0)
- w=adjustr(c13)
- do i=1,13
- j=index(c,w(i:i))-1
- if(j.lt.0) j=0
- call mp_short_mult(qb,qa(2:10),9,42) !qb(1:9)=42*qa(2:9)
- call mp_short_add(qa,qb(2:10),9,j) !qa(1:9)=qb(2:9)+j
- enddo
-
- write(c71,1010) qa(2:10)
-1010 format(b7.7,8b8.8)
-
- return
-end subroutine packtext77var
-
-subroutine unpacktext77var(c71,c13)
-
- integer*1 ia(10)
- character*1 qa(10),qb(10)
- character*13 c13
- character*71 c71
- character*42 c
- equivalence (qa,ia),(qb,ib)
- data c/' 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ+-./?'/
-
- qa(1)=char(0)
- read(c71,1010) qa(2:10)
-1010 format(b7.7,8b8.8)
-
- do i=13,1,-1
- call mp_short_div(qb,qa(2:10),9,42,ir)
- c13(i:i)=c(ir+1:ir+1)
- qa(2:10)=qb(1:9)
- enddo
-
- return
-end subroutine unpacktext77var
-
-subroutine mp_short_opsvar(w,u)
- character*1 w(*),u(*)
- integer i,ireg,j,n,ir,iv,ii1,ii2
- character*1 creg(4)
- save ii1,ii2
- equivalence (ireg,creg)
-
- entry mp_short_init
- ireg=256*ichar('2')+ichar('1')
- do j=1,4
- if (creg(j).eq.'1') ii1=j
- if (creg(j).eq.'2') ii2=j
- enddo
- return
-
- entry mp_short_add(w,u,n,iv)
- ireg=256*iv
- do j=n,1,-1
- ireg=ichar(u(j))+ichar(creg(ii2))
- w(j+1)=creg(ii1)
- enddo
- w(1)=creg(ii2)
- return
-
- entry mp_short_mult(w,u,n,iv)
- ireg=0
- do j=n,1,-1
- ireg=ichar(u(j))*iv+ichar(creg(ii2))
- w(j+1)=creg(ii1)
- enddo
- w(1)=creg(ii2)
- return
-
- entry mp_short_div(w,u,n,iv,ir)
- ir=0
- do j=1,n
- i=256*ir+ichar(u(j))
- w(j)=char(i/iv)
- ir=mod(i,iv)
- enddo
- return
-
- return
-end subroutine mp_short_opsvar
-
-end module packjt77sdvar
diff --git a/lib/ft8var/subtractft8var.f90 b/lib/ft8var/subtractft8var.f90
index a15f9bfa..ae60652b 100644
--- a/lib/ft8var/subtractft8var.f90
+++ b/lib/ft8var/subtractft8var.f90
@@ -1,4 +1,4 @@
-subroutine subtractft8var(itone,f0,dt)
+subroutine subtractft8var(residual,itone,f0,dt,delta)
! Subtract an ft8 signal
!
@@ -7,20 +7,25 @@ subroutine subtractft8var(itone,f0,dt)
! Complex amp : cfilt(t) = LPF[ dd(t)*CONJG(cref(t)) ]
! Subtract : dd(t) = dd(t) - 2*REAL{cref*cfilt}
- use ft8_mod1, only : dd8,cw,NFILT1,NFILT2,endcorr
+ use ft8_mod1, only : cw,NFILT1,NFILT2,endcorr
+ use ft8_mtd_residual, only : mtd_start_sample
! NMAX=15*12000,NFFT=15*12000,NFRAME=1920*79
parameter (NFFT=180000,NMAX=180000,NFRAME=151680)
complex cref(nframe),cfilt(nmax)
- integer itone(79)
- save cfilt
- !$omp threadprivate(cfilt)
+ real, intent(inout) :: residual(NMAX)
+ real, intent(out), optional :: delta(NFRAME)
+ integer, intent(in) :: itone(79)
+ real, intent(in) :: f0,dt
+ save cref,cfilt
+ !$omp threadprivate(cref,cfilt)
- nstart=dt*12000+1
+ nstart=mtd_start_sample(dt)
+ if(present(delta)) delta=0.0
call gen_ft8wavevar(itone,79,1920,2.0,12000.0,f0,cref,xjunk,1,NFRAME)
do i=1,nframe
id=nstart-1+i
if(id.ge.1.and.id.le.NMAX) then
- cfilt(i)=dd8(id)*conjg(cref(i))
+ cfilt(i)=residual(id)*conjg(cref(i))
else
cfilt(i)=0.0
endif
@@ -33,9 +38,11 @@ subroutine subtractft8var(itone,f0,dt)
cfilt(nframe:nframe-NFILT1/2:-1)=cfilt(nframe:nframe-NFILT1/2:-1)*endcorr
do i=1,nframe
j=nstart+i-1
- if(j.ge.1 .and. j.le.NMAX) dd8(j)=dd8(j)-2*REAL(cfilt(i)*cref(i))
+ if(j.ge.1 .and. j.le.NMAX) then
+ correction=-2*REAL(cfilt(i)*cref(i))
+ residual(j)=residual(j)+correction
+ if(present(delta)) delta(i)=correction
+ endif
enddo
-!!!$omp flush(dd8) ! makes no difference in number of decoded messages
-
return
end subroutine subtractft8var
diff --git a/lib/ft8var/sync8dvar.f90 b/lib/ft8var/sync8dvar.f90
index 34874679..84b6507e 100644
--- a/lib/ft8var/sync8dvar.f90
+++ b/lib/ft8var/sync8dvar.f90
@@ -1,7 +1,8 @@
subroutine sync8dvar(cd0,i0,ctwk,itwk,sync,ipass,lastsync,iqso,lcq,lcallsstd,lcqcand)
! Compute sync power for a complex, downsampled FT8 signal.
- use ft8_mod1, only : csync,csynce,csyncsd,csyncsdcq,csynccq
+ use ft8_mod1, only : csync,csynce,csyncsd,csyncsdcq,csynccq, &
+ csyncsd_valid,csyncsdcq_valid
complex, intent(in) :: cd0(-800:4000),ctwk(32)
complex csync1(0:18,32),csync2(32),z1,z2,z3,z4,zt1(0:6),zt2(0:6),zt3(0:6),zt4(0:7),zt5(0:18), &
@@ -9,9 +10,10 @@ subroutine sync8dvar(cd0,i0,ctwk,itwk,sync,ipass,lastsync,iqso,lcq,lcallsstd,lcq
real sync1(0:20)!,sync2(0:20)
integer, intent(in) :: i0,ipass,iqso
logical(1), intent(in) :: lcq,lcallsstd,lcqcand
- logical(1) lastsync
+ logical(1) lastsync,lsync1_valid
- sync=0.; sync1=0.; zt1=0.; zt2=0.; zt3=0.; z11=0.; z22=0.; z33=0.!; sync2=0.
+ sync=0.; sync1=0.; zt1=0.; zt2=0.; zt3=0.; z4=0.; z11=0.; z22=0.; z33=0.!; sync2=0.
+ lsync1_valid=.false.
k=1
do i=0,6 ! Sum over 7 Costas frequencies and three Costas arrays
i1=i0+i*32; i2=i1+1152; i3=i1+2304 ! +36*32, +72*32
@@ -83,9 +85,15 @@ subroutine sync8dvar(cd0,i0,ctwk,itwk,sync,ipass,lastsync,iqso,lcq,lcallsstd,lcq
endif
if(.not.lastsync) then
- if(iqso.gt.1 .and. iqso.lt.4 .and. lcallsstd) csync1=csynce; if(iqso.eq.4 .and. .not.lcq) csync1=csyncsd
+ if(iqso.gt.1 .and. iqso.lt.4 .and. lcallsstd) then
+ csync1=csynce
+ lsync1_valid=.true.
+ else if(iqso.eq.4 .and. .not.lcq .and. csyncsd_valid) then
+ csync1=csyncsd
+ lsync1_valid=.true.
+ endif
- if((iqso.eq.4 .and. .not.lcq) .or. ((iqso.eq.2 .or. iqso.eq.3) .and. lcallsstd)) then
+ if(lsync1_valid) then
zt5=0.
do i=0,18
csync2=csync1(i,1:32)
@@ -105,7 +113,7 @@ subroutine sync8dvar(cd0,i0,ctwk,itwk,sync,ipass,lastsync,iqso,lcq,lcallsstd,lcq
enddo
endif
- if(iqso.eq.4 .and. lcq) then
+ if(iqso.eq.4 .and. lcq .and. csyncsdcq_valid) then
do i=0,57
csync2=csyncsdcq(i,1:32)
if(itwk.eq.1) csync2=ctwk*csync2 !Tweak the frequency
diff --git a/lib/ft8var/sync8var.f90 b/lib/ft8var/sync8var.f90
index 6540d766..17b2b894 100644
--- a/lib/ft8var/sync8var.f90
+++ b/lib/ft8var/sync8var.f90
@@ -1,11 +1,18 @@
-subroutine sync8var(nfa,nfb,syncmin,nfqso,candidate,ncand,jzb,jzt,ipass,lqsothread,ncandthin,ndtcenter)
+subroutine sync8var(residual,nfa,nfb,syncmin,nfqso,candidate,ncand,jzb,jzt,ipass, &
+ lqsothread,ncandthin,ndtcenter,progress_generation)
- use ft8_mod1, only : dd8,windowx,facx,icos7,lagcc,lagccbail,nfawide,nfbwide
+ use ft8_mod1, only : windowx,facx,icos7,lagcc,lagccbail,nfawide,nfbwide
+ use decode_completion_module, only : write_decode_progress
+ real, intent(in) :: residual(180000)
include 'ft8_params.f90'
complex cx(0:NH1)
- real s(NH1,NHSYM),x(NFFT1),sync2d(NH1,jzb:jzt),red(NH1),candidate0(5,450),candidate(4,460),tall(30),freq,rcandthin,dtcenter
+ real, save :: s(NH1,NHSYM)
+ !$omp threadprivate(s)
+ real x(NFFT1),sync2d(NH1,jzb:jzt),red(NH1),candidate0(5,450),candidate(4,460),tall(30),freq,rcandthin,dtcenter
+ real candidate_sync(450)
integer jpeak(NH1),indx(NH1),ii(1)
- integer, intent(in) :: nfa,nfb,nfqso,jzb,jzt,ipass,ncandthin,ndtcenter
+ integer, parameter :: max_sync_stencil=16
+ integer, intent(in) :: nfa,nfb,nfqso,jzb,jzt,ipass,ncandthin,ndtcenter,progress_generation
logical(1) syncq(NH1,jzb:jzt),redcq(NH1),lcq,lcq2,lpass1,lpass2
logical(1), intent(in) :: lqsothread
equivalence (x,cx)
@@ -14,22 +21,26 @@ subroutine sync8var(nfa,nfb,syncmin,nfqso,candidate,ncand,jzb,jzt,ipass,lqsothre
tstep=0.04 ! NSTEP/12000.0
df=3.125 ! 12000.0/NFFT1 , Hz
syncq=.false.; redcq=.false.; candidate(4,:)=0.
+ ncand=0
rcandthin=ncandthin/100.;
dtcenter=ndtcenter/100.
+ if(nfa.gt.nfb .or. nfawide.gt.nfbwide) return
+
if(ipass.eq.1 .or. ipass.eq.4 .or. ipass.eq.7) then
do j=1,NHSYM
ia=(j-1)*NSTEP + 1
ib=ia+NSPS-1
x(1:759)=0.
- if(j.ne.1) then; x(760:960)=dd8(ia-201:ia-1)*windowx(200:0:-1); else; x(760:960)=0.; endif
- x(961:2880)=facx*dd8(ia:ib); x(961)=x(961)*1.9; x(2880)=x(2880)*1.9
- if(j.ne.NHSYM) then; x(2881:3081)=dd8(ib+1:ib+201)*windowx; else; x(2881:3081)=0.; endif
+ if(j.ne.1) then; x(760:960)=residual(ia-201:ia-1)*windowx(200:0:-1); else; x(760:960)=0.; endif
+ x(961:2880)=facx*residual(ia:ib); x(961)=x(961)*1.9; x(2880)=x(2880)*1.9
+ if(j.ne.NHSYM) then; x(2881:3081)=residual(ib+1:ib+201)*windowx; else; x(2881:3081)=0.; endif
x(3082:)=0.
call four2avar(cx,NFFT1,1,-1,0) !r2c FFT
do i=1,NH1
s(i,j)=SQRT(real(cx(i))**2 + aimag(cx(i))**2)
enddo
+ if(mod(j,16).eq.0) call write_decode_progress(progress_generation)
enddo
endif
if(ipass.eq.2 .or. ipass.eq.5 .or. ipass.eq.8) then
@@ -37,14 +48,15 @@ subroutine sync8var(nfa,nfb,syncmin,nfqso,candidate,ncand,jzb,jzt,ipass,lqsothre
ia=(j-1)*NSTEP + 1
ib=ia+NSPS-1
x(1:759)=0.
- if(j.ne.1) then; x(760:960)=dd8(ia-201:ia-1)*windowx(200:0:-1); else; x(760:960)=0.; endif
- x(961:2880)=facx*dd8(ia:ib); x(961)=x(961)*1.9; x(2880)=x(2880)*1.9
- if(j.ne.NHSYM) then; x(2881:3081)=dd8(ib+1:ib+201)*windowx; else; x(2881:3081)=0.; endif
+ if(j.ne.1) then; x(760:960)=residual(ia-201:ia-1)*windowx(200:0:-1); else; x(760:960)=0.; endif
+ x(961:2880)=facx*residual(ia:ib); x(961)=x(961)*1.9; x(2880)=x(2880)*1.9
+ if(j.ne.NHSYM) then; x(2881:3081)=residual(ib+1:ib+201)*windowx; else; x(2881:3081)=0.; endif
x(3082:)=0.
call four2avar(cx,NFFT1,1,-1,0) !r2c FFT
do i=1,NH1
s(i,j)=real(cx(i))**2 + aimag(cx(i))**2
enddo
+ if(mod(j,16).eq.0) call write_decode_progress(progress_generation)
enddo
endif
if(ipass.eq.3 .or. ipass.eq.6 .or. ipass.eq.9) then
@@ -52,18 +64,25 @@ subroutine sync8var(nfa,nfb,syncmin,nfqso,candidate,ncand,jzb,jzt,ipass,lqsothre
ia=(j-1)*NSTEP + 1
ib=ia+NSPS-1
x(1:759)=0.
- if(j.ne.1) then; x(760:960)=dd8(ia-201:ia-1)*windowx(200:0:-1); else; x(760:960)=0.; endif
- x(961:2880)=facx*dd8(ia:ib); x(961)=x(961)*1.9; x(2880)=x(2880)*1.9
- if(j.ne.NHSYM) then; x(2881:3081)=dd8(ib+1:ib+201)*windowx; else; x(2881:3081)=0.; endif
+ if(j.ne.1) then; x(760:960)=residual(ia-201:ia-1)*windowx(200:0:-1); else; x(760:960)=0.; endif
+ x(961:2880)=facx*residual(ia:ib); x(961)=x(961)*1.9; x(2880)=x(2880)*1.9
+ if(j.ne.NHSYM) then; x(2881:3081)=residual(ib+1:ib+201)*windowx; else; x(2881:3081)=0.; endif
x(3082:)=0.
call four2avar(cx,NFFT1,1,-1,0) !r2c FFT
do i=1,NH1
s(i,j)=abs(real(cx(i))) + abs(aimag(cx(i)))
enddo
+ if(mod(j,16).eq.0) call write_decode_progress(progress_generation)
enddo
endif
- ia=max(1,nint(nfa/df)); ib=max(1,nint(nfb/df)); iaw=max(1,nint(nfawide/df)); ibw=max(1,nint(nfbwide/df))
+ ia=max(1,nint(nfa/df))
+ ib=min(NH1-max_sync_stencil,nint(nfb/df))
+ iaw=max(1,nint(nfawide/df))
+ ibw=min(NH1-max_sync_stencil,nint(nfbwide/df))
+ ia=max(ia,iaw)
+ ib=min(ib,ibw)
+ if(ia.gt.ib .or. iaw.gt.ibw) return
nssy=4 ! NSPS/NSTEP ! # steps per symbol
nssy36=144 ! nssy*36
nssy72=288 ! nssy*72
@@ -74,7 +93,7 @@ subroutine sync8var(nfa,nfb,syncmin,nfqso,candidate,ncand,jzb,jzt,ipass,lqsothre
nfos6=12 ! nfos*6
do j=jzb,jzt
do i=iaw,ibw
- ta=0.; tb=0.; tc=0.
+ ta=0.; tb=0.; tc=0.; tall=0.
do n=0,6
k=j+jstrt+nssy*n
if(k.gt.0) then
@@ -112,10 +131,11 @@ subroutine sync8var(nfa,nfb,syncmin,nfqso,candidate,ncand,jzb,jzt,ipass,lqsothre
endif
sync2d(i,j)=max(sync_abc,sync_bc); if(lcq) syncq(i,j)=.true.
enddo
+ if(mod(j-jzb+1,16).eq.0) call write_decode_progress(progress_generation)
enddo
else
! nfos6=15 ! 16i spec bw -1
- nfos6=16
+ nfos6=max_sync_stencil
do j=jzb,jzt
do i=iaw,ibw
ta=0.; tb=0.; tc=0.; tcq=0.; t0a=0.; t0b=0.; t0c=0.; t0cq=0.
@@ -151,6 +171,7 @@ subroutine sync8var(nfa,nfb,syncmin,nfqso,candidate,ncand,jzb,jzt,ipass,lqsothre
sync2d(i,j)=max(syncf,syncs)
if(syncf.gt.syncs) then; if(lcq) syncq(i,j)=.true.; else; if(lcq2) syncq(i,j)=.true.; endif
enddo
+ if(mod(j-jzb+1,16).eq.0) call write_decode_progress(progress_generation)
enddo
endif
@@ -226,10 +247,11 @@ subroutine sync8var(nfa,nfb,syncmin,nfqso,candidate,ncand,jzb,jzt,ipass,lqsothre
! Sort by sync
! call indexx(candidate0(3,1:ncand),ncand,indx)
- if(rcandthin.gt.0.99) then; call indexx(candidate0(3,1:ncand),ncand,indx)
+ if(rcandthin.gt.0.99) then; candidate_sync(1:ncand)=candidate0(3,1:ncand)
! sort by sync value with DT weight
- else; call indexx(candidate0(5,1:ncand),ncand,indx)
+ else; candidate_sync(1:ncand)=candidate0(5,1:ncand)
endif
+ call indexx(candidate_sync,ncand,indx)
! Sort by frequency
! call indexx(candidate0(1,1:ncand),ncand,indx)
diff --git a/lib/ft8var/tone8.f90 b/lib/ft8var/tone8.f90
index d5a95761..63e21e94 100644
--- a/lib/ft8var/tone8.f90
+++ b/lib/ft8var/tone8.f90
@@ -1,13 +1,15 @@
subroutine tone8(lmycallstd,lhiscallstd)
use ft8_mod1, only : itone56,idtone56,msg,csynce,mycall,hiscall,idtonecqdxcns,idtonedxcns73,mybcall,hisbcall,lhound, &
+ idtone56_valid, &
idtonefox73,idtonespec
- complex csig0(151680)
+ complex, allocatable :: csig0(:)
character msg37*37,msgsent37*37,mycall14*14,hiscall14*14
character*4 rpt(56)
integer itone(79),itone1(79)
integer*1 msgbits(77)
logical(1), intent(in) :: lmycallstd,lhiscallstd
+ logical(1) valid_first
data rpt/'-01 ','-02 ','-03 ','-04 ','-05 ','-06 ','-07 ','-08 ','-09 ','-10 ', &
'-11 ','-12 ','-13 ','-14 ','-15 ','-16 ','-17 ','-18 ','-19 ','-20 ', &
@@ -20,6 +22,11 @@ subroutine tone8(lmycallstd,lhiscallstd)
! integer itone56(56,79),idtone56(56,58)
! character*37 msg(56)
+ idtone56(1:56,1:58)=0
+ itone56(1:56,1:79)=0
+ idtone56_valid(1:56)=.false.
+ valid_first=.false.
+
if(lhound .and. len_trim(mybcall).gt.2 .and. len_trim(hisbcall).gt.2) then
msg37=''; msg37=trim(mybcall)//' '//trim(hisbcall)//' RR73'
i3=-1; n3=-1
@@ -58,10 +65,7 @@ subroutine tone8(lmycallstd,lhiscallstd)
msg(i)=msg37
i3=-1; n3=-1
call genft8var(msg37,i3,n3,0,msgsent37,msgbits,itone)
- if(i.eq.1) itone1=itone
- idtone56(i,1:29)=itone(8:36)
- idtone56(i,30:58)=itone(44:72)
- itone56(i,1:79)=itone(1:79)
+ call store_tone_slot(i,itone,i3.ge.0,i.eq.1)
enddo
go to 2
endif
@@ -71,10 +75,7 @@ subroutine tone8(lmycallstd,lhiscallstd)
msg37=''; msg37=trim(mycall)//' '//trim(hiscall14)//' '//trim(rpt(i))
i3=-1; n3=-1
call genft8var(msg37,i3,n3,0,msgsent37,msgbits,itone)
- if(i.eq.1) itone1=itone
- idtone56(i,1:29)=itone(8:36)
- idtone56(i,30:58)=itone(44:72)
- itone56(i,1:79)=itone(1:79)
+ call store_tone_slot(i,itone,i3.ge.0,i.eq.1)
msg37=''; msg37=trim(mycall)//' '//trim(hiscall)//' '//trim(rpt(i))
msg(i)=msg37
enddo
@@ -82,9 +83,7 @@ subroutine tone8(lmycallstd,lhiscallstd)
msg37=''; msg37=trim(mycall14)//' '//trim(hiscall)//' '//trim(rpt(i))
i3=-1; n3=-1
call genft8var(msg37,i3,n3,0,msgsent37,msgbits,itone)
- idtone56(i,1:29)=itone(8:36)
- idtone56(i,30:58)=itone(44:72)
- itone56(i,1:79)=itone(1:79)
+ call store_tone_slot(i,itone,i3.ge.0,.false.)
msg37=''; msg37=trim(mycall)//' '//trim(hiscall)//' '//trim(rpt(i))
msg(i)=msg37
enddo
@@ -92,9 +91,7 @@ subroutine tone8(lmycallstd,lhiscallstd)
msg(53)=msg37
i3=-1; n3=-1
call genft8var(msg37,i3,n3,0,msgsent37,msgbits,itone)
- idtone56(53,1:29)=itone(8:36)
- idtone56(53,30:58)=itone(44:72)
- itone56(53,1:79)=itone(1:79)
+ call store_tone_slot(53,itone,i3.ge.0,.false.)
go to 2
endif
@@ -103,10 +100,7 @@ subroutine tone8(lmycallstd,lhiscallstd)
msg37=''; msg37=trim(mycall14)//' '//trim(hiscall)//' '//trim(rpt(i))
i3=-1; n3=-1
call genft8var(msg37,i3,n3,0,msgsent37,msgbits,itone)
- if(i.eq.1) itone1=itone
- idtone56(i,1:29)=itone(8:36)
- idtone56(i,30:58)=itone(44:72)
- itone56(i,1:79)=itone(1:79)
+ call store_tone_slot(i,itone,i3.ge.0,i.eq.1)
msg37=''; msg37=trim(mycall)//' '//trim(hiscall)//' '//trim(rpt(i))
msg(i)=msg37
enddo
@@ -114,9 +108,7 @@ subroutine tone8(lmycallstd,lhiscallstd)
msg37=''; msg37=trim(mycall)//' '//trim(hiscall14)//' '//trim(rpt(i))
i3=-1; n3=-1
call genft8var(msg37,i3,n3,0,msgsent37,msgbits,itone)
- idtone56(i,1:29)=itone(8:36)
- idtone56(i,30:58)=itone(44:72)
- itone56(i,1:79)=itone(1:79)
+ call store_tone_slot(i,itone,i3.ge.0,.false.)
msg37=''; msg37=trim(mycall)//' '//trim(hiscall)//' '//trim(rpt(i))
msg(i)=msg37
enddo
@@ -124,17 +116,37 @@ subroutine tone8(lmycallstd,lhiscallstd)
msg(53)=msg37
i3=-1; n3=-1
call genft8var(msg37,i3,n3,0,msgsent37,msgbits,itone)
- idtone56(53,1:29)=itone(8:36)
- idtone56(53,30:58)=itone(44:72)
- itone56(53,1:79)=itone(1:79)
+ call store_tone_slot(53,itone,i3.ge.0,.false.)
go to 2
endif
-2 m=13441 ! 7*1920+1
+2 if(.not.valid_first) return
+ allocate(csig0(151680))
+ m=13441 ! 7*1920+1
call gen_ft8wavevar(itone1,79,1920,2.0,12000.0,0.0,csig0,xjunk,1,151680)
do j=0,18
do k=1,32; csynce(j,k)=csig0(m); m=m+60; enddo
enddo
return
+
+contains
+
+ subroutine store_tone_slot(islot,itone,valid,set_first)
+ integer, intent(in) :: islot,itone(79)
+ logical, intent(in) :: valid,set_first
+
+ ! Invalid generated messages leave the slot cleared/invalid; valid_first
+ ! prevents csynce from being regenerated from a stale first tone sequence.
+ if(.not.valid) return
+ if(set_first) then
+ itone1=itone
+ valid_first=.true.
+ endif
+ idtone56(islot,1:29)=itone(8:36)
+ idtone56(islot,30:58)=itone(44:72)
+ itone56(islot,1:79)=itone(1:79)
+ idtone56_valid(islot)=.true.
+ end subroutine store_tone_slot
+
end subroutine tone8
diff --git a/lib/ft8var/tonesdvar.f90 b/lib/ft8var/tonesdvar.f90
index b973ca77..50d3cb00 100644
--- a/lib/ft8var/tonesdvar.f90
+++ b/lib/ft8var/tonesdvar.f90
@@ -1,14 +1,15 @@
subroutine tonesdvar(msgd,lcq)
- use ft8_mod1, only : csyncsd,csyncsdcq,itone76,idtone76,msgsd76
- complex csig0(151680)
+ use ft8_mod1, only : csyncsd,csyncsdcq,itone76,idtone76,msgsd76, &
+ idtone76_valid,csyncsd_valid,csyncsdcq_valid
+ complex, allocatable :: csig0(:)
character, intent(in) :: msgd*37
character msg37*37,msgsent37*37,c1*12,c2*12,grid*6
character*4 rpt(75)
integer itone(79),itone1(79)
integer*1 msgbits(77)
logical(1), intent(in) :: lcq
- logical(1) lgrid,lr73
+ logical(1) lgrid,lr73,valid_first
data rpt/'+09 ','+08 ','+07 ','+06 ','+05 ','+04 ','+03 ','+02 ','+01 ','+00 ', &
'-01 ','-02 ','-03 ','-04 ','-05 ','-06 ','-07 ','-08 ','-09 ','-10 ', &
@@ -25,11 +26,21 @@ subroutine tonesdvar(msgd,lcq)
! complex csyncsd(0:18,32),csyncsdcq(0:71,32)
lgrid=.false.; lr73=.false.
+ valid_first=.false.
+ idtone76(1:76,1:58)=0
+ itone76(1:76,1:79)=0
+ idtone76_valid(1:76)=.false.
+ if(lcq) then
+ csyncsdcq_valid=.false.
+ else
+ csyncsd_valid=.false.
+ endif
if(lcq) then
msg37=msgd
i3=-1; n3=-1
call genft8sdvar(msg37,i3,n3,msgsent37,msgbits,itone)
+ if(i3.lt.0) return
else
c1=' '; c2=' '
ispc1=index(msgd,' '); ispc2=index(msgd((ispc1+1):),' ')+ispc1; ispc3=index(msgd((ispc2+1):),' ')+ispc2;
@@ -48,21 +59,31 @@ subroutine tonesdvar(msgd,lcq)
msgsd76(i)=msg37
i3=-1; n3=-1
call genft8sdvar(msg37,i3,n3,msgsent37,msgbits,itone)
- if(i.eq.1) itone1=itone
+ if(i3.lt.0) cycle
+ if(i.eq.1) then
+ itone1=itone
+ valid_first=.true.
+ endif
idtone76(i,1:29)=itone(8:36)
idtone76(i,30:58)=itone(44:72)
itone76(i,1:79)=itone(1:79)
+ idtone76_valid(i)=.true.
enddo
msg37=' '
msg37=trim(c1)//' '//trim(c2)//' '//trim(grid)
msgsd76(76)=msg37
i3=-1; n3=-1
call genft8sdvar(msg37,i3,n3,msgsent37,msgbits,itone)
- idtone76(76,1:29)=itone(8:36)
- idtone76(76,30:58)=itone(44:72)
- itone76(76,1:79)=itone(1:79)
+ if(i3.ge.0) then
+ idtone76(76,1:29)=itone(8:36)
+ idtone76(76,30:58)=itone(44:72)
+ itone76(76,1:79)=itone(1:79)
+ idtone76_valid(76)=.true.
+ endif
endif
+ if(.not.lcq .and. .not.valid_first) return
+ allocate(csig0(151680))
m=13441 ! 7*1920+1
if(lcq) then
call gen_ft8wavevar(itone,79,1920,2.0,12000.0,0.0,csig0,xjunk,1,151680)
@@ -70,11 +91,13 @@ subroutine tonesdvar(msgd,lcq)
if(i.eq.29) m=m+13440
do j=1,32; csyncsdcq(i,j)=csig0(m); m=m+60; enddo
enddo
+ csyncsdcq_valid=.true.
else
call gen_ft8wavevar(itone1,79,1920,2.0,12000.0,0.0,csig0,xjunk,1,151680)
do i=0,18
do j=1,32; csyncsd(i,j)=csig0(m); m=m+60; enddo
enddo
+ csyncsd_valid=.true.
endif
return
diff --git a/lib/gen_cw_wave.f90 b/lib/gen_cw_wave.f90
index cf6d6d98..1698af67 100644
--- a/lib/gen_cw_wave.f90
+++ b/lib/gen_cw_wave.f90
@@ -11,6 +11,7 @@ subroutine gen_cw_wave(message,ifreq,wave)
real x(NMAX)
real y(NMAX)
+ wave=0.
call morse(message,icw,ncw)
i1=0
diff --git a/lib/genmsk_128_90.f90 b/lib/genmsk_128_90.f90
index 6e35d725..90b5078c 100644
--- a/lib/genmsk_128_90.f90
+++ b/lib/genmsk_128_90.f90
@@ -81,10 +81,13 @@ subroutine genmsk_128_90(msg0,ichk,msgsent,i4tone,itype)
i3=-1
n3=-1
- call pack77(message,i3,n3,c77)
+ c77=' '
+ unpk77_success=.false.
+ call pack77_legacy_truncating_fallback(message,i3,n3,c77)
+ if(i3.lt.0 .or. n3.lt.0) go to 998
call unpack77(c77,0,msgsent,unpk77_success) !Unpack to get msgsent
if(ichk.eq.1) go to 999
- read(c77,"(77i1)") msgbits
+ read(c77,"(77i1)",err=998) msgbits
call encode_128_90(msgbits,codeword)
!Create 144-bit channel vector:
@@ -116,5 +119,11 @@ subroutine genmsk_128_90(msg0,ichk,msgsent,i4tone,itype)
! Flip polarity
i4tone=-i4tone+1
+ go to 999
+998 msgbits=0
+ bitseq=0
+ i4tone=0
+ msgsent='*** bad message *** '
+ itype=-1
999 return
end subroutine genmsk_128_90
diff --git a/lib/get_q3list.f90 b/lib/get_q3list.f90
index a6b6de81..d9b66e2d 100644
--- a/lib/get_q3list.f90
+++ b/lib/get_q3list.f90
@@ -1,5 +1,8 @@
subroutine get_q3list(fname,bDiskData,nlist,list)
+ use jpl_ephemeris_status, only: EPHEMERIS_INVALID_INPUT, &
+ EPHEMERIS_UNAVAILABLE
+
type q3list
character*6 call
character*4 grid
@@ -8,13 +11,15 @@ subroutine get_q3list(fname,bDiskData,nlist,list)
integer moonel
end type q3list
- parameter (MAX_CALLERS=40)
+ parameter (MAX_CALLERS=50)
character*(*) fname
- character*36 list(40)
+ character*37 list(MAX_CALLERS)
character*8 grid6
logical*1 bDiskData
integer time
integer nt(8)
+ integer utc_year,utc_month,utc_day
+ integer ephemeris_result
integer indx(MAX_CALLERS)
type(q3list) ctmp(MAX_CALLERS),callers(MAX_CALLERS)
character*256 jpleph_file_name,file24name
@@ -24,7 +29,7 @@ subroutine get_q3list(fname,bDiskData,nlist,list)
nhist2=0
open(24,file=fname,status='unknown',form='unformatted')
read(24,end=1) nhist2
- if(nhist2.ge.1 .and. nhist2.le.40) then
+ if(nhist2.ge.1 .and. nhist2.le.MAX_CALLERS) then
read(24,end=1) ctmp(1:nhist2)
else
nhist2=0
@@ -34,7 +39,7 @@ subroutine get_q3list(fname,bDiskData,nlist,list)
now=time()
call date_and_time(values=nt)
- uth=nt(5) + (nt(6)-nt(4))/60.0 + nt(7)/3600.0
+ call normalize_utc_calendar(nt,utc_year,utc_month,utc_day,uth)
j=0
do i=1,nhist2
@@ -42,10 +47,13 @@ subroutine get_q3list(fname,bDiskData,nlist,list)
if(age.gt.24.0) cycle
grid6=ctmp(i)%grid//'mm'
call grid2deg(grid6,xlon,xlat)
- call sun(nt(1),nt(2),nt(3),uth,-xlon,xlat,RASun,DecSun,xLST, &
- AzSun,ElSun,mjd,day)
- call moondopjpl(nt(1),nt(2),nt(3),uth,-xlon,xlat,RAMoon,DecMoon, &
- xLST,HA,AzMoon,ElMoon,vr,techo)
+ call sun(utc_year,utc_month,utc_day,uth,-xlon,xlat,RASun,DecSun, &
+ xLST,AzSun,ElSun,mjd,day)
+ call moondopjpl(utc_year,utc_month,utc_day,uth,-xlon,xlat,RAMoon, &
+ DecMoon, &
+ xLST,HA,AzMoon,ElMoon,vr,techo,ephemeris_result)
+ if(ephemeris_result.eq.EPHEMERIS_INVALID_INPUT .or. &
+ ephemeris_result.eq.EPHEMERIS_UNAVAILABLE) cycle
if(ElMoon.lt.-5.0 .and. (.not.bDiskData)) cycle
j=j+1 !Keep this one...
callers(j)=ctmp(i)
@@ -63,7 +71,7 @@ subroutine get_q3list(fname,bDiskData,nlist,list)
age=(now - callers(j)%nsec)/3600.0
write(list(i),1000) i,callers(j)%nfreq,callers(j)%call, &
callers(j)%grid,callers(j)%moonel,age,char(0)
-1000 format(i2,'.',i6,2x,a6,2x,a4,i5,f7.1,a1)
+1000 format(i2,'.',i6,2x,a6,2x,a4,i5,f7.1,1x,a1)
! h1=mod(now,86400)/3600.0
! h2=mod(callers(i)%nsec,86400)/3600.0
@@ -81,9 +89,70 @@ subroutine get_q3list(fname,bDiskData,nlist,list)
return
end subroutine get_q3list
+subroutine normalize_utc_calendar(values,year,month,day,uth)
+
+ implicit none
+
+ integer, intent(in) :: values(8)
+ integer, intent(out) :: year,month,day
+ real, intent(out) :: uth
+ real :: utc_seconds
+
+ year=values(1)
+ month=values(2)
+ day=values(3)
+ utc_seconds=3600.0*values(5) + 60.0*values(6) + values(7) + &
+ 0.001*values(8) - 60.0*values(4)
+
+ if(utc_seconds.lt.0.0) then
+ utc_seconds=utc_seconds + 86400.0
+ day=day - 1
+ if(day.lt.1) then
+ month=month - 1
+ if(month.lt.1) then
+ year=year - 1
+ month=12
+ endif
+ day=days_in_month(year,month)
+ endif
+ else if(utc_seconds.ge.86400.0) then
+ utc_seconds=utc_seconds - 86400.0
+ day=day + 1
+ if(day.gt.days_in_month(year,month)) then
+ day=1
+ month=month + 1
+ if(month.gt.12) then
+ year=year + 1
+ month=1
+ endif
+ endif
+ endif
+ uth=utc_seconds/3600.0
+
+contains
+
+ integer function days_in_month(calendar_year,calendar_month)
+ integer, intent(in) :: calendar_year,calendar_month
+ logical :: leap_year
+
+ select case(calendar_month)
+ case(4,6,9,11)
+ days_in_month=30
+ case(2)
+ leap_year=mod(calendar_year,400).eq.0 .or. &
+ (mod(calendar_year,4).eq.0 .and. mod(calendar_year,100).ne.0)
+ days_in_month=28
+ if(leap_year) days_in_month=29
+ case default
+ days_in_month=31
+ end select
+ end function days_in_month
+
+end subroutine normalize_utc_calendar
+
subroutine rm_q3list(dxcall0)
- parameter (MAX_CALLERS=40)
+ parameter (MAX_CALLERS=50)
type q3list
character*6 call
character*4 grid
@@ -125,8 +194,16 @@ subroutine rm_q3list(dxcall0)
end subroutine rm_q3list
subroutine jpl_setup(fname)
+ use jpl_ephemeris_status, only: reset_jpl_reader
character*256 fname,jpleph_file_name
common/jplcom/jpleph_file_name
- jpleph_file_name=fname
+ j = index(fname,char(0))
+ if(j.eq.0) then
+ jpleph_file_name=fname
+ else
+ jpleph_file_name(1:j)=fname(1:j)
+ jpleph_file_name(j:)=' '
+ endif
+ call reset_jpl_reader()
return
end subroutine jpl_setup
diff --git a/lib/ft2/gfsk_pulse.f90 b/lib/gfsk_pulse.f90
index 99ab78e3..99ab78e3 100644
--- a/lib/ft2/gfsk_pulse.f90
+++ b/lib/gfsk_pulse.f90
diff --git a/lib/hspec.f90 b/lib/hspec.f90
index 216f2ddf..9db613cb 100644
--- a/lib/hspec.f90
+++ b/lib/hspec.f90
@@ -96,7 +96,8 @@ subroutine hspec(id2,k,nutc0,ntrpdepth,nrxfreq,ntol,bmsk144, &
k0=k-3584
tt2=sum(float(abs(id2(k0:k0+3583))))
if(tt1.ne.0.0 .and. tt2.ne.0) then
- call mskrtd(id2(k-7168+1:k),nutc0,tsec,ntol,nrxfreq,ndepth, &
+! k is the end-exclusive count supplied by the audio producer.
+ call mskrtd(id2(k-7168:k-1),nutc0,tsec,ntol,nrxfreq,ndepth, &
mycall,hiscall,bshmsg,btrain,pcoeffs,bswl,datadir,line0)
if(line0(1:1).eq.char(0)) then
line1(1:1)=char(0)
diff --git a/lib/jpl_ephemeris_status.f90 b/lib/jpl_ephemeris_status.f90
new file mode 100644
index 00000000..0d15cdc8
--- /dev/null
+++ b/lib/jpl_ephemeris_status.f90
@@ -0,0 +1,29 @@
+module jpl_ephemeris_status
+ implicit none
+
+ integer, parameter :: JPL_STATUS_OK = 0
+ integer, parameter :: JPL_STATUS_IO_ERROR = 1
+ integer, parameter :: JPL_STATUS_INVALID_HEADER = 2
+ integer, parameter :: JPL_STATUS_OUT_OF_RANGE = 3
+ integer, parameter :: JPL_STATUS_NOT_AVAILABLE = 4
+ integer, parameter :: JPL_STATUS_INVALID_REQUEST = 5
+
+ integer, parameter :: EPHEMERIS_JPL = 0
+ integer, parameter :: EPHEMERIS_ANALYTIC_FALLBACK = 1
+ integer, parameter :: EPHEMERIS_INVALID_INPUT = 2
+ integer, parameter :: EPHEMERIS_UNAVAILABLE = 3
+
+ integer, save :: configuration_generation = 0
+ integer, save :: jpl_reader_generation = 0
+
+contains
+
+ subroutine reset_jpl_reader()
+ configuration_generation = configuration_generation + 1
+ end subroutine reset_jpl_reader
+
+ subroutine note_jpl_reader_change()
+ jpl_reader_generation = jpl_reader_generation + 1
+ end subroutine note_jpl_reader_change
+
+end module jpl_ephemeris_status
diff --git a/lib/jplsubs.f b/lib/jplsubs.f
index f1438d93..e1e4fb8d 100644
--- a/lib/jplsubs.f
+++ b/lib/jplsubs.f
@@ -52,8 +52,7 @@ C IF 'INQUIRE' DOES NOT WORK, USUALLY IRECSZ WILL BE LEFT AT 0
. ' INQUIRE STATEMENT PROBABLY DID NOT WORK'
KSIZE=IRECSZ/NRECL
- if(nrfile.eq.-99) stop !silence compiler warning
-
+ NRFILE=-1
RETURN
END
@@ -97,7 +96,7 @@ C
C NRFILE IS THE INTERNAL UNIT NUMBER USED FOR THE EPHEMERIS FILE
- NRFILE=12
+ NRFILE=-1
C NAMFIL IS THE EXTERNAL NAME OF THE BINARY EPHEMERIS FILE
@@ -112,15 +111,28 @@ C ** DETERMINE THE SIZE OF THE EPHEMERIS RECORD
MRECL=NRECL*1000
- OPEN(NRFILE,
+ OPEN(NEWUNIT=NRFILE,
* FILE=NAMFIL,
* ACCESS='DIRECT',
* FORM='UNFORMATTED',
* RECL=MRECL,
- * STATUS='OLD')
+ * STATUS='OLD',
+ * ACTION='READ',
+ * IOSTAT=IOS)
+ IF(IOS.NE.0) THEN
+ KSIZE=0
+ NRFILE=-1
+ RETURN
+ ENDIF
- READ(NRFILE,REC=1)TTL,(CNAM(K),K=1,OLDMAX),SS,NCON,AU,EMRAT,
+ READ(NRFILE,REC=1,IOSTAT=IOS)TTL,
+ & (CNAM(K),K=1,OLDMAX),SS,NCON,AU,EMRAT,
& ((IPT(I,J),I=1,3),J=1,12),NUMDE,(IPT(I,13),I=1,3)
+ IF(IOS.NE.0) THEN
+ KSIZE=0
+ CLOSE(NRFILE)
+ RETURN
+ ENDIF
CLOSE(NRFILE)
@@ -205,14 +217,11 @@ C *******************************************************************
END
C++++++++++++++++++++++++++
C
- SUBROUTINE PLEPH ( ET, NTARG, NCENT, RRD )
+ SUBROUTINE PLEPH ( ET, NTARG, NCENT, RRD, STATUS )
+ USE JPL_EPHEMERIS_STATUS
C
C++++++++++++++++++++++++++
-C NOTE : Over the years, different versions of PLEPH have had a fifth argument:
-C sometimes, an error return statement number; sometimes, a logical denoting
-C whether or not the requested date is covered by the ephemeris. We apologize
-C for this inconsistency; in this present version, we use only the four necessary
-C arguments and do the testing outside of the subroutine.
+C STATUS REPORTS FILE, HEADER, RANGE, AND REQUEST ERRORS WITHOUT TERMINATING.
C
C THIS SUBROUTINE READS THE JPL PLANETARY EPHEMERIS
C AND GIVES THE POSITION AND VELOCITY OF THE POINT 'NTARG'
@@ -255,6 +264,8 @@ C
C The option is available to have the units in km and km/sec.
C For this, set km=.true. in the STCOMX common block.
C
+C STATUS = INTEGER STATUS VALUE DEFINED BY JPL_EPHEMERIS_STATUS.
+C
IMPLICIT DOUBLE PRECISION (A-H,O-Z)
@@ -267,10 +278,8 @@ C
DATA ZIPS/2*0.d0/
LOGICAL BSAVE,KM,BARY
- LOGICAL FIRST
- DATA FIRST/.TRUE./
- INTEGER LIST(12),IPT(39),DENUM
+ INTEGER LIST(12),IPT(39),DENUM,STATUS
COMMON/EPHHDR/CVAL,SS,AU,EMRAT,DENUM,NCON,IPT
COMMON/STCOMX/KM,BARY,PVSUN
@@ -283,13 +292,26 @@ C
C ENTRY POINT 'DPLEPH' FOR DOUBLY-DIMENSIONED TIME ARGUMENT
C (SEE THE DISCUSSION IN THE SUBROUTINE STATE)
- ENTRY DPLEPH(ET2Z,NTARG,NCENT,RRD)
+ ENTRY DPLEPH(ET2Z,NTARG,NCENT,RRD,STATUS)
ET2(1)=ET2Z(1)
ET2(2)=ET2Z(2)
- 11 IF(FIRST) CALL STATE(ZIPS,LIST,PVST,PNUT)
- FIRST=.FALSE.
+ 11 STATUS=JPL_STATUS_OK
+ DO I=1,6
+ RRD(I)=0.D0
+ ENDDO
+
+ IF(NTARG.EQ.14 .OR. NTARG.EQ.15) THEN
+ IF(NCENT.NE.0) THEN
+ STATUS=JPL_STATUS_INVALID_REQUEST
+ RETURN
+ ENDIF
+ ELSE IF(NTARG.LT.1 .OR. NTARG.GT.13 .OR.
+ * NCENT.LT.1 .OR. NCENT.GT.13) THEN
+ STATUS=JPL_STATUS_INVALID_REQUEST
+ RETURN
+ ENDIF
IF(NTARG .EQ. NCENT) RETURN
@@ -300,44 +322,25 @@ C (SEE THE DISCUSSION IN THE SUBROUTINE STATE)
C CHECK FOR NUTATION CALL
IF(NTARG.NE.14) GO TO 97
- IF(IPT(35).GT.0) THEN
- LIST(11)=2
- CALL STATE(ET2,LIST,PVST,PNUT)
- DO I=1,4
- RRD(I)=PNUT(I)
- ENDDO
- RRD(5) = 0.d0
- RRD(6) = 0.d0
- RETURN
- ELSE
- DO I=1,4
- RRD(I)=0.d0
- ENDDO
- WRITE(6,297)
- 297 FORMAT(' ***** NO NUTATIONS ON THE EPHEMERIS FILE *****')
- STOP
- ENDIF
+ LIST(11)=2
+ CALL STATE(ET2,LIST,PVST,PNUT,STATUS)
+ IF(STATUS.NE.JPL_STATUS_OK) RETURN
+ DO I=1,4
+ RRD(I)=PNUT(I)
+ ENDDO
+ RETURN
C CHECK FOR LIBRATIONS
97 CONTINUE
- DO I=1,6
- RRD(I)=0.d0
- ENDDO
-
IF(NTARG.NE.15) GO TO 98
- IF(IPT(38).GT.0) THEN
- LIST(12)=2
- CALL STATE(ET2,LIST,PVST,PNUT)
- DO I=1,6
- RRD(I)=PVST(I,11)
- ENDDO
- RETURN
- ELSE
- WRITE(6,298)
- 298 FORMAT(' ***** NO LIBRATIONS ON THE EPHEMERIS FILE *****')
- STOP
- ENDIF
+ LIST(12)=2
+ CALL STATE(ET2,LIST,PVST,PNUT,STATUS)
+ IF(STATUS.NE.JPL_STATUS_OK) RETURN
+ DO I=1,6
+ RRD(I)=PVST(I,11)
+ ENDDO
+ RETURN
C FORCE BARYCENTRIC OUTPUT BY 'STATE'
@@ -357,7 +360,8 @@ C SET UP PROPER ENTRIES IN 'LIST' ARRAY FOR STATE CALL
C MAKE CALL TO STATE
- CALL STATE(ET2,LIST,PVST,PNUT)
+ CALL STATE(ET2,LIST,PVST,PNUT,STATUS)
+ IF(STATUS.NE.JPL_STATUS_OK) GO TO 190
DO I=1,10
DO J = 1,6
@@ -409,6 +413,8 @@ C MAKE CALL TO STATE
BARY=BSAVE
RETURN
+ 190 BARY=BSAVE
+ RETURN
END
C+++++++++++++++++++++++++++++++++
C
@@ -576,7 +582,10 @@ C MAKE ADJUSTMENTS FOR NEGATIVE INPUT NUMBER
C++++++++++++++++++++++++++++++++
C
- SUBROUTINE STATE(ET2,LIST,PV,PNUT)
+ SUBROUTINE STATE(ET2,LIST,PV,PNUT,STATUS)
+ USE JPL_EPHEMERIS_STATUS
+ USE IEEE_ARITHMETIC, ONLY: IEEE_IS_FINITE
+ USE ISO_FORTRAN_ENV, ONLY: INT64
C
C++++++++++++++++++++++++++++++++
C
@@ -656,8 +665,7 @@ C D EPSILON (NUTATION IN OBLIQUITY)
C D PSI DOT
C D EPSILON DOT
C
-C * STATEMENT # FOR ERROR RETURN, IN CASE OF EPOCH OUT OF
-C RANGE OR I/O ERRORS.
+C STATUS INTEGER STATUS VALUE DEFINED BY JPL_EPHEMERIS_STATUS.
C
C COMMON AREA STCOMX:
C
@@ -685,67 +693,138 @@ C
PARAMETER ( OLDMAX = 400)
INTEGER NMAX
PARAMETER ( NMAX = 1000)
-
DIMENSION ET2(2),PV(6,11),PNUT(4),T(2),PJD(4),BUF(1500),
. SS(3),CVAL(NMAX),PVSUN(6)
- INTEGER LIST(12),IPT(3,13)
-
- LOGICAL FIRST
- DATA FIRST/.TRUE./
+ INTEGER LIST(12),IPT(3,13),STATUS
+ INTEGER(INT64) FILESIZE,IRECORD_END
CHARACTER*6 TTL(14,3),CNAM(NMAX)
- CHARACTER*256 NAMFIL
+ CHARACTER*256 NAMFIL,JPLEPH_FILE_NAME,ACTIVE_PATH
- LOGICAL KM,BARY
+ LOGICAL KM,BARY,INITIALIZED,FAILED,ISOPEN
+ INTEGER SAVED_GENERATION,FAILURE_STATUS
+ DATA INITIALIZED/.FALSE./,FAILED/.FALSE./
+ DATA SAVED_GENERATION/-1/,FAILURE_STATUS/1/
+ DATA NRFILE/-1/,NRL/0/,ACTIVE_PATH/' '/
COMMON/EPHHDR/CVAL,SS,AU,EMRAT,NUMDE,NCON,IPT
COMMON/CHRHDR/CNAM,TTL
COMMON/STCOMX/KM,BARY,PVSUN
+ COMMON/JPLCOM/JPLEPH_FILE_NAME
-C
-C ENTRY POINT - 1ST TIME IN, GET POINTER DATA, ETC., FROM EPH FILE
-C
- IF(FIRST) THEN
- FIRST=.FALSE.
-
-C ************************************************************************
-C ************************************************************************
-
-C THE USER MUST SELECT ONE OF THE FOLLOWING BY DELETING THE 'C' IN COLUMN 1
+ STATUS=JPL_STATUS_OK
+ DO I=1,11
+ DO J=1,6
+ PV(J,I)=0.D0
+ ENDDO
+ ENDDO
+ DO I=1,4
+ PNUT(I)=0.D0
+ ENDDO
+ DO I=1,6
+ PVSUN(I)=0.D0
+ ENDDO
-C ************************************************************************
+C RESET LOCAL READER STATE WHEN THE CONFIGURATION CHANGES
-C CALL FSIZER1(NRECL,KSIZE,NRFILE,NAMFIL)
-C CALL FSIZER2(NRECL,KSIZE,NRFILE,NAMFIL)
- CALL FSIZER3(NRECL,KSIZE,NRFILE,NAMFIL)
+ IF(SAVED_GENERATION.NE.CONFIGURATION_GENERATION .OR.
+ * ACTIVE_PATH.NE.JPLEPH_FILE_NAME) THEN
+ IF(NRFILE.NE.-1) THEN
+ INQUIRE(UNIT=NRFILE,OPENED=ISOPEN)
+ IF(ISOPEN) CLOSE(NRFILE)
+ ENDIF
+ NRFILE=-1
+ NRL=0
+ INITIALIZED=.FALSE.
+ FAILED=.FALSE.
+ FAILURE_STATUS=JPL_STATUS_IO_ERROR
+ ACTIVE_PATH=JPLEPH_FILE_NAME
+ SAVED_GENERATION=CONFIGURATION_GENERATION
+ CALL NOTE_JPL_READER_CHANGE()
+ ENDIF
- IF(NRECL .EQ. 0) WRITE(*,*)' ***** FSIZER IS NOT WORKING *****'
+ IF(.NOT.IEEE_IS_FINITE(ET2(1)) .OR.
+ * .NOT.IEEE_IS_FINITE(ET2(2))) THEN
+ STATUS=JPL_STATUS_INVALID_REQUEST
+ RETURN
+ ENDIF
-C ************************************************************************
-C ************************************************************************
+ IF(FAILED) THEN
+ STATUS=FAILURE_STATUS
+ RETURN
+ ENDIF
+C
+C ENTRY POINT - 1ST TIME IN, GET POINTER DATA, ETC., FROM EPH FILE
+C
+ IF(.NOT.INITIALIZED) THEN
+ NRECL=4
+ KSIZE=2036
+ NAMFIL=JPLEPH_FILE_NAME
IRECSZ=NRECL*KSIZE
NCOEFFS=KSIZE/2
- OPEN(NRFILE,
+ OPEN(NEWUNIT=NRFILE,
* FILE=NAMFIL,
* ACCESS='DIRECT',
* FORM='UNFORMATTED',
* RECL=IRECSZ,
- * STATUS='OLD')
+ * STATUS='OLD',
+ * ACTION='READ',
+ * IOSTAT=IOS)
+ IF(IOS.NE.0) THEN
+ NRFILE=-1
+ GO TO 990
+ ENDIF
- READ(NRFILE,REC=1)TTL,(CNAM(K),K=1,OLDMAX),SS,NCON,AU,EMRAT,
+ READ(NRFILE,REC=1,IOSTAT=IOS)TTL,
+ & (CNAM(K),K=1,OLDMAX),SS,NCON,AU,EMRAT,
& ((IPT(I,J),I=1,3),J=1,12),NUMDE,(IPT(I,13),I=1,3)
- & ,(CNAM(L),L=OLDMAX+1,NCON)
-
- IF(NCON .LE. OLDMAX)THEN
- READ(NRFILE,REC=2)(CVAL(I),I=1,OLDMAX)
- ELSE
- READ(NRFILE,REC=2)(CVAL(I),I=1,NCON)
+ IF(IOS.NE.0) GO TO 991
+ IF(NCON.LT.0 .OR. NCON.GT.NMAX .OR.
+ * NCON.GT.NCOEFFS) GO TO 992
+
+C READ EXTENDED CONSTANT NAMES ONLY AFTER NCON IS KNOWN TO FIT
+
+ IF(NCON.GT.OLDMAX) THEN
+ READ(NRFILE,REC=1,IOSTAT=IOS)TTL,
+ & (CNAM(K),K=1,OLDMAX),SS,NCON,AU,EMRAT,
+ & ((IPT(I,J),I=1,3),J=1,12),NUMDE,
+ & (IPT(I,13),I=1,3),(CNAM(L),L=OLDMAX+1,NCON)
+ IF(IOS.NE.0) GO TO 991
ENDIF
+ IF(.NOT.IEEE_IS_FINITE(SS(1)) .OR.
+ * .NOT.IEEE_IS_FINITE(SS(2)) .OR.
+ * .NOT.IEEE_IS_FINITE(SS(3)) .OR.
+ * .NOT.IEEE_IS_FINITE(AU) .OR.
+ * .NOT.IEEE_IS_FINITE(EMRAT)) GO TO 992
+ IF(SS(2).LE.SS(1) .OR. SS(3).LE.0.D0 .OR.
+ * AU.LE.0.D0 .OR. EMRAT.LE.0.D0) GO TO 992
+
+ DO J=1,13
+ IF(IPT(1,J).EQ.0 .AND. IPT(2,J).EQ.0 .AND.
+ * IPT(3,J).EQ.0) THEN
+ IF(J.LE.11) GO TO 992
+ ELSE
+ IF(IPT(1,J).LE.0 .OR. IPT(2,J).LE.0 .OR.
+ * IPT(3,J).LE.0) GO TO 992
+ IF(IPT(1,J).GT.NCOEFFS .OR. IPT(2,J).GT.18
+ * .OR. IPT(3,J).GT.NCOEFFS) GO TO 992
+ NCOMP=3
+ IF(J.EQ.12) NCOMP=2
+ IAVAILABLE=NCOEFFS-IPT(1,J)+1
+ IF(IPT(2,J).GT.IAVAILABLE/NCOMP/IPT(3,J)) GO TO 992
+ ENDIF
+ ENDDO
+
+ NVALUES=MAX(OLDMAX,NCON)
+ READ(NRFILE,REC=2,IOSTAT=IOS)(CVAL(I),I=1,NVALUES)
+ IF(IOS.NE.0) GO TO 991
+
NRL=0
+ INITIALIZED=.TRUE.
ENDIF
@@ -753,6 +832,15 @@ C ********** MAIN ENTRY POINT **********
IF(ET2(1) .EQ. 0.D0) RETURN
+ IF(LIST(11).GT.0 .AND. IPT(2,12).EQ.0) THEN
+ STATUS=JPL_STATUS_NOT_AVAILABLE
+ RETURN
+ ENDIF
+ IF(LIST(12).GT.0 .AND. IPT(2,13).EQ.0) THEN
+ STATUS=JPL_STATUS_NOT_AVAILABLE
+ RETURN
+ ENDIF
+
S=ET2(1)-.5D0
CALL SPLIT_DP(S,PJD(1))
CALL SPLIT_DP(ET2(2),PJD(3))
@@ -763,11 +851,21 @@ C ********** MAIN ENTRY POINT **********
C ERROR RETURN FOR EPOCH OUT OF RANGE
- IF(PJD(1)+PJD(4).LT.SS(1) .OR. PJD(1)+PJD(4).GT.SS(2)) GO TO 98
+ IF(PJD(1)+PJD(4).LT.SS(1) .OR.
+ * PJD(1)+PJD(4).GT.SS(2)) THEN
+ STATUS=JPL_STATUS_OUT_OF_RANGE
+ RETURN
+ ENDIF
C CALCULATE RECORD # AND RELATIVE TIME IN INTERVAL
- NR=IDINT((PJD(1)-SS(1))/SS(3))+3
+ RECORD_SPAN=PJD(1)-SS(1)+PJD(4)
+ IF(.NOT.IEEE_IS_FINITE(RECORD_SPAN)) GO TO 992
+ IF(SS(3).LE.RECORD_SPAN/DBLE(HUGE(NR)-3)) GO TO 992
+ RECORD_OFFSET=RECORD_SPAN/SS(3)
+ IF(.NOT.IEEE_IS_FINITE(RECORD_OFFSET) .OR.
+ * RECORD_OFFSET.GE.DBLE(HUGE(NR)-3)) GO TO 992
+ NR=IDINT(RECORD_OFFSET)+3
IF(PJD(1).EQ.SS(2)) NR=NR-1
tmp1 = DBLE(NR-3)*SS(3) + SS(1)
@@ -777,8 +875,13 @@ C CALCULATE RECORD # AND RELATIVE TIME IN INTERVAL
C READ CORRECT RECORD IF NOT IN CORE
IF(NR.NE.NRL) THEN
+ INQUIRE(UNIT=NRFILE,SIZE=FILESIZE,IOSTAT=IOS)
+ IF(IOS.NE.0) GO TO 991
+ IRECORD_END=INT(NR,INT64)*INT(IRECSZ,INT64)
+ IF(FILESIZE.LT.IRECORD_END) GO TO 991
+ READ(NRFILE,REC=NR,IOSTAT=IOS)(BUF(K),K=1,NCOEFFS)
+ IF(IOS.NE.0) GO TO 991
NRL=NR
- READ(NRFILE,REC=NR,ERR=99)(BUF(K),K=1,NCOEFFS)
ENDIF
IF(KM) THEN
@@ -829,20 +932,27 @@ C GET LIBRATIONS IF REQUESTED (AND IF ON FILE)
RETURN
- 98 WRITE(*,198)ET2(1)+ET2(2),SS(1),SS(2)
- 198 FORMAT(' *** Requested JED,',f12.2,
- * ' not within ephemeris limits,',2f12.2,' ***')
-
- STOP
-
- 99 WRITE(*,'(2F12.2,A80)')ET2,'ERROR RETURN IN STATE'
-
- STOP
+ 990 FAILURE_STATUS=JPL_STATUS_IO_ERROR
+ GO TO 994
+ 991 FAILURE_STATUS=JPL_STATUS_IO_ERROR
+ GO TO 993
+ 992 FAILURE_STATUS=JPL_STATUS_INVALID_HEADER
+ 993 IF(NRFILE.NE.-1) THEN
+ INQUIRE(UNIT=NRFILE,OPENED=ISOPEN)
+ IF(ISOPEN) CLOSE(NRFILE)
+ ENDIF
+ 994 NRFILE=-1
+ NRL=0
+ INITIALIZED=.FALSE.
+ FAILED=.TRUE.
+ STATUS=FAILURE_STATUS
+ RETURN
END
C+++++++++++++++++++++++++++++
C
SUBROUTINE CONST(NAM,VAL,SSS,N)
+ USE JPL_EPHEMERIS_STATUS
C
C+++++++++++++++++++++++++++++
C
@@ -871,17 +981,17 @@ C
DOUBLE PRECISION PVST(6,11),PNUT(4)
DATA ZIPS/2*0.d0/
- INTEGER IPT(3,13),DENUM,LIST(12)
- logical first
- data first/.true./
-
+ INTEGER IPT(3,13),DENUM,LIST(12),STATUS
COMMON/EPHHDR/CVAL,SS,AU,EMRAT,DENUM,NCON,IPT
COMMON/CHRHDR/CNAM,TTL
C CALL STATE TO INITIALIZE THE EPHEMERIS AND READ IN THE CONSTANTS
- IF(FIRST) CALL STATE(ZIPS,LIST,PVST,PNUT)
- first=.false.
+ CALL STATE(ZIPS,LIST,PVST,PNUT,STATUS)
+ IF(STATUS.NE.JPL_STATUS_OK) THEN
+ N=0
+ RETURN
+ ENDIF
N=NCON
diff --git a/lib/jt4.f90 b/lib/jt4.f90
index 21407255..42a2d16b 100644
--- a/lib/jt4.f90
+++ b/lib/jt4.f90
@@ -23,4 +23,7 @@ module jt4
0,1,1,1,0,0,1,0,1,1,0,1,1,1,1,0,0,0,0,1,1,0,1,1,0,0,0,1,1,1, &
0,1,1,1,0,1,1,1,0,0,1,0,0,0,1,1,0,1,1,0,0,1,0,0,0,1,1,1,1,1, &
1,0,0,1,1,0,0,0,0,1,1,0,0,0,1,0,1,1,0,1,1,1,1,0,1,0,1/
+
+ save ppsave,zz
+
end module jt4
diff --git a/lib/jt49sim.f90 b/lib/jt49sim.f90
index 7da5b510..9bced81e 100644
--- a/lib/jt49sim.f90
+++ b/lib/jt49sim.f90
@@ -80,7 +80,7 @@ program jt49sim
do ifile=1,nfiles !Loop over requested number of files
write(fname,1002) ifile !Output filename
1002 format('000000_',i4.4)
- open(10,file=fname//'.wav',access='stream',status='unknown')
+ open(10,file=fname//'.wav',access='stream',status='replace')
xnoise=0.
cdat=0.
if(snrdb.lt.90) then
diff --git a/lib/jt4_decode.f90 b/lib/jt4_decode.f90
index 483c8275..8ab48bda 100644
--- a/lib/jt4_decode.f90
+++ b/lib/jt4_decode.f90
@@ -61,9 +61,9 @@ contains
character(len=12), intent(in) :: mycall,hiscall
character(len=6), intent(in) :: hisgrid
procedure(jt4_average_callback), optional :: average_callback
-
real*4 dat(30*11025)
character*6 cfile6
+ save dat
this%decode_callback => decode_callback
if (present (average_callback)) then
@@ -443,7 +443,6 @@ subroutine getsnr(dat,npts,mode4,dtx,decoded,nsnr)
do i=1,nh
s(i)=real(cx(i))**2 + aimag(cx(i))**2
enddo
- jtone=nint((fpk-1500)/(mode4*df))
nshift=mode4*itone(j)
savg=savg + cshift(s,nshift) !Move all power into lowest tone freq
enddo
diff --git a/lib/jt4sim.f90 b/lib/jt4sim.f90
index 73edabf7..c15d6d55 100644
--- a/lib/jt4sim.f90
+++ b/lib/jt4sim.f90
@@ -62,7 +62,7 @@ program jt4sim
do ifile=1,nfiles !Loop over requested number of files
write(fname,1002) ifile !Output filename
1002 format('000000_',i4.4)
- open(10,file=fname//'.wav',access='stream',status='unknown')
+ open(10,file=fname//'.wav',access='stream',status='replace')
xnoise=0.
cdat=0.
if(snrdb.lt.90) then
diff --git a/lib/jt65.f90 b/lib/jt65.f90
index bce3a4f1..2e77c694 100644
--- a/lib/jt65.f90
+++ b/lib/jt65.f90
@@ -17,6 +17,7 @@ program jt65
character(len=500) optarg
character*12 mycall,hiscall
character*6 hisgrid
+ integer :: files_read, samples_read
type (option) :: long_options(12) = [ &
option ('aggressive',.true.,'a','aggressiveness [0-10], default AGGR=0','AGGR'), &
@@ -107,6 +108,7 @@ program jt65
call timer('jt65 ',0)
ndecoded=0
+ files_read=0
do ifile=noffset+1,noffset+nremain
nfa=nlow
nfb=nhigh
@@ -114,14 +116,32 @@ program jt65
call get_command_argument(ifile,optarg,narglen)
infile=optarg(:narglen)
call timer('read ',0)
- call wav%read (infile)
+ call wav%read (infile, ios, optarg)
+ if (ios /= 0) then
+ call timer('read ',1)
+ write(*,*) 'Cannot read WAV file ',trim(infile),': ',trim(optarg)
+ cycle
+ end if
+ if (wav%audio_format%sample_rate /= 12000) then
+ close(unit=wav%lun)
+ call timer('read ',1)
+ write(*,*) 'Cannot read WAV file ',trim(infile),': unsupported sample rate'
+ cycle
+ end if
i1=index(infile,'.wav')
if( i1 .eq. 0 ) i1=index(infile,'.WAV')
read(infile(i1-4:i1-1),*,err=998) nutc
npts=52*12000
- read(unit=wav%lun) id2(1:npts)
+ id2=0
+ call wav%read_samples(id2(1:npts), samples_read, ios, optarg)
close(unit=wav%lun)
call timer('read ',1)
+ if (ios /= 0) then
+ write(*,*) 'Cannot read WAV file ',trim(infile),': ',trim(optarg)
+ cycle
+ end if
+ if (samples_read < npts) print*,'EOF on input file ',trim(infile)
+ files_read=files_read+1
dd(1:npts)=id2(1:npts)
dd(npts+1:)=0.
call test(dd,nutc,nfa,nfb,nfqso,ntol,nsubmode, &
@@ -132,6 +152,7 @@ program jt65
call timer('jt65 ',1)
call timer('jt65 ',101)
+ if (files_read == 0) stop 2
! call four2a(a,-1,1,1,1) !Free the memory used for plans
! call filbig(a,-1,1,0.0,0,0,0,0,0) ! (ditto)
go to 999
diff --git a/lib/jt65_decode.f90 b/lib/jt65_decode.f90
index 4e73ee7b..18a901ce 100644
--- a/lib/jt65_decode.f90
+++ b/lib/jt65_decode.f90
@@ -205,6 +205,8 @@ contains
if(bVHF) then
flip=ca(icand)%flip
nflip=int(flip)
+ else
+ nflip=1
endif
if(sync1.lt.float(minsync)) nflip=0
if(ipass.eq.1) ntry65a=ntry65a + 1
@@ -275,6 +277,8 @@ contains
! Display a decoded message obtained by averaging 2 or more transmissions
call this%callback(sync1,nsnr,dtx-1.0,nfreq,ndrift, &
nflip,width,avemsg,nftt,nqave,nsmo,nsum,minsync)
+ if (iand(ndepth,128).ne.0 .and. .not.nagain .and. &
+ abs(nfreq-nfqso).le.ntol) clear_avg65=.true. ! AutoClrAvg
prtavg=.true.
end if
@@ -370,6 +374,13 @@ contains
data first/.true./
save
+ nftt=0
+ avemsg=' '
+ deepave=' '
+ qave=0.0
+ deepbest=' '
+ nfttbest=0
+
if(first .or. clear_avg65) then
iutc=-1
nfsave=0
@@ -385,7 +396,10 @@ contains
do i=1,64
if(iutc(i).lt.0) exit
- if(nutc.eq.iutc(i) .and. abs(nfreq-nfsave(i)).le.ntol) go to 10
+ if(nutc.eq.iutc(i) .and. abs(nfreq-nfsave(i)).le.ntol) then
+ nsave=mod(nsave-2+MAXAVE,MAXAVE)+1
+ go to 10
+ endif
enddo
! Save data for message averaging
@@ -396,9 +410,6 @@ contains
nflipsave(nsave)=nflip
s1save(-255:256,1:126,nsave)=s1
s3save(1:64,1:63,nsave)=s3a
- avemsg=' '
- deepbest=' '
- nfttbest=0
10 syncsum=0.
dtsum=0.
diff --git a/lib/jt65_mod.f90 b/lib/jt65_mod.f90
index 23c29537..772ebeae 100644
--- a/lib/jt65_mod.f90
+++ b/lib/jt65_mod.f90
@@ -1,5 +1,7 @@
module jt65_mod
+ save
+
integer param(0:9)
integer mrs(63)
integer mrs2(63)
diff --git a/lib/jt65sim.f90 b/lib/jt65sim.f90
index 623a0fca..d3f099ff 100644
--- a/lib/jt65sim.f90
+++ b/lib/jt65sim.f90
@@ -151,7 +151,7 @@ program jt65sim
do ifile=1,nfiles !Loop over requested number of files
write(fname,1002) ifile !Output filename
1002 format('000000_',i4.4)
- open(10,file=fname//'.wav',access='stream',status='unknown')
+ open(10,file=fname//'.wav',access='stream',status='replace')
xnoise=0.
cdat=0.
diff --git a/lib/jt9.f90 b/lib/jt9.f90
index 64901c09..be09716b 100644
--- a/lib/jt9.f90
+++ b/lib/jt9.f90
@@ -10,11 +10,22 @@ program jt9
use timer_module, only: timer
use timer_impl, only: init_timer, fini_timer
use readwav
+ use jt9_input_validation, only: parse_integer, parse_real, parse_wav_filename_nutc
+ use, intrinsic :: iso_fortran_env, only: error_unit
use ft8_mod1, only : dd8
use jt65_mod6, only : dd
+ use streaming_emit, only: streaming_emit_set_enabled, streaming_emit_error
+ use jt9_params_init, only: init_default_params, init_streaming_extra_fields, &
+ apply_per_mode_policy, cli_args_t
include 'jt9com.f90'
+ interface
+ subroutine jt9_print_version() bind(C, name='jt9_print_version')
+ end subroutine jt9_print_version
+ end interface
+
+ type(cli_args_t) :: args
integer*2 id2a(180000)
integer(C_INT) iret
type(wav_header) wav
@@ -28,18 +39,24 @@ program jt9
integer :: arglen,stat,offset,remain,mode=0,flow=200,fsplit=2700, &
fhigh=4000,nrxfreq=1500,ndepth=1,nexp_decode=0,nQSOProg=0,ncycles=3, &
- nft8rxfsens=3,nmt=0,nmtft8decsens=3,ndecoderstart=3
+ nft8rxfsens=3,nmt=0,nmtft8decsens=3,ndecoderstart=3, samples_read, wav_status
logical :: read_files = .true., tx9 = .false., display_help = .false., &
+ display_version = .false., &
bLowSidelobes = .false., nexp_decode_set = .false., &
have_ntol = .false.,multift8 = .false.,hidedupes = .false., &
- lft8lowth = .true.,lft8subpass = .true.,lwidedxcsearch = .true.
- type (option) :: long_options(41) = [ &
+ lft8lowth = .true.,lft8subpass = .true.,lwidedxcsearch = .true., &
+ stream_mode = .false.
+ type (option) :: long_options(43) = [ &
option ('help', .false., 'h', 'Display this help message', ''), &
+ option ('version', .false., 'v', 'Display version and build revision', ''),&
option ('shmem',.true.,'s','Use shared memory for sample data','KEY'), &
+ option ('stream', .false., '0', &
+ 'Read framed PCM samples from stdin', &
+ ''), &
option ('tr-period', .true., 'p', 'Tx/Rx period, default SECONDS=60', &
'SECONDS'), &
option ('executable-path', .true., 'e', &
- 'Location of subordinate executables (KVASD) default PATH="."', &
+ 'Location of subordinate executables, default PATH="."', &
'PATH'), &
option ('data-path', .true., 'a', &
'Location of writeable data files, default PATH="."', 'PATH'), &
@@ -107,7 +124,6 @@ program jt9
'FLAGS') ]
type(dec_data), allocatable :: shared_data
- character(len=20) :: datetime=''
character(len=12) :: mycall='K1ABC', hiscall='W9XYZ'
character(len=6) :: mygrid='', hisgrid='EN37'
common/patience/npatience,nthreads
@@ -119,7 +135,7 @@ program jt9
TRperiod=60.d0
do
- call getopt('hs:e:a:b:r:m:p:d:f:F:w:t:9876543WYqkTMUSZL:S:H:c:G:x:g:X:Q:C:R:N:E:D:', &
+ call getopt('hvs:e:a:b:r:m:p:d:f:F:w:t:9876543WYqkTMUSZL:S:H:c:G:x:g:X:Q:C:R:N:E:D:', &
long_options,c,optarg,arglen,stat,offset,remain,.true.)
if (stat .ne. 0) then
exit
@@ -127,48 +143,59 @@ program jt9
select case (c)
case ('h')
display_help = .true.
+ case ('v')
+ display_version = .true.
case ('s')
read_files = .false.
shm_key = optarg(:arglen)
+ case ('0')
+ read_files = .false.
+ stream_mode = .true.
+ call streaming_emit_set_enabled(.true.)
case ('e')
exe_dir = optarg(:arglen)
case ('a')
data_dir = optarg(:arglen)
+ case ('r')
+ share_dir = optarg(:arglen) ! read-only shipped-data dir (cty.dat, ALLCALL7.TXT, ...)
case ('b')
nsubmode = ichar (optarg(:1)) - ichar ('A')
case ('t')
temp_dir = optarg(:arglen)
case ('m')
- read (optarg(:arglen), *) nthreads
+ call require_integer('m', optarg(:arglen), nthreads)
case ('p')
- read (optarg(:arglen), *) TRperiod
+ call require_real('p', optarg(:arglen), TRperiod)
+ if (TRperiod <= 0.d0 .or. TRperiod > dble(NTMAX)) then
+ call invalid_option('p', optarg(:arglen), 'must be between 0 and 1800 seconds')
+ end if
case ('d')
- read (optarg(:arglen), *) ndepth
+ call require_integer('d', optarg(:arglen), ndepth)
case ('f')
- read (optarg(:arglen), *) nrxfreq
+ call require_integer('f', optarg(:arglen), nrxfreq)
case ('F')
- read (optarg(:arglen), *) ntol
+ call require_integer('F', optarg(:arglen), ntol)
have_ntol = .true.
case ('L')
- read (optarg(:arglen), *) flow
+ call require_integer('L', optarg(:arglen), flow)
case ('S')
- read (optarg(:arglen), *) fsplit
+ call require_integer('S', optarg(:arglen), fsplit)
case ('H')
- read (optarg(:arglen), *) fhigh
+ call require_integer('H', optarg(:arglen), fhigh)
case ('M')
multift8 = .true.
case ('C')
- read (optarg(:arglen), *) ncycles
+ call require_integer('C', optarg(:arglen), ncycles)
case ('U')
hidedupes = .true.
case ('R')
- read (optarg(:arglen), *) nft8rxfsens
+ call require_integer('R', optarg(:arglen), nft8rxfsens)
case ('N')
- read (optarg(:arglen), *) nmt
+ call require_integer('N', optarg(:arglen), nmt)
case ('E')
- read (optarg(:arglen), *) nmtft8decsens
+ call require_integer('E', optarg(:arglen), nmtft8decsens)
case ('D')
- read (optarg(:arglen), *) ndecoderstart
+ call require_integer('D', optarg(:arglen), ndecoderstart)
case ('Z')
lwidedxcsearch = .false.
case ('q')
@@ -176,7 +203,10 @@ program jt9
case ('k')
mode = 144
case ('Q')
- read (optarg(:arglen), *) nQSOProg
+ call require_integer('Q', optarg(:arglen), nQSOProg)
+ if (nQSOProg < 0 .or. nQSOProg > 5) then
+ call invalid_option('Q', optarg(:arglen), 'must be between 0 and 5')
+ end if
case ('3')
mode = 66
case ('4')
@@ -194,7 +224,7 @@ program jt9
case ('T')
tx9 = .true.
case ('w')
- read (optarg(:arglen), *) npatience
+ call require_integer('w', optarg(:arglen), npatience)
case ('W')
mode = 241
case ('Y')
@@ -208,10 +238,15 @@ program jt9
case ('g')
read (optarg(:arglen), *) hisgrid
case ('X')
- read (optarg(:arglen), *) nexp_decode
+ call require_integer('X', optarg(:arglen), nexp_decode)
nexp_decode_set = .true.
end select
end do
+
+ if (display_version) then
+ call jt9_print_version()
+ stop
+ endif
if (display_help .or. stat .lt. 0 &
.or. (.not. read_files .and. remain .gt. 0) &
@@ -220,9 +255,12 @@ program jt9
print *, 'Usage: jt9 [OPTIONS] file1 [file2 ...]'
print *, ' Reads data from *.wav files.'
print *, ''
- print *, ' jt9 -s <key> [-w patience] [-m threads] [-e path] [-a path] [-t path]'
+ print *, ' jt9 -s <key> [-w patience] [-m threads] [-e path] [-a path] [-t path] [-r path]'
print *, ' Gets data from shared memory region with key==<key>'
print *, ''
+ print *, ' cat <pcm-stream> | jt9 --stream'
+ print *, ' Reads framed PCM samples from stdin.'
+ print *, ''
print *, 'OPTIONS:'
print *, ''
do i = 1, size (long_options)
@@ -248,7 +286,67 @@ program jt9
numfano=0
if (.not. read_files) then
- call jt9a() !We're running under control of WSJT-X
+ if (stream_mode) then
+ ! Streaming subprocess mode. Mirror the WAV path's shared_data setup,
+ ! then hand off to the streaming reader.
+ if (mode .eq. 0) then
+ mode = 8 ! default: FT8
+ if (TRperiod .eq. 60.d0) TRperiod = 15.d0
+ end if
+ if (mode .eq. 5 .and. TRperiod .eq. 60.d0) TRperiod = 7.5d0 ! FT4
+ if (mode .eq. 144 .and. TRperiod .eq. 60.d0) TRperiod = 30.d0 ! MSK144
+
+ ! Per-mode ntol defaulting (mirrors WAV path lines 277–285).
+ if (mode .eq. 241 .or. mode .eq. 242) then
+ ntol = min(ntol, 100)
+ else if (mode .eq. 65 + 9 .and. .not. have_ntol) then
+ ntol = 20
+ else if (mode .eq. 66 .and. .not. have_ntol) then
+ ntol = 10
+ else
+ ntol = min(ntol, 1000)
+ end if
+
+ ! Per-mode nexp_decode default (mirrors WAV path lines 287–291).
+ if (.not. nexp_decode_set) then
+ if (mode .eq. 240 .or. mode .eq. 241 .or. mode .eq. 242) then
+ nexp_decode = 3 * 256 ! FST4: single decode off, nb=0
+ end if
+ end if
+
+ if (mycall.eq.'b') mycall = ' '
+ if (hiscall.eq.'b') then
+ hiscall = ' '
+ hisgrid = ' '
+ end if
+ allocate(shared_data)
+ call init_timer (trim(data_dir)//'/timer.out')
+ shared_data%id2 = 0
+
+ ! Common params first, then streaming-only fields.
+ args = cli_args_t( &
+ flow=flow, fsplit=fsplit, fhigh=fhigh, nrxfreq=nrxfreq, &
+ ndepth=ndepth, ntol=ntol, nQSOProg=nQSOProg, &
+ nexp_decode=nexp_decode, ncycles=ncycles, &
+ nft8rxfsens=nft8rxfsens, nmt=nmt, ndecoderstart=ndecoderstart, &
+ nsubmode=nsubmode, mycall=mycall, hiscall=hiscall, &
+ mygrid=mygrid, hisgrid=hisgrid, &
+ datetime='2026-Apr-25 00:00 ', &
+ tx9=tx9, multift8=.false., hidedupes=.false., &
+ lft8lowth=.true., lft8subpass=.true., &
+ lwidedxcsearch=lwidedxcsearch, have_ntol=have_ntol, &
+ nexp_decode_set=nexp_decode_set)
+ call init_default_params(shared_data%params, mode, TRperiod, args)
+ call init_streaming_extra_fields(shared_data%params, args)
+
+ ! Streaming-side overrides post-init.
+ ! (mode=9 nfa=fsplit handled by init_default_params per-mode adjustment.)
+ ! (single-pass FT8 only in stream — already enforced via args.multift8=.false.)
+
+ call jt9_stream(shared_data, mode, TRperiod)
+ else
+ call jt9a() !We're running under control of WSJT-X (shared memory)
+ end if
go to 999
endif
@@ -279,18 +377,20 @@ program jt9
do iarg = offset + 1, offset + remain
call get_command_argument (iarg, optarg, arglen)
infile = optarg(:arglen)
- call wav%read (infile)
+ call wav%read (infile, wav_status, optarg)
+ if (wav_status /= 0) then
+ write(error_unit, '(A)') 'jt9: cannot read WAV file ' // trim(infile) // ': ' // trim(optarg)
+ stop 2
+ end if
nfsample=wav%audio_format%sample_rate
- i1=index(infile,'.wav')
- if(i1.lt.1) i1=index(infile,'.WAV')
- if(infile(i1-5:i1-5).eq.'_') then
- read(infile(i1-4:i1-1),*,err=1) nutc
- else
- read(infile(i1-6:i1-1),*,err=1) nutc
- endif
- go to 2
-1 nutc=0
-2 nsps=6912
+ if (nfsample /= 12000 .and. .not. (mode == 4 .and. nfsample == 11025)) then
+ close(unit=wav%lun)
+ write(error_unit, '(A,I0,A)') 'jt9: unsupported ',nfsample, &
+ ' Hz WAV sample rate for the selected mode'
+ stop 2
+ end if
+ call parse_wav_filename_nutc(infile, nutc)
+ nsps=6912
npts=TRperiod*12000.d0
kstep=nsps/2
k=0
@@ -301,18 +401,29 @@ program jt9
call timer('jt9 ',0)
endif
shared_data%id2=0 !??? Why is this necessary ???
+ if(mode.eq.4) npts=52*nfsample
if(mode.eq.5) npts=21*3456
if(mode.eq.66) npts=TRperiod*12000
- do iblk=1,npts/kstep
- k=iblk*kstep
+ nblocks=npts/kstep
+ if(mode.eq.4) nblocks=(npts+kstep-1)/kstep
+ do iblk=1,nblocks
+ k0=(iblk-1)*kstep
+ k=min(iblk*kstep,npts)
if(mode.eq.8 .and. k.gt.179712) exit
call timer('read_wav',0)
- read(unit=wav%lun,end=3) shared_data%id2(k-kstep+1:k)
- go to 4
-3 call timer('read_wav',1)
- print*,'EOF on input file ',trim(infile)
- exit
-4 call timer('read_wav',1)
+ call wav%read_samples(shared_data%id2(k0+1:k), samples_read, &
+ wav_status, optarg)
+ call timer('read_wav',1)
+ if (wav_status /= 0) then
+ close(unit=wav%lun)
+ write(error_unit, '(A)') 'jt9: cannot read WAV file ' // &
+ trim(infile) // ': ' // trim(optarg)
+ stop 2
+ end if
+ if (samples_read == 0) then
+ print*,'EOF on input file ',trim(infile)
+ exit
+ end if
nhsym=(k-2048)/kstep
if(nhsym.ge.1 .and. nhsym.ne.nhsym0) then
if(mode.eq.9 .or. mode.eq.74) then
@@ -328,53 +439,38 @@ program jt9
if(nhsym.ge.181 .and. mode.ne.240 .and. mode.ne.241 .and. &
mode.ne.242 .and. mode.ne.66) exit
endif
+ if (samples_read < k-k0) then
+ print*,'EOF on input file ',trim(infile)
+ exit
+ end if
enddo
close(unit=wav%lun)
- shared_data%params%nutc=nutc
- shared_data%params%ndiskdat=.true.
- shared_data%params%ntr=TRperiod
- shared_data%params%nfqso=nrxfreq
- shared_data%params%newdat=.true.
- shared_data%params%npts8=74736
- shared_data%params%nfa=flow
- shared_data%params%nfsplit=fsplit
- shared_data%params%nfb=fhigh
- shared_data%params%ntol=ntol
- shared_data%params%kin=64800
- if(mode.eq.240) shared_data%params%kin=720000 !### 60 s periods ###
- shared_data%params%nzhsym=nhsym
- shared_data%params%ndepth=ndepth
- shared_data%params%lft8apon=.true.
- shared_data%params%ljt65apon=.true.
- shared_data%params%napwid=75
- shared_data%params%dttol=3.
- if(mode.eq.164 .and. nsubmode.lt.100) nsubmode=nsubmode+100
- shared_data%params%nagain=.false.
- shared_data%params%nclearave=.false.
- shared_data%params%lapcqonly=.false.
- shared_data%params%naggressive=0
- shared_data%params%n2pass=2
- shared_data%params%nQSOprogress=nQSOProg
- shared_data%params%nranera=6 !### ntrials=3000
- shared_data%params%nrobust=.false.
- shared_data%params%nexp_decode=nexp_decode
- shared_data%params%lmultift8=multift8
- shared_data%params%mycall=transfer(mycall,shared_data%params%mycall)
- shared_data%params%mygrid=transfer(mygrid,shared_data%params%mygrid)
- shared_data%params%hiscall=transfer(hiscall,shared_data%params%hiscall)
- shared_data%params%hisgrid=transfer(hisgrid,shared_data%params%hisgrid)
- if (tx9) then
- shared_data%params%ntxmode=9
- else
- shared_data%params%ntxmode=65
- end if
- if (mode.eq.0) then
- shared_data%params%nmode=65+9
- else
- shared_data%params%nmode=mode
- end if
- shared_data%params%nsubmode=nsubmode
+ ! WAV-path-only mode adjustment (mode=164 with submode<100 bumps by 100).
+ ! Hoisted before init_default_params so the bumped value is threaded
+ ! through the args bundle.
+ if (mode.eq.164 .and. nsubmode.lt.100) nsubmode = nsubmode + 100
+
+ ! WAV mode initializes only fields historically set by this path.
+ args = cli_args_t( &
+ flow=flow, fsplit=fsplit, fhigh=fhigh, nrxfreq=nrxfreq, &
+ ndepth=ndepth, ntol=ntol, nQSOProg=nQSOProg, &
+ nexp_decode=nexp_decode, ncycles=ncycles, &
+ nft8rxfsens=nft8rxfsens, nmt=nmt, ndecoderstart=ndecoderstart, &
+ nsubmode=nsubmode, mycall=mycall, hiscall=hiscall, &
+ mygrid=mygrid, hisgrid=hisgrid, &
+ datetime='2013-Apr-16 15:13 ', &
+ tx9=tx9, multift8=multift8, hidedupes=hidedupes, &
+ lft8lowth=lft8lowth, lft8subpass=lft8subpass, &
+ lwidedxcsearch=lwidedxcsearch, have_ntol=have_ntol, &
+ nexp_decode_set=nexp_decode_set)
+ call init_default_params(shared_data%params, mode, TRperiod, args)
+
+ ! WAV-path post-init overrides.
+ shared_data%params%nutc = nutc ! parsed from filename
+ shared_data%params%ndiskdat = .true. ! reading from disk
+ shared_data%params%nzhsym = nhsym ! per-period (matches former jt9.f90:486)
+ if (mode.eq.0) shared_data%params%nmode = 65 + 9 ! WAV-only mode=0 → JT65+JT9
if (multift8 .and. mode.eq.8) then
shared_data%params%lft8subpass = .true.
@@ -412,12 +508,9 @@ program jt9
shared_data%params%nsdecatt = 1
!print*,'lwidedxcsearch ',shared_data%params%lwidedxcsearch
end if
-!### temporary, for MAP65:
- if(mode.eq.66 .and. TRperiod.eq.60) shared_data%params%emedelay=2.5
+ ! emedelay (Q65 60s), datetime placeholder, and mode=9 nfa=fsplit
+ ! handled by init_default_params + apply_per_mode_policy above.
- datetime="2013-Apr-16 15:13" !### Temp
- shared_data%params%datetime=transfer(datetime,shared_data%params%datetime)
- if(mode.eq.9 .and. fsplit.ne.2700) shared_data%params%nfa=fsplit
nearly=50
if(mode.eq.8 .and. .not. shared_data%params%lmultift8) then
! "Early" decoding pass, FT8 only, when jt9 reads data from disk
@@ -509,5 +602,36 @@ program jt9
endif
call fftwf_cleanup_threads()
call fftwf_cleanup()
+ if (allocated(shared_data)) deallocate(shared_data)
+
+contains
+
+ subroutine require_integer(option, text, value)
+ character(len=*), intent(in) :: option, text
+ integer, intent(out) :: value
+
+ logical :: ok
+
+ call parse_integer(text, value, ok)
+ if (.not. ok) call invalid_option(option, text, 'must be an integer')
+ end subroutine require_integer
+
+ subroutine require_real(option, text, value)
+ character(len=*), intent(in) :: option, text
+ real(kind=8), intent(out) :: value
+
+ logical :: ok
+
+ call parse_real(text, value, ok)
+ if (.not. ok) call invalid_option(option, text, 'must be a finite number')
+ end subroutine require_real
+
+ subroutine invalid_option(option, text, reason)
+ character(len=*), intent(in) :: option, text, reason
+
+ write(error_unit, '(A)') 'jt9: invalid value for -' // trim(option) // ': ' // &
+ trim(text) // ' (' // trim(reason) // ')'
+ stop 2
+ end subroutine invalid_option
end program jt9
diff --git a/lib/jt9_input_validation.f90 b/lib/jt9_input_validation.f90
new file mode 100644
index 00000000..333fb30b
--- /dev/null
+++ b/lib/jt9_input_validation.f90
@@ -0,0 +1,158 @@
+module jt9_input_validation
+ use, intrinsic :: ieee_arithmetic, only: ieee_is_finite
+ implicit none
+
+ private
+ public :: parse_integer, parse_real, parse_wav_filename_nutc
+
+contains
+
+ subroutine parse_integer(text, value, ok)
+ character(len=*), intent(in) :: text
+ integer, intent(out) :: value
+ logical, intent(out) :: ok
+
+ integer :: ios
+
+ value = 0
+ if (.not. is_integer_token(text)) then
+ ok = .false.
+ return
+ end if
+ read(text, *, iostat=ios) value
+ ok = ios == 0
+ end subroutine parse_integer
+
+ subroutine parse_real(text, value, ok)
+ character(len=*), intent(in) :: text
+ real(kind=8), intent(out) :: value
+ logical, intent(out) :: ok
+
+ integer :: ios
+
+ value = 0.d0
+ if (.not. is_real_token(text)) then
+ ok = .false.
+ return
+ end if
+ read(text, *, iostat=ios) value
+ ok = ios == 0 .and. ieee_is_finite(value)
+ end subroutine parse_real
+
+ pure logical function is_integer_token(text)
+ character(len=*), intent(in) :: text
+
+ integer :: first
+
+ first = 1
+ if (len(text) > 0) then
+ if (text(1:1) == '+' .or. text(1:1) == '-') first = 2
+ end if
+ is_integer_token = first <= len(text) .and. &
+ verify(text(first:), '0123456789') == 0
+ end function is_integer_token
+
+ pure logical function is_real_token(text)
+ character(len=*), intent(in) :: text
+
+ integer :: digits, i, length
+
+ is_real_token = .false.
+ length = len(text)
+ if (length == 0) return
+
+ i = 1
+ if (text(i:i) == '+' .or. text(i:i) == '-') i = i + 1
+ if (i > length) return
+
+ digits = 0
+ do while (i <= length)
+ if (text(i:i) < '0' .or. text(i:i) > '9') exit
+ digits = digits + 1
+ i = i + 1
+ end do
+ if (i <= length) then
+ if (text(i:i) == '.') then
+ i = i + 1
+ do while (i <= length)
+ if (text(i:i) < '0' .or. text(i:i) > '9') exit
+ digits = digits + 1
+ i = i + 1
+ end do
+ end if
+ end if
+ if (digits == 0) return
+
+ if (i <= length) then
+ if (text(i:i) /= 'e' .and. text(i:i) /= 'E') return
+ i = i + 1
+ if (i <= length) then
+ if (text(i:i) == '+' .or. text(i:i) == '-') i = i + 1
+ end if
+ if (i > length) return
+ digits = 0
+ do while (i <= length)
+ if (text(i:i) < '0' .or. text(i:i) > '9') return
+ digits = digits + 1
+ i = i + 1
+ end do
+ if (digits == 0) return
+ end if
+
+ is_real_token = i > length
+ end function is_real_token
+
+ subroutine parse_wav_filename_nutc(filename, nutc)
+ character(len=*), intent(in) :: filename
+ integer, intent(out) :: nutc
+
+ integer :: dot, ios, length
+ character(len=:), allocatable :: stem
+
+ nutc = 0
+ length = len_trim(filename)
+ if (length == 0) return
+
+ dot = index(filename(:length), '.', back=.true.)
+ if (dot == 0) return
+ if (.not. is_wav_extension(filename(dot:length))) return
+
+ stem = filename(:dot - 1)
+ if (len(stem) >= 6) then
+ if (all_digits(stem(len(stem) - 5:))) then
+ read(stem(len(stem) - 5:), *, iostat=ios) nutc
+ if (ios == 0) return
+ end if
+ end if
+ if (len(stem) >= 5) then
+ if (stem(len(stem) - 4:len(stem) - 4) == '_' .and. &
+ all_digits(stem(len(stem) - 3:))) then
+ read(stem(len(stem) - 3:), *, iostat=ios) nutc
+ if (ios == 0) return
+ end if
+ end if
+ nutc = 0
+ end subroutine parse_wav_filename_nutc
+
+ pure logical function is_wav_extension(extension)
+ character(len=*), intent(in) :: extension
+
+ is_wav_extension = len(extension) == 4 .and. &
+ (extension == '.wav' .or. extension == '.WAV')
+ end function is_wav_extension
+
+ pure logical function all_digits(text)
+ character(len=*), intent(in) :: text
+
+ integer :: i
+
+ all_digits = len(text) > 0
+ do i = 1, len(text)
+ if (text(i:i) < '0' .or. text(i:i) > '9') then
+ all_digits = .false.
+ return
+ end if
+ end do
+ end function all_digits
+
+end module jt9_input_validation
diff --git a/lib/jt9_params_init.f90 b/lib/jt9_params_init.f90
new file mode 100644
index 00000000..782a7e12
--- /dev/null
+++ b/lib/jt9_params_init.f90
@@ -0,0 +1,241 @@
+! Shared params init — factored from WAV-path (jt9.f90:474-554),
+! stream-mode dispatch arm (jt9.f90:298-388), and streaming_io.f90:130-190.
+!
+! Eliminates the structural drift surface that arose from hand-copying
+! a baseline-init block into streaming_io.f90. Now both the WAV-decoder and
+! streaming-decoder paths route through one source of truth.
+!
+! Scope discipline:
+! - init_default_params sets ONLY fields the pre-refactor WAV path was
+! setting (the "common" subset). This preserves WAV byte-identical
+! behavior under run-golden-fixtures.sh — the regression gate.
+! - init_streaming_extra_fields sets the additional fields the pre-refactor
+! streaming dispatch arm (jt9.f90:298-388) set beyond the common set.
+! Streaming callers do init_default_params THEN init_streaming_extra_fields.
+! - The WAV multift8-only block at jt9.f90:519-554 stays inline (out of
+! scope). It sets some of the same fields init_streaming_extra_fields
+! sets, but with multift8-specific logic; not factored here.
+!
+! Public surface:
+! init_default_params(params, mode, TRperiod, args)
+! Common-subset init. Always called first.
+!
+! init_streaming_extra_fields(params, args)
+! Extra fields needed by the streaming subprocess path. Streaming
+! callers call this AFTER init_default_params.
+!
+! apply_per_mode_policy(params, mode, TRperiod)
+! Per-mode ntol cap + Q65 60s emedelay. Called from init_default_params,
+! and from streaming_apply's apply_configure_fields on mode/trperiod change.
+!
+! Per-mode invariants preserved (each documented inline at the policy site):
+! - FST4/FST4W (mode 241/242): ntol = min(ntol, 100)
+! - JT65+JT9 combined (mode 74): ntol hard = 20 unless -F supplied (have_ntol)
+! - Q65 (mode 66): ntol hard = 10 unless -F supplied; emedelay = 2.5 when TRperiod = 60
+! - All other modes: ntol = min(ntol, 1000)
+! - FST4 60s (mode 240): kin = 720000 (init-only; not in policy sub)
+! - JT9 with explicit -S<HZ> (mode 9 ∧ fsplit ≠ 2700): nfa = fsplit
+! (init-only; not in policy sub since fsplit isn't in apply_configure_fields'
+! scope today)
+
+module jt9_params_init
+ use, intrinsic :: iso_c_binding, only: c_int, c_short, c_float, c_char, c_bool
+
+ include 'jt9com.f90'
+
+ private
+ public :: init_default_params
+ public :: init_streaming_extra_fields
+ public :: apply_per_mode_policy
+ public :: cli_args_t
+
+ ! CLI-arg bundle threaded through to the params init. Defaults match
+ ! jt9.f90's local-var defaults (lines 30-32) so a bare call (with all
+ ! args at default) produces the same shape as un-flagged jt9 invocation.
+ type :: cli_args_t
+ integer :: flow = 200
+ integer :: fsplit = 2700
+ integer :: fhigh = 4000
+ integer :: nrxfreq = 1500
+ integer :: ndepth = 1
+ integer :: ntol = 1000 ! caller pre-clamps; per-mode policy applies on top
+ integer :: nQSOProg = 0
+ integer :: nexp_decode = 0
+ integer :: ncycles = 3
+ integer :: nft8rxfsens = 3
+ integer :: nmt = 0
+ integer :: ndecoderstart = 3
+ integer :: nsubmode = 0
+ character(len=12) :: mycall = ' '
+ character(len=12) :: hiscall = ' '
+ character(len=6) :: mygrid = ' '
+ character(len=6) :: hisgrid = ' '
+ character(len=20) :: datetime = '2026-Apr-25 00:00 '
+ logical :: tx9 = .false.
+ logical :: multift8 = .false.
+ logical :: hidedupes = .false.
+ logical :: lft8lowth = .true.
+ logical :: lft8subpass = .true.
+ logical :: lwidedxcsearch = .true.
+ logical :: have_ntol = .false. ! tracks whether -F was supplied
+ logical :: nexp_decode_set = .false. ! tracks whether --exp-decode was supplied
+ end type cli_args_t
+
+contains
+
+ ! Common-subset init. Sets the fields the pre-refactor WAV path was
+ ! setting, plus the per-mode policy outcomes (ntol cap, emedelay,
+ ! kin mode=240 override, nfa mode=9-fsplit override).
+ !
+ ! Caller-specific overrides happen AFTER the call:
+ ! - WAV path: nutc (filename), ndiskdat=.true., nzhsym=nhsym (per-period),
+ ! nmode=65+9 if mode=0
+ ! - Streaming dispatch: ndiskdat=.false. (default; jt9_stream overrides
+ ! via init_streaming_extra_fields side-effect or its own override)
+ subroutine init_default_params(params, mode, TRperiod, args)
+ type(params_block), intent(out) :: params
+ integer, intent(in) :: mode
+ real(8), intent(in) :: TRperiod
+ type(cli_args_t), intent(in) :: args
+
+ ! Common-subset structural defaults (preserves pre-refactor WAV scope).
+ params%nutc = 0 ! caller may overwrite (filename)
+ params%ndiskdat = .false. ! caller may overwrite
+ params%ntr = int(TRperiod)
+ params%nQSOProgress = args%nQSOProg
+ params%nfqso = args%nrxfreq
+ params%newdat = .true.
+ params%npts8 = 74736
+ params%nfa = args%flow
+ params%nfsplit = args%fsplit
+ params%nfb = args%fhigh
+ params%ntol = args%ntol ! per-mode policy applies below
+ params%kin = 64800 ! mode=240 override below
+ params%nzhsym = 50 ! caller may overwrite per-period
+ params%nsubmode = args%nsubmode
+ params%nagain = .false.
+ params%ndepth = args%ndepth
+ params%lft8apon = .true.
+ params%lapcqonly = .false.
+ params%ljt65apon = .true.
+ params%napwid = 75
+ if (args%tx9) then
+ params%ntxmode = 9
+ else
+ params%ntxmode = 65
+ end if
+ params%nmode = mode ! caller may overwrite (WAV mode=0 → 65+9)
+ params%nclearave = .false.
+ params%emedelay = 0.0 ! per-mode policy may override
+ params%dttol = 3.
+ params%n2pass = 2
+ params%nranera = 6
+ params%naggressive = 0
+ params%nrobust = .false.
+ params%nexp_decode = args%nexp_decode
+
+ params%datetime = transfer(args%datetime, params%datetime)
+ params%mycall = transfer(args%mycall, params%mycall)
+ params%mygrid = transfer(args%mygrid, params%mygrid)
+ params%hiscall = transfer(args%hiscall, params%hiscall)
+ params%hisgrid = transfer(args%hisgrid, params%hisgrid)
+
+ params%lmultift8 = args%multift8
+
+ ! Per-mode init-only adjustments (NOT folded into apply_per_mode_policy
+ ! because they reference CLI args (fsplit) or are mode-specific to a
+ ! degree the post-configure policy doesn't need to revisit).
+
+ ! FST4 60s period uses a larger sample window (jt9.f90:485 in WAV path).
+ if (mode .eq. 240) params%kin = 720000
+
+ ! JT9 with explicit -S<HZ>: remap nfa to fsplit (jt9.f90:386, :560).
+ if (mode .eq. 9 .and. args%fsplit .ne. 2700) params%nfa = args%fsplit
+
+ ! Init-time ntol cap (per-mode). Streaming-config-time ntol policy
+ ! lives in apply_configure_fields where it can branch on consumer-set vs
+ ! mode-default (see streaming_apply.f90).
+ if (mode .eq. 241 .or. mode .eq. 242) then
+ params%ntol = min(args%ntol, 100) ! FST4/FST4W
+ else if (mode .eq. 65 + 9 .and. .not. args%have_ntol) then
+ params%ntol = 20 ! JT65+JT9 hard (unless -F given)
+ else if (mode .eq. 66 .and. .not. args%have_ntol) then
+ params%ntol = 10 ! Q65 hard (unless -F given)
+ else
+ params%ntol = min(args%ntol, 1000) ! FT8/FT4/etc
+ end if
+
+ ! Q65 60s emedelay (the only piece left in apply_per_mode_policy
+ ! — ntol moved out).
+ call apply_per_mode_policy(params, mode, TRperiod)
+ end subroutine init_default_params
+
+ ! Streaming-only extras. Mirrors fields the pre-refactor stream-dispatch
+ ! arm (jt9.f90:298-388) set beyond the common set. NOT called by WAV
+ ! callers — those leave these fields at their bind(C) default state
+ ! (matching pre-refactor WAV behavior; the multift8-only block in WAV
+ ! will set a subset of these for multift8 mode).
+ subroutine init_streaming_extra_fields(params, args)
+ type(params_block), intent(inout) :: params
+ type(cli_args_t), intent(in) :: args
+
+ ! Tx-side companion to nfqso (WAV path leaves this uninit; streaming sets it).
+ params%nftx = args%nrxfreq
+
+ params%minw = 1
+ params%minsync = 0
+ params%nlist = 0
+ params%max_drift = 0
+ params%b_even_seq = .false.
+ params%b_superfox = .false.
+ params%lft8lowth = args%lft8lowth
+ params%lft8subpass = args%lft8subpass
+ params%lwidedxcsearch = args%lwidedxcsearch
+ params%lhound = .false.
+ params%lcommonft8b = .true.
+ params%lhideft8dupes = args%hidedupes
+ params%nft8cycles = args%ncycles
+ params%nft8rxfsens = args%nft8rxfsens
+ params%nmt = args%nmt
+ params%ndecoderstart = args%ndecoderstart
+ params%ncandthin = 100
+ params%ndtcenter = 0
+ params%nharmonicsdepth = 0
+ params%nprepass = 4
+ params%nsdecatt = 1
+ params%nlasttx = 0
+ params%ndelay = 0
+ params%nsecbandchanged = 0
+ params%nagainfil = .false.
+ params%nstophint = .false.
+ params%nhint = .false.
+ params%fmaskact = .false.
+ params%ltxing = .false.
+ params%lmycallstd = .true.
+ params%lhiscallstd = .true.
+ params%lapmyc = .false.
+ params%lmodechanged = .false.
+ params%lbandchanged = .false.
+ params%lenabledxcsearch= .true.
+ params%lmultinst = .false.
+ params%lskiptx1 = .false.
+ end subroutine init_streaming_extra_fields
+
+ ! Per-mode policy that runs both at init AND on configure-frame mode/trperiod
+ ! changes. Currently only Q65 60s emedelay (ntol was moved out since the
+ ! cap-vs-restore semantics differ between init and config-time).
+ ! Idempotent.
+ subroutine apply_per_mode_policy(params, mode, TRperiod)
+ type(params_block), intent(inout) :: params
+ integer, intent(in) :: mode
+ real(8), intent(in) :: TRperiod
+
+ ! Q65 60s mode requires 2.5s eme-delay; other modes 0.0.
+ if (mode .eq. 66 .and. TRperiod .eq. 60.d0) then
+ params%emedelay = 2.5
+ else
+ params%emedelay = 0.0
+ end if
+ end subroutine apply_per_mode_policy
+
+end module jt9_params_init
diff --git a/lib/jt9_version.c b/lib/jt9_version.c
new file mode 100644
index 00000000..daa7a248
--- /dev/null
+++ b/lib/jt9_version.c
@@ -0,0 +1,20 @@
+#include <stdio.h>
+
+#include "scs_version.h"
+#include "wsjtx_config.h"
+
+#ifndef JT9_PROGRAM_NAME
+#define JT9_PROGRAM_NAME "jt9"
+#endif
+
+void jt9_print_version(void)
+{
+ printf("%s %d.%d.%d%s", JT9_PROGRAM_NAME,
+ PROJECT_VERSION_MAJOR, PROJECT_VERSION_MINOR, PROJECT_VERSION_PATCH,
+ BUILD_TYPE_REVISION);
+ if (SCS_VERSION_STR[0] != '\0') {
+ printf(" (revision %s)\n", SCS_VERSION_STR);
+ } else {
+ puts(" (revision unavailable)");
+ }
+}
diff --git a/lib/jt9a.f90 b/lib/jt9a.f90
index 35f8c0c2..9daa8272 100644
--- a/lib/jt9a.f90
+++ b/lib/jt9a.f90
@@ -1,5 +1,12 @@
subroutine jt9a()
- use, intrinsic :: iso_c_binding, only: c_f_pointer, c_null_char, c_bool
+ use, intrinsic :: iso_c_binding, only: c_f_pointer, c_null_char, c_bool, c_sizeof, c_int
+ use decoder_ipc_atomic, only: decoder_ipc_control_try_claim, &
+ decoder_ipc_control_finish, decoder_ipc_progress_bind, &
+ decoder_ipc_progress_unbind, DECODER_IPC_CLAIM_INVALID, &
+ DECODER_IPC_CLAIM_INCOMPATIBLE, DECODER_IPC_CLAIM_NONE, &
+ DECODER_IPC_CLAIMED, DECODER_IPC_CLAIM_SHUTDOWN
+ use decode_completion_module, only: decode_completion_result, &
+ reset_decode_completion, set_decode_completion, write_decode_completion
use prog_args
use timer_module, only: timer
use timer_impl, only: init_timer !, limtrace
@@ -10,10 +17,13 @@ subroutine jt9a()
include 'jt9com.f90'
integer*2 id2a(180000)
+ save id2a !Keep this big array off the stack
! Multiple instances:
- type(dec_data), pointer, volatile :: shared_data !also makes target volatile
+ type(shared_dec_data), pointer, volatile :: shared_memory
type(params_block) :: local_params
logical(c_bool) :: ok
+ integer(c_int) :: active_generation, claim_result
+ type(decode_completion_result) :: completion
call init_timer (trim(data_dir)//'/timer.out')
! open(23,file=trim(data_dir)//'/CALL3.TXT',status='unknown')
@@ -25,49 +35,61 @@ subroutine jt9a()
ok=shmem_attach()
if(.not.ok) call abort
msdelay=10
- call c_f_pointer(shmem_address(),shared_data)
+ call c_f_pointer(shmem_address(),shared_memory)
+ nbytes=shmem_size()
+ if(nbytes.lt.c_sizeof(shared_memory)) then
+ ok=shmem_detach()
+ print*,'jt9a: Incompatible shared-memory layout.'
+ go to 999
+ endif
-! Terminate if ipc(2) is 999
-10 ok=shmem_lock()
- if(.not.ok) call abort
- if(shared_data%ipc(2).eq.999.0) then
- ok=shmem_unlock()
+ call decoder_ipc_progress_bind(shared_memory%control%generation, &
+ shared_memory%control%state, shared_memory%control%version, &
+ shared_memory%control%progress)
+
+ call reset_decode_completion(completion)
+
+10 claim_result=decoder_ipc_control_try_claim( &
+ shared_memory%control%generation, shared_memory%control%state, &
+ shared_memory%control%version, active_generation)
+ if(claim_result.eq.DECODER_IPC_CLAIM_SHUTDOWN) then
ok=shmem_detach()
go to 999
- endif! Wait here until GUI has set ipc(2) to 1
- if(shared_data%ipc(2).ne.1) then
- ok=shmem_unlock()
- if(.not.ok) call abort
- call sleep_msec(msdelay)
- go to 10
endif
- shared_data%ipc(2)=0
- nbytes=shmem_size()
- if(nbytes.le.0) then
- ok=shmem_unlock()
+ if(claim_result.eq.DECODER_IPC_CLAIM_INCOMPATIBLE) then
ok=shmem_detach()
- print*,'jt9a: Shared memory does not exist.'
- print*,"Must start 'jt9 -s <thekey>' from within WSJT-X."
+ print*,'jt9a: Incompatible shared-memory protocol version.'
go to 999
endif
- local_params=shared_data%params !save a copy because wsjtx carries on accessing
- ok=shmem_unlock()
- if(.not.ok) call abort
+ if(claim_result.eq.DECODER_IPC_CLAIM_INVALID) then
+ ok=shmem_detach()
+ print*,'jt9a: Invalid decoder request generation.'
+ go to 999
+ endif
+ if(claim_result.eq.DECODER_IPC_CLAIM_NONE) then
+ call sleep_msec(msdelay)
+ go to 10
+ endif
+ if(claim_result.ne.DECODER_IPC_CLAIMED) call abort
+ write(*,'(a,i0)') '<DecodeStarted> gen=',active_generation
call flush(6)
+ local_params=shared_memory%payload%params
call timer('decoder ',0)
if(local_params%nmode.eq.8 .and. local_params%ndiskdat .and. &
.not. local_params%nagain .and. .not. local_params%lmultift8) then
! Early decoding pass, FT8 only, when wsjtx reads from disk
nearly=41
local_params%nzhsym=nearly
- id2a(1:nearly*3456)=shared_data%id2(1:nearly*3456)
+ id2a(1:nearly*3456)=shared_memory%payload%id2(1:nearly*3456)
id2a(nearly*3456+1:)=0
- call multimode_decoder(shared_data%ss,id2a,local_params,12000)
+ call multimode_decoder_core(shared_memory%payload%ss,id2a,local_params, &
+ 12000,completion,active_generation)
nearly=47
local_params%nzhsym=nearly
- id2a(1:nearly*3456)=shared_data%id2(1:nearly*3456)
+ id2a(1:nearly*3456)=shared_memory%payload%id2(1:nearly*3456)
id2a(nearly*3456+1:)=0
- call multimode_decoder(shared_data%ss,id2a,local_params,12000)
+ call multimode_decoder_core(shared_memory%payload%ss,id2a,local_params, &
+ 12000,completion,active_generation)
local_params%nzhsym=50
endif
@@ -79,58 +101,63 @@ subroutine jt9a()
nearly=41
local_params%lmultift8=.false.
local_params%nzhsym=nearly
- id2a(1:nearly*3456)=shared_data%id2(1:nearly*3456)
+ id2a(1:nearly*3456)=shared_memory%payload%id2(1:nearly*3456)
id2a(nearly*3456+1:)=0
- call multimode_decoder(shared_data%ss,id2a,local_params,12000)
+ call multimode_decoder_core(shared_memory%payload%ss,id2a,local_params, &
+ 12000,completion,active_generation)
if(local_params%ndecoderstart.lt.2) then
nearly=46
local_params%lmultift8=.false.
local_params%nzhsym=nearly
- id2a(1:nearly*3456)=shared_data%id2(1:nearly*3456)
+ id2a(1:nearly*3456)=shared_memory%payload%id2(1:nearly*3456)
id2a(nearly*3456+1:)=0
- call multimode_decoder(shared_data%ss,id2a,local_params,12000)
+ call multimode_decoder_core(shared_memory%payload%ss,id2a,local_params, &
+ 12000,completion,active_generation)
endif
if(local_params%ndecoderstart.eq.0) nearly=49
if(local_params%ndecoderstart.eq.1) nearly=50
local_params%lmultift8=.true.
- shared_data%params%nzhsym=nearly
- id2a(1:nearly*3456)=shared_data%id2(1:nearly*3456)
+ shared_memory%payload%params%nzhsym=nearly
+ id2a(1:nearly*3456)=shared_memory%payload%id2(1:nearly*3456)
id2a(nearly*3456+1:)=0
- dd(1:nearly*3456)=shared_data%id2(1:nearly*3456)
+ dd(1:nearly*3456)=shared_memory%payload%id2(1:nearly*3456)
dd(nearly*3456+1:)=0
- dd8(1:nearly*3456)=shared_data%id2(1:nearly*3456)
+ dd8(1:nearly*3456)=shared_memory%payload%id2(1:nearly*3456)
dd8(nearly*3456+1:)=0
- if(local_params%ndecoderstart.eq.0) shared_data%params%nzhsym=49
- if(local_params%ndecoderstart.eq.1) shared_data%params%nzhsym=50
+ if(local_params%ndecoderstart.eq.0) shared_memory%payload%params%nzhsym=49
+ if(local_params%ndecoderstart.eq.1) shared_memory%payload%params%nzhsym=50
else
nearly=50
if(local_params%ndecoderstart.eq.2) nearly=48
if(local_params%ndecoderstart.eq.3) nearly=49
if(local_params%ndecoderstart.eq.4) nearly=50
- shared_data%params%nzhsym=nearly
- id2a(1:nearly*3456)=shared_data%id2(1:nearly*3456)
+ shared_memory%payload%params%nzhsym=nearly
+ id2a(1:nearly*3456)=shared_memory%payload%id2(1:nearly*3456)
id2a(nearly*3456+1:)=0
- dd(1:nearly*3456)=shared_data%id2(1:nearly*3456)
+ dd(1:nearly*3456)=shared_memory%payload%id2(1:nearly*3456)
dd(nearly*3456+1:)=0
- dd8(1:nearly*3456)=shared_data%id2(1:nearly*3456)
+ dd8(1:nearly*3456)=shared_memory%payload%id2(1:nearly*3456)
dd8(nearly*3456+1:)=0
- if(local_params%ndecoderstart.eq.2) shared_data%params%nzhsym=48
- if(local_params%ndecoderstart.eq.3) shared_data%params%nzhsym=49
- if(local_params%ndecoderstart.eq.4) shared_data%params%nzhsym=50
+ if(local_params%ndecoderstart.eq.2) shared_memory%payload%params%nzhsym=48
+ if(local_params%ndecoderstart.eq.3) shared_memory%payload%params%nzhsym=49
+ if(local_params%ndecoderstart.eq.4) shared_memory%payload%params%nzhsym=50
endif
elseif (local_params%nmode.eq.8 .and. local_params%lmultift8 .and. .not. &
local_params%ndiskdat) then
- dd(1:npts1)=shared_data%id2(1:npts1)
+ npts1=min(180000,local_params%nzhsym*3456)
+ dd(1:npts1)=shared_memory%payload%id2(1:npts1)
+ dd(npts1+1:)=0
rms=sum(abs(dd(1:10))) + sum(abs(dd(76001:76010))) + sum(abs(dd(151670:151680)))
dd8(1:npts1)=dd(1:npts1)
+ dd8(npts1+1:)=0
!### WHY WAS THIS STUFF HERE ??? ###
! if(rms.gt.0.001) then
-! dd(1:npts1)=shared_data%dd2(1:npts1)
+! dd(1:npts1)=shared_memory%payload%dd2(1:npts1)
! dd8(1:npts1)=dd(1:npts1)
!print *,'win7',rms
! else ! workaround for zero data values of dd2 array under WinXP
-! dd(1:npts1)=shared_data%id2(1:npts1)
+! dd(1:npts1)=shared_memory%payload%id2(1:npts1)
! dd8(1:npts1)=dd(1:npts1)
!print *, 'winxp',rms
! endif
@@ -140,30 +167,30 @@ subroutine jt9a()
if(local_params%nmode .eq. 144) then
! MSK144
- call decode_msk144(shared_data%id2, shared_data%params, data_dir)
+ call decode_msk144_core(shared_memory%payload%id2, local_params, data_dir, &
+ completion)
else
! Normal decoding pass
- call multimode_decoder(shared_data%ss,shared_data%id2,local_params,12000)
+ call multimode_decoder_core(shared_memory%payload%ss, &
+ shared_memory%payload%id2,local_params,12000,completion,active_generation)
endif
call timer('decoder ',1)
-!print*,time, ' jt9a before final loop which waits for ipc(3) ==1' !ft8md
-! Wait here until GUI routine decodeDone() has set ipc(3) to 1
-100 ok=shmem_lock()
- if(.not.ok) call abort
- if(shared_data%ipc(3).ne.1) then
- ok=shmem_unlock()
- if(.not.ok) call abort
- call sleep_msec(msdelay)
- go to 100
+ if(.not.completion%available) then
+ call set_decode_completion(completion,0,0,0)
+ endif
+ claim_result=decoder_ipc_control_finish(shared_memory%control%generation, &
+ shared_memory%control%state, shared_memory%control%version, &
+ active_generation)
+ if(claim_result.ne.0) then
+ call write_decode_completion(completion,active_generation)
+ call flush(6)
endif
- shared_data%ipc(3)=0
- ok=shmem_unlock()
- if(.not.ok) call abort
go to 10
-999 call timer('decoder ',101)
+999 call decoder_ipc_progress_unbind()
+ call timer('decoder ',101)
return
end subroutine jt9a
diff --git a/lib/jt9a_stub.f90 b/lib/jt9a_stub.f90
new file mode 100644
index 00000000..ca06055f
--- /dev/null
+++ b/lib/jt9a_stub.f90
@@ -0,0 +1,12 @@
+! Headless stub for jt9a(): the GUI shared-memory worker loop (lib/jt9a.f90)
+! is excluded from headless builds so jt9 links zero Qt (the real jt9a
+! depends on QSharedMemory). The headless jt9 is driven by `--stream`
+! or a WAV file; the GUI-worker entry is unreachable in normal use. If reached
+! (bare `jt9` with no --stream and no input file), fail clean with a diagnostic
+! instead of attaching shared memory (which the real jt9a aborts on).
+subroutine jt9a()
+ use, intrinsic :: iso_fortran_env, only: error_unit
+ write(error_unit,'(a)') 'jt9: GUI shared-memory worker mode is not available '// &
+ 'in the headless build. Use `jt9 --stream` or `jt9 <file.wav>`.'
+ stop 2
+end subroutine jt9a
diff --git a/lib/jt9com.f90 b/lib/jt9com.f90
index dc955479..fc0577a2 100644
--- a/lib/jt9com.f90
+++ b/lib/jt9com.f90
@@ -1,14 +1,28 @@
use, intrinsic :: iso_c_binding, only: c_int, c_short, c_float, c_char, c_bool
include 'constants.f90'
+ integer(c_int), parameter :: DECODER_IPC_VERSION = 2
+ integer(c_int), parameter :: DECODER_IPC_IDLE = 0
+ integer(c_int), parameter :: DECODER_IPC_READY = 1
+ integer(c_int), parameter :: DECODER_IPC_DECODING = 2
+ integer(c_int), parameter :: DECODER_IPC_COMPLETE = 3
+ integer(c_int), parameter :: DECODER_IPC_SHUTDOWN = 999
+
!
! these structures must be kept in sync with ../commons.h
!
+ type, bind(C) :: decoder_ipc_control
+ integer(c_int) :: generation
+ integer(c_int) :: state
+ integer(c_int) :: version
+ integer(c_int) :: progress
+ end type decoder_ipc_control
+
type, bind(C) :: params_block
integer(c_int) :: nutc
logical(c_bool) :: ndiskdat
integer(c_int) :: ntr
- integer(c_int) :: nQSOProgress ! See MainWindow::m_QSOProgress for values
+ integer(c_int) :: nQSOProgress ! Values are defined by ../QsoProgress.hpp
integer(c_int) :: nfqso
integer(c_int) :: nftx
logical(c_bool) :: newdat
@@ -92,10 +106,14 @@
end type params_block
type, bind(C) :: dec_data
- integer(c_int) :: ipc(3)
real(c_float) :: ss(184,NSMAX)
real(c_float) :: savg(NSMAX)
real(c_float) :: sred(5760)
integer(c_short) :: id2(NMAX)
type(params_block) :: params
end type dec_data
+
+ type, bind(C) :: shared_dec_data
+ type(decoder_ipc_control) :: control
+ type(dec_data) :: payload
+ end type shared_dec_data
diff --git a/lib/jt9sim.f90 b/lib/jt9sim.f90
index e195b40b..04f3f11a 100644
--- a/lib/jt9sim.f90
+++ b/lib/jt9sim.f90
@@ -87,7 +87,7 @@ program jt9sim
imin=mod(nmin,60)
write(fname,1002) ihr,imin !Create output filename
1002 format('000000_',2i2.2)
- open(10,file=fname//'.wav',access='stream',status='unknown')
+ open(10,file=fname//'.wav',access='stream',status='replace')
if(snrdb.lt.90) then
do i=1,npts
diff --git a/lib/jtty/JTTY Messages.mc b/lib/jtty/JTTY Messages.mc
new file mode 100644
index 00000000..7b0b91ea
--- /dev/null
+++ b/lib/jtty/JTTY Messages.mc
@@ -0,0 +1,44 @@
+#
+# Digital Function Key File Example for JTTY use
+#
+# See the discussion in the accompanying jtty_n1mm_integration.md file
+# The leading [[JTTY:ACTION]] marker opts into native Call8/STRUCT30 encoding.
+# Untagged N1MM text uses automatic packing after exchange-profile normalization.
+#
+# S&P F1 calls CQ and automatically places the program in RUN Mode
+# F2 F3 F4 F5 use "!" macro for his callsign
+# Exchange actions use the active JTTY profile; do not hardcode 599.
+# Run F11 remains spare until N1MM call-stack TXTEXT ordering is validated.
+#
+###################
+# RUN Messages
+###################
+F1 Run CQ,{TX}[[JTTY:CQ]]{MYCALL}{RX}
+F2 Run Exch,{TX}[[JTTY:CALL_EXCH]]! {EXCH}{RX}
+F3 Run TU,{TX}[[JTTY:CALL_TU_CQ]]! {MYCALL}{RX}
+F4 {MYCALL},{TX}[[JTTY:MYCALL]]{MYCALL}{RX}
+F5 His Call,{TX}[[JTTY:HISCALL]]!{RX}
+F6 NR?,{TX}[[JTTY:CONTROL]]NR?{RX}
+F7 Spare,
+F8 Agn?,{TX}[[JTTY:CONTROL]]AGN?{RX}
+F9 Spare,
+F10 Spare,
+F11 Spare,
+F12 Wipe,{WIPE}
+#
+###################
+# S&P Messages
+###################
+# "&" doubled, displays one "&" in the button label
+F1 S&&P CQ,{TX}[[JTTY:CQ]]{MYCALL}{RX}
+F2 S&&P Exch,{TX}[[JTTY:CALL_EXCH]]! {EXCH}{RX}
+F3 S&&P TU,{TX}[[JTTY:CALL_TU_MY]]! {MYCALL}{RX}
+F4 S&&P Call Him,{TX}[[JTTY:CALL_MY]]! {MYCALL}{RX}
+F5 His Call,{TX}[[JTTY:HISCALL]]!{RX}
+F6 {MYCALL},{TX}[[JTTY:MYCALL]]{MYCALL}{RX}
+F7 My Exch,{TX}[[JTTY:EXCH]]{EXCH}{RX}
+F8 Agn?,{TX}[[JTTY:CONTROL]]AGN?{RX}
+F9 Spare,
+F10 Spare,
+F11 Spare,
+F12 Wipe,{WIPE}
diff --git a/lib/jtty/ana64a.f90 b/lib/jtty/ana64a.f90
new file mode 100644
index 00000000..fe7c7fb8
--- /dev/null
+++ b/lib/jtty/ana64a.f90
@@ -0,0 +1,19 @@
+subroutine ana64a(iwave,npts,c0,nfft1)
+ implicit none
+ integer*2, intent(in) :: iwave(npts) !Raw data at 12000 Hz
+ integer, intent(in) :: npts, nfft1
+ integer :: nfft2
+ real :: fac
+ complex, intent(out) :: c0(0:nfft1-1)
+
+ nfft2=nfft1/2
+ fac=2.0/(32767.0*NFFT1)
+ c0(0:npts-1)=fac*iwave(1:npts)
+ c0(npts:)=0.
+ call four2a(c0,NFFT1,1,-1,1) !Forward c2c FFT
+ c0(nfft2/2+1:nfft2-1)=0. !Set negative freqs to 0.
+ c0(0)=0.5*c0(0)
+ call four2a(c0,nfft2,1,1,1) !Inverse c2c FFT; c0 is the analytic sig
+ c0(npts:)=0.
+ return
+end subroutine ana64a
diff --git a/lib/jtty/c_funcs.f90 b/lib/jtty/c_funcs.f90
new file mode 100644
index 00000000..3c21cf16
--- /dev/null
+++ b/lib/jtty/c_funcs.f90
@@ -0,0 +1,13 @@
+MODULE c_funcs
+
+ USE, INTRINSIC :: ISO_C_BINDING
+ IMPLICIT NONE
+
+ INTERFACE
+ ! Use BIND(C, name="putc") to link to the C library function
+ FUNCTION c_putc(character) BIND(C, name="putchar")
+ INTEGER(C_INT) :: c_putc
+ END FUNCTION c_putc
+ END INTERFACE
+
+ END MODULE C_Funcs
diff --git a/lib/ft2/cdatetime.f90 b/lib/jtty/cdatetime.f90
index 33deaf30..33deaf30 100644
--- a/lib/ft2/cdatetime.f90
+++ b/lib/jtty/cdatetime.f90
diff --git a/lib/jtty/decodes.txt b/lib/jtty/decodes.txt
new file mode 100644
index 00000000..ed82f996
--- /dev/null
+++ b/lib/jtty/decodes.txt
@@ -0,0 +1,463 @@
+ 0 1 1 1 F 1501.2 0.264 1.536 -11 ~~~~~
+ 0 2 2 2 F 1501.7 0.101 15.789 0 CQ K1JT CQ
+ 0 3 3 3 F 1502.2 0.315 24.483 6 K1JT
+ 0 4 3 3 T 1502.2 0.313 26.177 5 599 0004~
+ 0 5 4 4 F 1502.2 0.202 30.730 8 AA5AU
+ 0 6 5 5 F 1502.2 0.061 73.413 4 AA5AU
+ 0 7 6 6 F 1502.2 0.352 84.728 7 AA5AU
+ 0 8 7 7 F 1502.2 0.259 109.227 5 AA5AU
+ 0 9 8 8 F 1518.3 0.271 135.527 -8 CQ W1UE CQ
+ 0 10 9 9 F 1502.2 0.169 151.113 4 ONLY~
+ 0 11 9 9 T 1502.2 0.168 152.808 12 DECOD
+ 0 12 9 9 T 1502.2 0.168 154.504 10 ED~YO
+ 0 13 9 9 T 1502.2 0.169 156.201 16 UR~FI
+ 0 14 9 9 T 1502.2 0.168 157.896 8 RST~C
+ 0 15 9 9 T 1502.2 0.167 159.591 14 Q~~~~
+ 0 16 10 10 F 1502.2 0.157 172.301 13 DID~N
+ 0 17 10 10 T 1502.2 0.156 173.996 14 OT~DE
+ 0 18 10 10 T 1502.2 0.159 175.695 1 CODE~
+
+ 0 1 1 1 F 1515.4 0.173 8.229 -7 CQ W1UE CQ
+ 0 2 2 2 F 1502.2 0.347 16.035 14 NO~DE
+ 0 3 2 2 T 1502.2 0.347 17.731 13 CODE~
+ 14 4 3 3 F 2705.6 0.380 48.716 -14
+ 0 5 4 4 F 1502.2 0.117 60.325 2 CQ AA5AU CQ
+ 0 6 5 5 F 1517.9 0.199 65.919 -11 IS~TH
+ 0 7 5 5 T 1515.4 0.199 67.615 -7 IS~DE
+ 0 8 5 5 T 1515.8 0.199 69.311 -8 CODIN
+ 0 9 6 6 F 1502.2 0.392 74.592 7 YES~~
+ 0 10 7 7 F 1515.8 0.163 84.539 -9 CQ W1UE CQ
+ 0 11 8 8 F 1502.7 0.155 92.587 5 AA5AU
+ 0 12 2 8 T 1502.2 0.346 102.530 12 W1UE
+ 0 13 2 8 T 1502.2 0.345 104.225 13 599 0004~
+ 0 14 9 9 F 1518.3 0.220 118.940 -11 599 0008~
+ 0 15 10 10 F 1502.2 0.203 124.011 12 TU NOW W1UE
+ 0 16 10 10 T 1502.7 0.203 125.707 8 599 0004~
+ 0 17 11 11 F 1516.8 0.254 128.726 -9 TU W1UE CQ
+
+ 0 1 1 1 F 1514.3 0.357 30.037 -10 CQ W1UE CQ
+ 0 2 2 2 F 1502.7 0.227 35.419 1 AA5AU
+ 0 3 3 3 F 1516.8 0.186 39.194 -9 CQ W1UE CQ
+ 0 4 4 4 F 1502.7 0.191 47.255 7 AGN?~
+ 0 5 5 5 F 1502.2 0.405 55.525 -13 AGN?~
+ 0 6 6 6 F 1514.9 0.196 70.580 -9 AA5AU
+ 0 7 7 7 F 1502.7 0.017 79.305 11 599 0005~
+ 0 8 8 8 F 1502.7 0.321 97.841 12 I~HAV
+ 0 9 8 8 T 1502.2 0.320 99.536 14 E~STR
+ 0 10 8 8 T 1502.7 0.319 101.231 10 ONG~S
+ 0 11 8 8 T 1502.7 0.320 102.928 12 SB~QR
+ 0 12 8 8 T 1502.2 0.319 104.623 12 M~~~~
+ 0 13 9 9 F 1514.8 0.123 124.355 -7 R~IT~
+ 0 14 9 9 T 1517.4 0.127 126.055 -11 BUT~N
+ 0 15 9 9 T 1515.8 0.128 127.752 -6 OT~ST
+ 0 16 10 10 F 1502.7 0.159 138.807 -3 NOT~B
+ 0 17 10 10 T 1502.7 0.160 140.504 15 OTHER
+ 0 18 10 10 T 1502.7 0.160 142.200 16 NING~
+ 0 19 10 10 T 1502.7 0.160 143.896 16 DECOD
+ 0 20 10 10 T 1502.7 0.161 145.593 15 E~NOW
+ 0 21 11 11 F 1515.4 0.267 152.059 -11 Y~YOU
+ 0 22 11 11 T 1517.8 0.266 153.754 -10 ~CAN'
+ 0 23 11 11 T 1514.8 0.267 155.451 -12 T~COP
+ 0 24 12 12 F 1502.7 0.283 161.403 10 NOT~S
+ 0 25 12 12 T 1502.7 0.281 163.097 1 URE~~
+ 0 26 13 13 F 1519.3 0.129 168.033 -10 CQ W1UE CQ
+
+ 0 1 1 1 F 1517.8 0.175 9.927 -11 W1UE
+ 0 2 2 2 F 1501.7 0.358 17.742 6 AA5AU
+ 0 3 2 2 T 1501.7 0.357 19.437 14 599 0001~
+ 0 4 3 3 F 1502.7 0.415 25.855 14 599 0005~
+ 0 5 4 4 F 1497.4 0.000 25.864 -10 599 0005~
+ 0 6 5 5 F 1501.7 0.125 37.013 2 TU WV4P CQ
+ 0 7 6 6 F 1502.2 0.215 45.583 4 U~QTC
+ 0 8 6 6 T 1501.7 0.214 47.278 10 ~FOR~
+ 0 9 6 6 T 1501.7 0.214 48.974 16 ME~?~
+ 0 10 7 7 F 1501.7 0.107 76.427 12 CQ WV4P CQ
+ 0 11 8 8 F 1515.8 0.404 80.540 -11 W1UE
+ 0 12 9 9 F 1501.7 0.026 86.098 3 CQ WV4P CQ
+ 0 13 2 9 T 1501.7 0.359 100.423 1 CQ WV4P CQ
+ 0 14 10 10 F 1517.9 0.069 104.797 -13 W1UE
+ 0 15 11 11 F 1517.3 0.267 116.867 -10 WV4P
+ 0 16 11 11 T 1516.8 0.264 118.560 -7 W1UE~
+ 0 17 12 12 F 1502.2 0.178 125.258 2 ~~~~~
+ 0 18 13 13 F 1516.8 0.296 134.704 -13 CODE~
+ 0 19 14 14 F 1502.7 0.101 141.717 5 CQ AA5AU CQ
+ 0 20 5 14 T 1502.2 0.121 144.705 1 YOU~Q
+ 0 21 5 14 T 1502.2 0.121 146.401 15 TC~FO
+ 0 22 5 14 T 1502.2 0.121 148.097 16 R~ME~
+ 0 23 5 14 T 1502.2 0.121 149.793 16 ?~~~~
+ 0 24 15 15 F 1502.7 0.086 165.022 15 CQ AA5AU CQ
+ 0 25 16 16 F 1515.8 0.393 169.993 -7 W1UE
+
+ 0 1 1 1 F 1517.8 0.164 21.364 -11 BE~BA
+ 0 2 1 1 T 1513.9 0.162 23.058 -9 CK~IN
+ 0 3 1 1 T 1517.8 0.164 26.452 -11 NUTE~
+ 0 4 2 2 F 1502.2 0.067 39.075 14 AWESO
+ 0 5 2 2 T 1502.2 0.066 40.770 15 ME~ME
+ 0 6 2 2 T 1502.2 0.066 42.466 15 ~TOO~
+ 0 7 2 2 T 1502.2 0.066 44.162 16 !~~~~
+ 0 8 3 3 F 1502.7 0.377 52.529 8 73~AA
+ 0 9 3 3 T 1503.2 0.377 54.225 14 5AU~~
+ 0 10 2 3 T 1503.2 0.068 102.676 14 TU AA5AU CQ
+ 0 11 4 4 F 1516.8 0.157 112.093 -11 W1UE
+ 0 12 5 5 F 1503.2 0.144 118.440 1 W1UE
+ 0 13 5 5 T 1503.2 0.144 120.136 13 599 0007~
+ 0 14 6 6 F 1515.3 0.339 125.419 -11 599 010~~
+ 0 15 7 7 F 1503.2 0.351 128.823 16 TU AA5AU CQ
+ 0 16 8 8 F 1503.2 0.262 143.150 4 AA5AU
+
+ 0 1 1 1 F 1515.9 0.215 7.847 -12 CQ W1UE CQ
+ 0 2 2 2 F 1503.2 0.353 17.737 16 AA5AU
+ 0 3 3 3 F 1503.2 0.064 45.432 17 AGN?~
+ 0 4 4 4 F 1503.2 0.321 55.441 16 AGN?~
+ 0 5 5 5 F 1503.2 0.315 76.211 4 NO~DE
+ 0 6 5 5 T 1503.2 0.315 77.907 15 CODE~
+ 0 7 5 5 T 1503.2 0.315 79.603 16 QRX~W
+ 0 8 5 5 T 1503.2 0.315 81.299 16 ILL~R
+ 0 9 5 5 T 1503.2 0.315 82.995 15 ESTAR
+ 0 10 5 5 T 1503.2 0.315 84.691 16 T~~~~
+ 0 11 6 6 F 1503.2 0.161 135.417 14 CQ AA5AU CQ
+ 0 12 7 7 F 1515.3 0.334 149.158 -11 W1UE
+ 0 13 8 8 F 1503.2 0.020 156.900 16 W1UE
+ 0 14 8 8 T 1503.2 0.020 158.596 16 599 0008~
+ 0 15 9 9 F 1516.8 0.240 165.176 -10 599 010~~
+ 0 16 10 10 F 1503.2 0.190 172.334 5 TU AA5AU CQ
+
+ 0 1 1 1 F 1503.2 0.133 3.101 8 AA5AU
+ 0 2 2 2 F 1514.8 0.093 11.965 -11 599 011~~
+ 0 3 3 3 F 1503.2 0.362 15.626 15 W1UE
+ 0 4 3 3 T 1503.7 0.361 17.321 16 599 0009~
+ 0 5 4 4 F 1517.4 0.273 21.897 -12 TU W1UE CQ
+ 0 6 5 5 F 1517.4 0.019 30.971 -13 CQ W1UE CQ
+ 0 7 6 6 F 1515.8 0.071 45.439 -10 CQ W1UE CQ
+ 0 8 7 7 F 1503.7 0.343 63.943 16 WHEN~
+ 0 9 7 7 T 1503.7 0.343 65.639 16 I~STO
+ 0 10 7 7 T 1503.2 0.343 67.335 16 P~DEC
+ 0 11 7 7 T 1503.7 0.343 69.031 15 ODING
+ 0 12 7 7 T 1503.7 0.343 70.727 16 ~I~HA
+ 0 13 7 7 T 1503.7 0.343 72.423 16 VE~TO
+ 0 14 7 7 T 1503.7 0.343 74.119 16 ~REST
+ 0 15 7 7 T 1503.7 0.343 75.815 16 ART~P
+ 0 16 7 7 T 1503.7 0.343 77.511 16 GM~~~
+ 0 17 8 8 F 1515.4 0.259 92.691 -12 W1UE
+ 0 18 9 9 F 1513.9 0.352 95.752 -10 W1UE
+ 0 19 6 9 T 1515.8 0.074 98.442 -12 W1UE
+ 0 20 10 10 F 1515.3 0.305 110.969 -10 CQ W1UE CQ
+ 0 21 3 10 T 1503.7 0.361 118.233 4 AA5AU
+ 0 22 11 11 F 1518.3 0.136 129.456 -8 AA5AU
+ 0 23 11 11 T 1515.4 0.136 131.152 -10 599 012~~
+ 0 24 12 12 F 1503.7 0.051 136.155 14 599 0009~
+ 0 25 13 13 F 1516.3 0.110 141.726 -11 TU W1UE CQ
+ 0 26 14 14 F 1503.7 0.083 169.683 6 AA5AU
+ 0 27 8 14 T 1517.8 0.257 174.945 -8 AA5AU
+ 0 28 8 14 T 1515.3 0.255 176.639 -12 599 013~~
+
+ 0 1 1 1 F 1503.7 0.146 0.994 13 W1UE
+ 0 2 1 1 T 1503.7 0.145 2.689 15 599 0009~
+ 0 3 2 2 F 1516.8 0.124 6.484 -7 TU W1UE CQ
+ 0 4 3 3 F 1516.8 0.000 32.224 -9 DID~U
+ 0 5 3 3 T 1519.3 0.002 33.922 -13 ~DECO
+ 0 6 4 4 F 1514.3 0.415 37.303 -11 L~3~M
+ 0 7 3 4 T 1516.4 0.000 39.008 -12 ESSAG
+ 0 8 3 4 T 1516.9 0.004 40.708 -9 ES~FO
+ 0 9 5 5 F 1503.7 0.059 47.123 11 YES~~
+ 0 10 6 6 F 1519.3 0.085 58.173 -12 GOOD!
+ 0 11 7 7 F 1503.7 0.219 66.363 10 TU AA5AU CQ
+ 0 12 8 8 F 1517.9 0.007 70.815 -12 W1UE
+ 0 13 9 9 F 1503.7 0.315 78.755 14 599 010~~
+ 0 14 10 10 F 1503.7 0.347 86.843 13 TU AA5AU CQ
+ 0 15 11 11 F 1517.3 0.354 91.090 -10 AA5AU
+ 0 16 12 12 F 1503.7 0.202 102.386 14 CQ AA5AU CQ
+ 0 17 6 12 T 1517.3 0.083 106.931 -9 W1UE
+ 0 18 13 13 F 1503.7 0.192 110.432 4 W1UE
+ 0 19 13 13 T 1503.7 0.192 112.128 16 599 011~~
+ 0 20 14 14 F 1515.3 0.246 115.574 -9 599 014~~
+ 0 21 12 14 T 1503.7 0.201 118.073 10 TU AA5AU CQ
+ 0 22 15 15 F 1514.3 0.213 124.021 -12 W1UE
+ 0 23 16 16 F 1503.7 0.231 129.127 3 AA5AU
+ 0 24 17 17 F 1516.4 0.138 135.394 -10 W1UE
+ 0 25 18 18 F 1503.7 0.116 145.972 14 DID~G
+ 0 26 18 18 T 1503.7 0.115 147.667 13 ET~TH
+ 0 27 18 18 T 1503.7 0.115 149.363 14 AT~LA
+ 0 28 18 18 T 1503.2 0.116 151.060 13 ST~TX
+ 0 29 19 19 F 1517.9 0.062 156.518 -13 GETTI
+ 0 30 20 20 F 1517.3 0.055 159.903 -11 ~CLIC
+ 0 31 20 20 T 1514.9 0.054 161.598 -8 K~ON~
+ 0 32 20 20 T 1515.3 0.054 163.294 -8 YOUR~
+ 0 33 12 20 T 1503.7 0.206 170.230 7 RRR~~
+
+ 0 1 1 1 F 1503.2 0.219 4.883 6 YOUR~
+ 0 2 1 1 T 1503.7 0.219 6.579 16 CALL~
+ 0 3 1 1 T 1503.2 0.219 8.275 16 STAYS
+ 0 4 1 1 T 1502.7 0.220 9.972 14 ~IN~D
+ 0 5 1 1 T 1503.7 0.219 11.667 14 X~CAL
+ 0 6 1 1 T 1503.2 0.219 13.363 16 L~BOX
+ 0 7 2 2 F 1514.3 0.334 25.350 -11 NOT~I
+ 0 8 2 2 T 1516.8 0.335 27.047 -10 F~YOU
+ 0 9 3 3 F 1516.9 0.343 28.751 -9 ~LOG~
+ 0 10 2 3 T 1515.8 0.334 30.438 -11 IT~~~
+ 0 11 4 4 F 1502.7 0.062 36.526 13 HOW~D
+ 0 12 4 4 T 1502.7 0.061 38.221 16 O~YOU
+ 0 13 4 4 T 1503.2 0.061 39.917 16 ~LOG~
+ 0 14 5 5 F 1503.2 0.306 41.434 -5 IT~~~
+ 0 15 6 6 F 1517.3 0.357 53.357 -14 WHEN~
+ 0 16 6 6 T 1514.9 0.357 55.053 -8 LOGGI
+ 0 17 6 6 T 1517.3 0.362 56.754 -13 NG~WI
+ 0 18 7 7 F 1518.3 0.350 58.438 -11 NDOW~
+ 0 19 6 7 T 1517.9 0.356 60.140 -8 POPS~
+ 0 20 7 7 T 1516.8 0.349 63.525 -10 OG~IT
+ 0 21 8 8 F 1516.9 0.287 66.855 -9 AFTER
+ 0 22 8 8 T 1518.3 0.287 68.551 -8 ~F3~~
+ 0 23 9 9 F 1502.2 0.410 82.666 15 LOGGI
+ 0 24 9 9 T 1502.2 0.409 84.361 16 NG~WI
+ 0 25 9 9 T 1502.2 0.409 86.057 16 NDOW~
+ 0 26 9 9 T 1502.2 0.409 87.753 15 DOES~
+ 0 27 9 9 T 1502.2 0.410 89.450 14 NOT~P
+ 0 28 9 9 T 1502.2 0.410 91.146 16 OP~UP
+ 0 29 9 9 T 1502.2 0.409 92.841 16 ~AFTE
+ 0 30 9 9 T 1502.2 0.410 94.538 16 R~F3~
+
+ 0 1 1 1 F 1517.9 0.370 0.370 -10 IN~~~
+ 0 2 2 2 F 1502.2 0.375 8.007 5 LOG~Q
+ 0 3 2 2 T 1502.2 0.375 9.703 16 SO~DO
+ 0 4 2 2 T 1502.2 0.375 11.399 15 ES~NO
+ 0 5 2 2 T 1502.2 0.375 13.095 12 THING
+
+ 0 1 1 1 F 1518.3 0.284 0.708 -9 OG~QS
+ 0 2 2 2 F 1515.8 0.277 2.397 -6 O.~MI
+ 0 3 2 2 T 1520.8 0.277 4.093 -10 NE~PO
+ 0 4 1 2 T 1517.3 0.283 5.795 -7 PS~UP
+ 0 5 3 3 F 1502.2 0.305 16.417 15 DOES~
+ 0 6 3 3 T 1502.2 0.305 18.113 12 NOT~W
+ 0 7 3 3 T 1502.2 0.305 19.809 16 ORK~H
+ 0 8 3 3 T 1502.2 0.305 21.505 16 ERE~~
+ 0 9 4 4 F 1514.8 0.260 49.020 -6 SOMEO
+ 0 10 4 4 T 1516.8 0.261 50.717 -6 NE~EL
+ 0 11 4 4 T 1515.8 0.263 52.415 -3 SE~IS
+ 0 12 4 4 T 1516.4 0.262 54.110 -8 ~IN~T
+ 0 13 4 4 T 1515.8 0.263 55.807 -9 HERE~
+
+ 0 1 1 1 F 1502.7 0.035 5.971 2 AGN?~
+
+ 0 1 1 1 F 1516.8 0.293 4.957 -11 JOE~~
+ 0 2 2 2 F 1502.7 0.037 14.029 1 AA5AU
+
+ 0 1 1 1 F 1502.7 0.175 3.143 4 AA5AU
+
+ 0 1 1 1 F 1502.7 0.097 8.577 1 AGN?~
+
+ 0 1 1 1 F 1502.2 0.369 4.185 6 AGN?~
+
+ 0 1 1 1 F 1503.7 0.328 8.808 5 NOT~D
+ 0 2 1 1 T 1503.2 0.327 10.503 12 ECODI
+ 0 3 1 1 T 1503.2 0.328 12.200 11 NG~DE
+ 0 4 1 1 T 1503.2 0.328 13.896 13 ~AA5A
+ 0 5 1 1 T 1503.2 0.327 15.591 11 U~~~~
+ 0 6 2 2 F 1503.2 0.126 42.950 -11 WILL~
+ 0 7 2 2 T 1503.2 0.125 44.645 11 RESTA
+ 0 8 2 2 T 1503.2 0.125 46.341 14 RT~PG
+ 0 9 2 2 T 1503.2 0.126 48.038 7 M~DE~
+ 0 10 2 2 T 1503.7 0.125 49.733 6 AA5AU
+ 0 11 3 3 F 1502.2 0.316 87.660 5 AA5AU
+
+ 0 1 1 1 F 1502.2 0.415 1.263 4 599 012~~
+ 0 2 2 2 F 1497.4 0.000 1.272 -8 599 012~~
+
+ 0 1 1 1 F 1502.2 0.338 5.850 12 W2PU
+ 0 2 1 1 T 1501.7 0.337 7.545 12 599 012~~
+
+ 0 1 1 1 F 1517.3 0.076 3.892 -13 W1UE
+
+ 0 1 1 1 F 1514.3 0.270 5.782 -10 TU W1UE CQ
+
+ 0 1 1 1 F 1514.3 0.270 5.782 -10 TU W1UE CQ
+
+ 0 1 1 1 F 1519.3 0.029 3.421 -10 W2PU
+ 0 2 1 1 T 1518.3 0.027 5.115 -12 599 016~~
+
+ 0 1 1 1 F 1516.8 0.371 3.339 -8 W2PU
+ 0 2 1 1 T 1514.8 0.373 5.037 -7 599 016~~
+
+ 0 1 1 1 F 1502.7 0.003 2.547 11 AA5AU
+
+ 0 1 1 1 F 1502.7 0.240 1.512 14 W2PU
+ 0 2 1 1 T 1502.7 0.239 3.207 13 599 012~~
+
+ 0 1 1 1 F 1518.3 0.032 5.120 -10 W1UE
+
+ 0 1 1 1 F 1515.8 0.253 5.341 -8 599 016~~
+
+ 0 1 1 1 F 1502.2 0.372 6.732 5 CQ AA5AU CQ
+ 0 2 2 2 F 1502.7 0.037 23.357 8 CQ AA5AU CQ
+ 0 3 3 3 F 1503.2 0.321 32.969 3 K9AN
+ 0 4 3 3 T 1502.7 0.320 34.664 13 599 013~~
+ 0 5 4 4 F 1502.7 0.265 43.513 9 TU AA5AU CQ
+ 0 6 5 5 F 1516.3 0.113 48.025 -9 W1UE
+ 0 7 6 6 F 1502.7 0.071 53.495 12 W1UE
+ 0 8 6 6 T 1503.2 0.071 55.191 2 599 014~~
+ 0 9 7 7 F 1517.3 0.126 59.062 -11 AA5AU
+ 0 10 7 7 T 1517.4 0.124 60.756 -11 599 016~~
+ 0 11 8 8 F 1502.7 0.352 64.376 3 TU AA5AU CQ
+
+ 0 1 1 1 F 1502.7 0.105 2.225 9 W2PU
+ 0 2 1 1 T 1502.7 0.104 3.920 8 599 015~~
+
+ 0 1 1 1 F 1503.2 0.137 2.681 13 TU AA5AU CQ
+ 0 2 2 2 F 1516.8 0.346 8.826 -9 W1UE
+ 0 3 3 3 F 1503.2 0.366 16.478 4 W1UE
+ 0 4 3 3 T 1502.7 0.366 18.174 7 599 016~~
+ 0 5 4 4 F 1514.3 0.275 21.475 -7 AA5AU
+ 0 6 4 4 T 1514.8 0.272 23.168 -9 599 016~~
+ 0 7 5 5 F 1503.2 0.395 26.259 9 TU AA5AU CQ
+ 0 8 6 6 F 1503.2 0.005 34.773 8 K9AN
+ 0 9 6 6 T 1503.2 0.003 36.467 6 599 017~~
+ 0 10 5 6 T 1503.2 0.398 45.766 5 TU AA5AU CQ
+ 0 11 7 7 F 1502.7 0.042 55.586 12 W1UE
+ 0 12 7 7 T 1502.7 0.041 57.281 11 599 018~~
+ 0 13 8 8 F 1516.8 0.251 61.731 -7 599 016~~
+ 0 14 9 9 F 1502.2 0.106 64.554 12 TU AA5AU CQ
+
+ 0 1 1 1 F 1502.2 0.377 5.041 13 WOW~D
+ 0 2 1 1 T 1502.2 0.377 6.737 15 E~AA5
+ 0 3 1 1 T 1502.2 0.377 8.433 12 AU~~~
+ 0 4 2 2 F 1517.3 0.181 21.381 -10 CQ W1UE CQ
+
+ 0 1 1 1 F 1515.8 0.301 6.661 -12 CQ W1UE CQ
+ 0 2 2 2 F 1502.2 0.156 12.876 5 AA5AU
+
+ 0 1 1 1 F 1502.2 0.347 0.771 2 CQ WV4P CQ
+ 0 2 1 1 T 1502.2 0.351 7.983 14 AA5AU
+ 0 3 2 2 F 1502.2 0.389 16.501 4 CQ WV4P CQ
+
+ 0 1 1 1 F 1502.2 0.201 3.593 5 CQ WV4P CQ
+
+ 0 1 1 1 F 1502.2 0.301 3.269 3 W1UE
+ 0 2 1 1 T 1502.2 0.300 4.964 11 599 0003~
+ 0 3 2 2 F 1515.8 0.272 8.328 -9 WV4P
+ 0 4 3 3 F 1502.2 0.051 14.891 14 TU WV4P CQ
+
+ 0 1 1 1 F 1502.2 0.395 5.483 -3 W2PU
+ 0 2 1 1 T 1502.2 0.393 7.177 16 599 0004~
+
+ 0 1 1 1 F 1502.2 0.067 2.611 14 TU WV4P CQ
+ 0 2 2 2 F 1502.7 0.307 5.819 -1 AA5AU
+ 0 3 3 3 F 1502.2 0.231 11.679 4 AA5AU
+ 0 4 3 3 T 1502.2 0.231 13.375 16 599 0005~
+ 0 5 4 4 F 1502.2 0.380 16.068 12 WV4P
+ 0 6 4 4 T 1502.2 0.380 17.764 8 599 019~~
+ 0 7 5 5 F 1502.2 0.179 24.347 11 TU WV4P CQ
+ 0 8 6 6 F 1502.2 0.354 26.642 5 U~QTC
+ 0 9 6 6 T 1502.2 0.353 28.337 15 ~FOR~
+ 0 10 6 6 T 1502.2 0.353 30.033 15 ME~?~
+
+ 0 1 1 1 F 1502.2 0.067 2.611 14 TU WV4P CQ
+ 0 2 2 2 F 1502.7 0.307 5.819 -1 AA5AU
+ 0 3 3 3 F 1502.2 0.231 11.679 4 AA5AU
+ 0 4 3 3 T 1502.2 0.231 13.375 16 599 0005~
+ 0 5 4 4 F 1502.2 0.380 16.068 12 WV4P
+ 0 6 4 4 T 1502.2 0.380 17.764 8 599 019~~
+ 0 7 5 5 F 1502.2 0.179 24.347 11 TU WV4P CQ
+ 0 8 6 6 F 1502.2 0.354 26.642 5 U~QTC
+ 0 9 6 6 T 1502.2 0.353 28.337 15 ~FOR~
+ 0 10 6 6 T 1502.2 0.353 30.033 15 ME~?~
+
+ 0 1 1 1 F 1502.2 0.185 5.273 11 599 0006~
+
+
+ 0 1 1 1 F 1501.7 0.092 1.788 11 K1JT
+ 0 2 1 1 T 1501.7 0.092 3.484 17 599 0006~
+
+ 0 1 1 1 F 1501.7 0.063 3.031 4 TU WV4P CQ
+ 0 2 2 2 F 1501.7 0.121 11.993 5 599 0007~
+ 0 3 3 3 F 1501.7 0.172 15.012 4 W1UE
+ 0 4 3 3 T 1502.2 0.172 16.708 9 599 0007~
+
+ 0 1 1 1 F 1503.2 0.240 6.600 5 AA5AU
+ 0 2 2 2 F 1501.7 0.201 14.617 4 599 0008~
+ 0 3 3 3 F 1501.2 0.343 17.727 1 599 0008~
+ 0 4 4 4 F 1501.2 0.333 20.261 13 AA5AU
+ 0 5 4 4 T 1501.7 0.334 21.958 13 599 0008~
+ 0 6 5 5 F 1503.7 0.269 24.861 -3 WV4P
+ 0 7 5 5 T 1503.2 0.270 26.558 4 599 019~~
+ 0 8 6 6 F 1501.7 0.261 30.789 2 TU WV4P CQ
+
+ 0 1 1 1 F 1501.7 0.135 3.103 8 W2ZQ
+ 0 2 1 1 T 1501.2 0.134 4.798 15 599 0009~
+
+
+
+ 0 1 1 1 F 1501.2 0.023 2.991 8 W3CCX
+ 0 2 1 1 T 1501.7 0.023 4.687 14 599 010~~
+
+ 0 1 1 1 F 1501.7 0.184 2.728 5 TU WV4P CQ
+ 0 2 2 2 F 1516.8 0.122 7.754 -11 W1UE
+ 0 3 3 3 F 1501.2 0.124 12.844 4 W1UE
+ 0 4 3 3 T 1501.2 0.123 14.539 16 599 011~~
+ 0 5 4 4 F 1517.8 0.105 17.489 -10 WV4P
+ 0 6 5 5 F 1501.7 0.307 23.203 13 TU WV4P CQ
+
+ 0 1 1 1 F 1503.2 0.111 10.711 6 CQ AA5AU CQ
+
+ 0 1 1 1 F 1515.8 0.130 6.490 -8 CQ W1UE CQ
+ 0 2 2 2 F 1501.2 0.199 17.583 2 WV4P
+ 0 3 3 3 F 1516.8 0.251 23.147 -10 WV4P
+ 0 4 3 3 T 1518.3 0.254 24.846 -9 599 016~~
+ 0 5 4 4 F 1501.2 0.307 29.987 9 TU WV4P CQ
+ 0 6 5 5 F 1501.2 0.406 37.294 2 599 013~~
+ 0 7 6 6 F 1503.7 0.246 49.854 2 AA5AU
+ 0 8 7 7 F 1517.3 0.007 77.599 -9 W1UE
+ 0 9 8 8 F 1503.7 0.301 110.541 2 AA5AU
+ 0 10 9 9 F 1518.8 0.261 117.285 -9 AA5AU
+ 0 11 9 9 T 1514.3 0.256 118.976 -9 599 017~~
+ 0 12 10 10 F 1503.7 0.230 121.918 12 WV4P
+ 0 13 10 10 T 1503.7 0.230 123.614 13 599 019~~
+ 0 14 11 11 F 1516.8 0.353 128.825 -12 TU W1UE CQ
+
+ 0 1 1 1 F 1517.3 0.132 22.604 -13 W1UE
+ 0 2 2 2 F 1501.2 0.215 38.375 3 I~AM~
+ 0 3 2 2 T 1501.2 0.215 40.071 17 USING
+ 0 4 2 2 T 1501.2 0.215 41.767 16 ~IN~N
+ 0 5 2 2 T 1501.2 0.215 43.463 16 1MM~R
+ 0 6 2 2 T 1501.2 0.215 45.159 14 IGHT~
+ 0 7 2 2 T 1501.2 0.215 46.855 13 NOW~~
+
+ 0 1 1 1 F 1501.2 0.019 19.099 14 I~JUS
+ 0 2 1 1 T 1501.2 0.018 20.794 15 T~TYP
+ 0 3 1 1 T 1501.2 0.018 22.490 15 ED~FT
+ 0 4 1 1 T 1501.7 0.018 24.186 9 8~ENT
+ 0 5 1 1 T 1501.2 0.018 25.882 16 ER~TH
+ 0 6 1 1 T 1501.2 0.019 27.579 15 EN~CH
+ 0 7 1 1 T 1501.2 0.019 29.275 15 ANGED
+ 0 8 1 1 T 1501.2 0.019 30.971 16 ~MODE
+ 0 9 1 1 T 1501.2 0.019 32.667 15 ,~WOR
+ 0 10 1 1 T 1501.2 0.019 34.363 11 KS~WE
+ 0 11 1 1 T 1501.2 0.019 36.059 15 LL~~~
+
+ 0 1 1 1 F 1501.2 0.263 7.471 9 YES~~
+
+ 0 1 1 1 F 1516.8 0.271 20.623 -6 W1UE
+ 0 2 2 2 F 1474.4 0.203 29.035 -10 CQ N9ADG CQ
+
+ 0 1 1 1 F 1503.7 0.219 9.123 11 IM~GO
+ 0 2 1 1 T 1504.2 0.218 10.818 15 OD~HE
+ 0 3 1 1 T 1504.2 0.218 12.514 14 RE~DE
+ 0 4 1 1 T 1504.2 0.218 14.210 15 ~AA5A
+ 0 5 1 1 T 1504.2 0.218 15.906 16 U~~~~
+ 0 6 2 2 F 1519.8 0.037 25.901 -9 GOOD~
+ 0 7 2 2 T 1520.8 0.035 27.595 -9 HERE~
+ 0 8 3 3 F 1517.8 0.028 29.284 -7 W1UE~
+ 0 9 4 4 F 1472.9 0.391 38.975 -9 CQ N9ADG CQ
+ 0 10 5 5 F 1504.2 0.327 60.111 13 DE~AA
+ 0 11 5 5 T 1504.2 0.327 61.807 16 5AU~Q
+ 0 12 5 5 T 1504.2 0.327 63.503 16 RT~~~
+ 0 13 6 6 F 1517.3 0.367 66.511 -7 9AN~B
+ 0 14 6 6 T 1518.3 0.367 68.207 -7 ARELY
+ 10 15 7 7 F 1983.4 0.260 68.100 -1 CQ N9ADG CQ
+ 0 16 6 7 T 1515.8 0.365 69.901 -7 ~SHOW
+ 0 17 6 7 T 1515.8 0.364 71.596 -9 ~ON~W
+ 0 18 6 7 T 1517.8 0.363 73.291 -6 ATERF
+ 0 19 6 7 T 1514.8 0.369 74.993 -9 ALL~B
+ 10 20 8 8 F 1981.9 0.024 74.648 -15 CQ N9ADG CQ
+ 0 21 6 8 T 1518.3 0.363 76.683 -9 UT~SO
+ 0 22 6 8 T 1519.3 0.366 78.382 -12 LID~C
+ 0 23 6 8 T 1515.3 0.366 80.078 -8 OPY~~
+
diff --git a/lib/jtty/gen_jttywave.f90 b/lib/jtty/gen_jttywave.f90
new file mode 100644
index 00000000..88c7eafb
--- /dev/null
+++ b/lib/jtty/gen_jttywave.f90
@@ -0,0 +1,110 @@
+subroutine gen_jttywave(itone,nsym,nsps,bt,fsample,f0,cwave,wave,icmplx,nwave)
+
+! Generate JT2 waveform using Gaussian-filtered frequency pulses.
+
+! Input: integer*4 itone(1:nsym) !Tones for channel symbols
+! integer*4 nsym !Number of channel symbols
+! integer*4 nsps !Number of samples per symbol
+! real*4 bt !BT product for Gaussian smoothing
+! real*4 fsample !Sample rate, Hz
+! real*4 f0 !Nominal carrier frequency (lowest tone)
+! integer*4 icmplx !0 for real waveford, 1 for complex
+! integer*4 nwave !Length of output waveform
+
+! Output: complex*8 cwave(nwave) !Complex waveform
+! read*4 wave(nwave) !Real waveform
+
+ parameter(NTAB=65536)
+ real wave(nwave)
+ complex cwave(nwave),ctab(0:NTAB-1)
+ real, allocatable :: pulse(:)
+ real, allocatable :: dphi(:)
+ integer itone(nsym)
+ data fchk0/0.0/
+ save pulse,twopi,dt,hmod,fchk0,ctab
+
+ if(nsym.le.0 .or. nwave.le.0) then
+ nwave=0
+ return
+ endif
+
+ ibt=nint(10*bt)
+ fchk=nsym+nsps+bt+fsample
+ if(fchk.ne.fchk0) then !Execute again only when params change
+ if( allocated(pulse) ) then
+ deallocate(pulse)
+ endif
+ allocate(pulse(1:3*nsps))
+
+ twopi=8.0*atan(1.0)
+ dt=1.0/fsample
+ hmod=1.0
+! Compute the frequency-smoothing pulse
+ do i=1,3*nsps
+ tt=(i-1.5*nsps)/real(nsps)
+ pulse(i)=gfsk_pulse(bt,tt)
+ enddo
+ do i=0,NTAB-1 !Tabulate the trig-functiion values
+ phi=i*twopi/NTAB
+ ctab(i)=cmplx(cos(phi),sin(phi))
+ enddo
+ fchk0=fchk
+ endif
+
+! Compute the smoothed frequency waveform.
+! Length = (nsym+2)*nsps samples, first and last symbols extended
+
+ allocate(dphi(0:(nsym+2)*nsps-1))
+
+ dphi_peak=twopi*hmod/real(nsps)
+ dphi=0.0
+ do j=1,nsym
+ ib=(j-1)*nsps
+ ie=ib+3*nsps-1
+ dphi(ib:ie) = dphi(ib:ie) + dphi_peak*pulse(1:3*nsps)*itone(j)
+ enddo
+
+! Add dummy symbols at beginning and end with tone values equal to 1st and
+! last symbol, respectively
+
+ dphi(0:2*nsps-1)=dphi(0:2*nsps-1)+dphi_peak*itone(1)*pulse(nsps+1:3*nsps)
+ dphi(nsym*nsps:(nsym+2)*nsps-1)=dphi(nsym*nsps:(nsym+2)*nsps-1) + &
+ dphi_peak*itone(nsym)*pulse(1:2*nsps)
+
+! Calculate and insert the audio waveform
+ phi=0.0
+ dphi = dphi + twopi*f0*dt !Shift frequency up by f0
+ if(icmplx .eq. 0) wave=0.
+ if(icmplx .ne. 0) cwave=0. !Avoid writing to memory we may not have access to
+
+ k=0
+ do j=nsps,nsps+nwave-1 !Don't include dummy symbols
+ k=k+1
+ if(icmplx.eq.0) then
+ wave(k)=sin(phi)
+ else
+ i=min(NTAB-1,int(phi*float(NTAB)/twopi))
+ cwave(k)=ctab(i)
+ endif
+ phi=modulo(phi+dphi(j),twopi)
+ enddo
+
+! Apply envelope shaping to the first and last symbols
+ nramp=nint(nsps/8.0)
+ if(icmplx.eq.0) then
+ wave(1:nramp)=wave(1:nramp) * &
+ (1.0-cos(twopi*(/(i,i=0,nramp-1)/)/(2.0*nramp)))/2.0
+ k1=nsym*nsps-nramp+1
+ wave(k1:k1+nramp-1)=wave(k1:k1+nramp-1) * &
+ (1.0+cos(twopi*(/(i,i=0,nramp-1)/)/(2.0*nramp)))/2.0
+ else
+ cwave(1:nramp)=cwave(1:nramp) * &
+ (1.0-cos(twopi*(/(i,i=0,nramp-1)/)/(2.0*nramp)))/2.0
+ k1=nsym*nsps-nramp+1
+ cwave(k1:k1+nramp-1)=cwave(k1:k1+nramp-1) * &
+ (1.0+cos(twopi*(/(i,i=0,nramp-1)/)/(2.0*nramp)))/2.0
+ endif
+
+ deallocate(dphi)
+ return
+end subroutine gen_jttywave
diff --git a/lib/jtty/gen_syncwave.f90 b/lib/jtty/gen_syncwave.f90
new file mode 100644
index 00000000..07c0ae43
--- /dev/null
+++ b/lib/jtty/gen_syncwave.f90
@@ -0,0 +1,26 @@
+subroutine gen_syncwave(csync,nss)
+ use jtty_fec, only: is13 ! sync sequence
+ implicit none
+ integer, intent(in) :: nss ! samples/symbol at 6000 samples/sec
+ integer :: i,j,k
+ real :: twopi, fsample, dt, baud, phi, dphi
+ complex, intent(out) :: csync(13*nss)
+
+ twopi=8.0*atan(1.0)
+ fsample = 6000.0
+ dt=1.0/fsample
+ baud=fsample/nss
+ csync=cmplx(0.,0.)
+ k=1
+ phi=0.0
+ do i=1,13
+ dphi=twopi*baud*is13(i)*dt
+ do j=1,nss
+ csync(k)=cmplx(cos(phi),sin(phi))
+ k=k+1
+ phi=phi+dphi
+ enddo
+ enddo
+
+ return
+end subroutine gen_syncwave
diff --git a/lib/jtty/genjtty.f90 b/lib/jtty/genjtty.f90
new file mode 100644
index 00000000..80be9c02
--- /dev/null
+++ b/lib/jtty/genjtty.f90
@@ -0,0 +1,161 @@
+subroutine genjtty(umsg,itone,nsym)
+
+! Input: character*80 umsg !User message
+! Output: integer*4 itone(1:nsym) !Tones for channel symbols
+! integer*4 nsym !Number of channel symbols
+
+ use jtty_mod, only: JTTY_EXCHANGE_UNKNOWN
+ parameter (MAX_TONES=59*16) !Max number of channel symbols
+ character*80 umsg !User-formatted message
+ integer itone(MAX_TONES) !Array of tone frequencies for this message
+ call genjtty_profile(umsg,JTTY_EXCHANGE_UNKNOWN,itone,nsym)
+
+ return
+end subroutine genjtty
+
+subroutine genjtty_profile(umsg,exchange_profile,itone,nsym)
+
+ use jtty_mod, only: pack_jtty,MAX_FRAMES
+ implicit none
+ character(len=80), intent(inout) :: umsg
+ integer, intent(in) :: exchange_profile
+ integer, intent(out) :: itone(59*MAX_FRAMES),nsym
+ character(len=34) :: frames(MAX_FRAMES)
+ integer :: nframes
+
+ nsym=0
+ call pack_jtty(umsg,frames,nframes,exchange_profile)
+ if(nframes.le.0) return
+ call genjtty_frames(frames,nframes,itone,nsym)
+end subroutine genjtty_profile
+
+subroutine genjtty_atoms(atoms,natoms,itone,nsym)
+
+ use jtty_mod, only: jtty_source_atom,pack_jtty_atoms,MAX_FRAMES
+ type(jtty_source_atom), intent(in) :: atoms(:)
+ integer, intent(in) :: natoms
+ integer, intent(out) :: itone(*)
+ integer, intent(out) :: nsym
+ character(len=34) :: frames(MAX_FRAMES)
+ integer :: nframes
+ logical :: valid
+
+ call pack_jtty_atoms(atoms,natoms,frames,nframes,valid)
+ nsym=0
+ if(.not.valid) return
+ call genjtty_frames(frames,nframes,itone,nsym)
+end subroutine genjtty_atoms
+
+subroutine genjtty_frames(frames,nframes,itone,nsym)
+
+ use jtty_fec, only: PAYLOAD_BITS,tbcc_encode,is13
+ use jtty_tbcc_code_profiles, only: JTTY_TBCC_PROFILE_1167_1545_80F
+ implicit none
+ character(len=34), intent(in) :: frames(*)
+ integer, intent(in) :: nframes
+ integer, intent(out) :: itone(*),nsym
+ integer :: payload(PAYLOAD_BITS),tone_symbols(46),i,ib
+
+ nsym=0
+ do i=1,nframes
+ read(frames(i),'(34i1)') payload
+ call tbcc_encode(payload,tone_symbols,JTTY_TBCC_PROFILE_1167_1545_80F)
+ ib=(i-1)*59+1
+ itone(ib:ib+12)=is13
+ itone(ib+13:ib+58)=tone_symbols
+ nsym=nsym+59
+ enddo
+end subroutine genjtty_frames
+
+subroutine genjtty_atoms_c(c_atoms,natoms,itone,nsym,status) bind(C,name='genjtty_atoms_c')
+
+ use iso_c_binding, only: c_char,c_int,c_null_char
+ use packjt77_grammar, only: pack77_arrl_section_index
+ use jtty_mod, only: jtty_source_atom,jtty_source_atom_c,JTTY_ATOM_CALL, &
+ JTTY_ATOM_EXCH_NUM,JTTY_ATOM_EXCH_LOC,JTTY_ATOM_EXCH_PAIR, &
+ JTTY_ATOM_CONTROL,JTTY_ATOM_GRID4,jtty_call_atom,jtty_exch_num_atom, &
+ jtty_exch_loc_atom,jtty_class_section_atom,jtty_control_atom, &
+ jtty_grid4_atom,MAX_FRAMES,JTTY_ENCODE_OK,JTTY_ENCODE_INVALID_DESCRIPTOR, &
+ JTTY_ENCODE_UNKNOWN_SECTION
+ type(jtty_source_atom_c), intent(in) :: c_atoms(*)
+ integer(c_int), value, intent(in) :: natoms
+ integer(c_int), intent(out) :: itone(*)
+ integer(c_int), intent(out) :: nsym
+ integer(c_int), intent(out) :: status
+ type(jtty_source_atom) :: atoms(MAX_FRAMES)
+ character(len=13) :: descriptor_text
+ integer :: i,section_index
+ logical :: text_valid
+
+ interface
+ subroutine genjtty_atoms(atoms,natoms,itone,nsym)
+ use jtty_mod, only: jtty_source_atom
+ type(jtty_source_atom), intent(in) :: atoms(:)
+ integer, intent(in) :: natoms
+ integer, intent(out) :: itone(*)
+ integer, intent(out) :: nsym
+ end subroutine genjtty_atoms
+ end interface
+
+ nsym=0; status=JTTY_ENCODE_INVALID_DESCRIPTOR
+ if(natoms.lt.1 .or. natoms.gt.MAX_FRAMES) return
+ do i=1,natoms
+ if(c_atoms(i)%reserved.ne.0) return
+ call unpack_descriptor_text(c_atoms(i)%text,descriptor_text,text_valid)
+ if(.not.text_valid) return
+ select case(int(c_atoms(i)%kind))
+ case(JTTY_ATOM_CALL)
+ if(c_atoms(i)%role.ne.0 .or. c_atoms(i)%value.ne.0) return
+ atoms(i)=jtty_call_atom(int(c_atoms(i)%subtype),descriptor_text)
+ case(JTTY_ATOM_EXCH_NUM)
+ if(len_trim(descriptor_text).ne.0) return
+ atoms(i)=jtty_exch_num_atom(int(c_atoms(i)%role), &
+ int(c_atoms(i)%subtype),int(c_atoms(i)%value))
+ case(JTTY_ATOM_EXCH_LOC)
+ if(c_atoms(i)%value.ne.0) return
+ atoms(i)=jtty_exch_loc_atom(int(c_atoms(i)%role), &
+ int(c_atoms(i)%subtype),descriptor_text)
+ case(JTTY_ATOM_EXCH_PAIR)
+ if(c_atoms(i)%subtype.ne.1) return
+ if(c_atoms(i)%role.lt.0 .or. c_atoms(i)%role.gt.5) return
+ section_index=pack77_arrl_section_index(descriptor_text)
+ if(section_index.lt.1) then
+ status=JTTY_ENCODE_UNKNOWN_SECTION
+ return
+ endif
+ atoms(i)=jtty_class_section_atom(int(c_atoms(i)%value), &
+ char(ichar('A')+int(c_atoms(i)%role)),section_index)
+ case(JTTY_ATOM_CONTROL)
+ if(c_atoms(i)%role.ne.0 .or. c_atoms(i)%value.ne.0 .or. &
+ len_trim(descriptor_text).ne.0) return
+ atoms(i)=jtty_control_atom(int(c_atoms(i)%subtype))
+ case(JTTY_ATOM_GRID4)
+ if(c_atoms(i)%subtype.ne.0 .or. c_atoms(i)%value.ne.0) return
+ atoms(i)=jtty_grid4_atom(int(c_atoms(i)%role),descriptor_text)
+ case default
+ return
+ end select
+ enddo
+ call genjtty_atoms(atoms,int(natoms),itone,nsym)
+ if(nsym.gt.0) status=JTTY_ENCODE_OK
+
+contains
+
+ subroutine unpack_descriptor_text(c_text,text,text_valid)
+ character(kind=c_char), intent(in) :: c_text(9)
+ character(len=13), intent(out) :: text
+ logical, intent(out) :: text_valid
+ integer :: j
+
+ text=''
+ text_valid=.false.
+ do j=1,9
+ if(c_text(j).eq.c_null_char) then
+ text_valid=.true.
+ return
+ endif
+ if(j.gt.8) return
+ text(j:j)=c_text(j)
+ enddo
+ end subroutine unpack_descriptor_text
+end subroutine genjtty_atoms_c
diff --git a/lib/jtty/jtty.f90 b/lib/jtty/jtty.f90
new file mode 100644
index 00000000..a8ac65c9
--- /dev/null
+++ b/lib/jtty/jtty.f90
@@ -0,0 +1,60 @@
+program jtty
+
+! Basic implementation of the JTTY protocol for use from the command line.
+
+ use jtty_mod
+ use jtty_fec
+ use jttycom
+ integer jttyaudio !C function for JTTY portaudio
+ character*12 arg
+ data idevin/-1/,idevout/-1/
+
+ narg=iargc()
+ if(narg.ne.7) then
+ print*,'Usage: jtty MyCall HisCall devin devout fTol nQSO ndebug'
+ print*,'Example: jtty K1JT K9AN 2 5 100 123 0'
+ call padevsub(idevin,idevout) !Configure the portaudio devices
+ go to 999
+ endif
+ call getarg(1,mycall)
+ call getarg(2,hiscall)
+ call getarg(3,arg)
+ read(arg,*) idevin
+ call getarg(4,arg)
+ read(arg,*) idevout
+ call getarg(5,arg)
+ read(arg,*) ftol
+ call getarg(6,arg)
+ read(arg,*) nQSO
+ call getarg(7,arg)
+ read(arg,*) ndebug
+
+ call padevsub(idevin,idevout) !Configure the portaudio devices
+
+ nright=1 !Use right channel for audio input
+ iwrite=0 !Set buffer pointer
+ nfsample=12000 !Sample rate (Hz)
+ ngo=1 !Set to 0 to stop program
+ npabuf=384 !PortAudio: 384 frames per buffer, 31.25 baud, 0.032 s
+ ntxok=0
+ ntransmitting=0
+ ltx=.false.
+ lrx=.false.
+ autoseq=.false.
+ QSO_in_progress=.false.
+ ntxed=0
+ nwave=59*384
+ txmsg=''
+ ftx=1500.0
+
+! Start the input and output audio streams. Note that in normal use this call
+! does not return until an error or end-of-program occurs.
+
+ ierr=jttyaudio(idevin,idevout,npabuf,nright,y1,y2,NMAX,iwrite,itx, &
+ iwave,nwave+3*npabuf,nfsample,nTxOK,nTransmitting,ngo,ndebug)
+
+ if(ierr.ne.0) then
+ print*,'Error',ierr,' starting audio input or output.'
+ endif
+
+999 end program jtty
diff --git a/lib/jtty/jtty.ini b/lib/jtty/jtty.ini
new file mode 100644
index 00000000..cecea728
--- /dev/null
+++ b/lib/jtty/jtty.ini
@@ -0,0 +1,3 @@
+K1JT FN20 2 5 0 NJ
+K1JT FN20 1 6 0 NJ
+MyCall MyGrid AudioIn AudioOut PTTport Exch
diff --git a/lib/jtty/jtty_block_pow.f90 b/lib/jtty/jtty_block_pow.f90
new file mode 100644
index 00000000..795e8559
--- /dev/null
+++ b/lib/jtty/jtty_block_pow.f90
@@ -0,0 +1,101 @@
+subroutine jtty_block_pow(z, nsym, iblock, pow_block)
+
+! Coherent block detection for JTTY's 4-FSK symbols. Cascades the already-
+! computed blocksize-1 complex correlator outputs z(0:3,1:nsym) (see
+! jtty_mdecode.f90's decode_and_merge) into coherent blocksize-2 and, if
+! iblock==4, blocksize-4 candidate-sequence sums, then reduces back to a
+! max-over-consistent-sequences per-tone/per-position array shaped like the
+! ordinary single-symbol pow(0:3,1:nsym), ready to feed directly into
+! tbcc_wava_fsk_decode's tone_energies argument -- no changes needed there.
+!
+! Combining operator is plain addition at every cascade level, with no
+! rotation/derotation term. This is specific to JTTY's tone grid: ctones()
+! is built with dphi=i*TWOPI/nss, so one full symbol window advances tone
+! i's phase by exactly i*TWOPI -- an exact multiple of 2*pi for all four
+! tones -- unlike e.g. FST4's centered tone grid (get_fst4_bitmetrics.f90),
+! which picks up a guaranteed 180-degree flip every symbol and so needs a
+! subtraction at its first cascade step.
+!
+! nsym is expected even (NCHAN_SYM=46). The L=2 cascade (nsym/2 pairs) is
+! always built first and used directly when iblock==2. When iblock==4,
+! pairs are grouped by two; if the pair count is odd, the last pair is left
+! at its L=2 reduction instead of being folded into an L=4 group -- this
+! costs nothing extra, since the L=2 cascade already covers every position.
+
+ implicit none
+ integer, intent(in) :: nsym ! NCHAN_SYM (46)
+ integer, intent(in) :: iblock ! 2 or 4
+ complex, intent(in) :: z(0:3,nsym)
+ real, intent(out) :: pow_block(0:3,nsym)
+
+ complex :: c2(0:3,0:3,nsym/2)
+ complex :: s4
+ integer :: npair, nquad, ip, iq, ipL, ipR
+ integer :: posA, posB, pos1, pos2, pos3, pos4
+ integer :: ta, tb, tc, td
+ real :: p2
+
+ npair = nsym/2
+
+ do ip=1,npair
+ posA=2*ip-1
+ posB=2*ip
+ do ta=0,3
+ do tb=0,3
+ c2(ta,tb,ip) = z(ta,posA) + z(tb,posB)
+ enddo
+ enddo
+ enddo
+
+! L=2 reduction, always computed: used directly for iblock==2, and as the
+! trailing-remainder fallback for iblock==4.
+ do ip=1,npair
+ posA=2*ip-1
+ posB=2*ip
+ do ta=0,3
+ p2 = real(c2(ta,0,ip)*conjg(c2(ta,0,ip)))
+ p2 = max(p2, real(c2(ta,1,ip)*conjg(c2(ta,1,ip))))
+ p2 = max(p2, real(c2(ta,2,ip)*conjg(c2(ta,2,ip))))
+ p2 = max(p2, real(c2(ta,3,ip)*conjg(c2(ta,3,ip))))
+ pow_block(ta,posA) = p2/2.0
+ enddo
+ do tb=0,3
+ p2 = real(c2(0,tb,ip)*conjg(c2(0,tb,ip)))
+ p2 = max(p2, real(c2(1,tb,ip)*conjg(c2(1,tb,ip))))
+ p2 = max(p2, real(c2(2,tb,ip)*conjg(c2(2,tb,ip))))
+ p2 = max(p2, real(c2(3,tb,ip)*conjg(c2(3,tb,ip))))
+ pow_block(tb,posB) = p2/2.0
+ enddo
+ enddo
+
+ if(iblock.eq.4) then
+ nquad = npair/2
+ do iq=1,nquad
+ ipL=2*iq-1
+ ipR=2*iq
+ pos1=2*ipL-1
+ pos2=2*ipL
+ pos3=2*ipR-1
+ pos4=2*ipR
+ pow_block(:,pos1)=0.0
+ pow_block(:,pos2)=0.0
+ pow_block(:,pos3)=0.0
+ pow_block(:,pos4)=0.0
+ do ta=0,3
+ do tb=0,3
+ do tc=0,3
+ do td=0,3
+ s4 = c2(ta,tb,ipL) + c2(tc,td,ipR)
+ p2 = real(s4*conjg(s4))/4.0
+ pow_block(ta,pos1) = max(pow_block(ta,pos1), p2)
+ pow_block(tb,pos2) = max(pow_block(tb,pos2), p2)
+ pow_block(tc,pos3) = max(pow_block(tc,pos3), p2)
+ pow_block(td,pos4) = max(pow_block(td,pos4), p2)
+ enddo
+ enddo
+ enddo
+ enddo
+ enddo
+ endif
+
+end subroutine jtty_block_pow
diff --git a/lib/jtty/jtty_codewords.f90 b/lib/jtty/jtty_codewords.f90
new file mode 100644
index 00000000..da0f3162
--- /dev/null
+++ b/lib/jtty/jtty_codewords.f90
@@ -0,0 +1,16 @@
+ integer cw(0:63) !Codewords for the RS(7,2) code
+ data cw/o'1243675',o'2436751',o'3675124',o'4367512',o'5124367', &
+ o'6751243',o'7512436',o'0352764',o'3527640',o'2764035', & !10
+ o'5276403',o'4035276',o'7640352',o'6403527',o'3061457', &
+ o'0614573',o'1457306',o'6145730',o'7306145',o'4573061', & !20
+ o'5730614',o'2170546',o'1705462',o'0546217',o'7054621', &
+ o'6217054',o'5462170',o'4621705',o'5607231',o'6072315', & !30
+ o'7231560',o'0723156',o'1560723',o'2315607',o'3156072', &
+ o'4716320',o'7163204',o'6320471',o'1632047',o'0471632', & !40
+ o'3204716',o'2047163',o'7425013',o'4250137',o'5013742', &
+ o'2501374',o'3742501',o'0137425',o'1374250',o'6534102', & !50
+ o'5341026',o'4102653',o'3410265',o'2653410',o'1026534', &
+ o'0265341',o'0000000',o'1111111',o'2222222',o'3333333', & !60
+ o'4444444',o'5555555',o'6666666',o'7777777'/
+
+! The source alphabet is defined by JTTY_ALPHABET in jtty_mod.f90.
diff --git a/lib/jtty/jtty_decode.f90 b/lib/jtty/jtty_decode.f90
new file mode 100644
index 00000000..357c687c
--- /dev/null
+++ b/lib/jtty/jtty_decode.f90
@@ -0,0 +1,192 @@
+subroutine jtty_decode(iwave,nchunk,nsps,f0,ftol,smin,synced,xdt,f1,snr,decoded,success,nharderrors,nsync,dmin)
+!
+! note nsps is samples per symbol at 12000 s^-1 sample rate.
+!
+ use jtty_mod
+ use jtty_fec
+ use jtty_tbcc_decoder, only: jtty_tbcc_decode
+ use jtty_payload_correlators, only: jtty_payload_correlator, &
+ jtty_payload_correlator_prepare, jtty_correlate_payload_symbols
+ implicit none
+ character*80, intent(out) :: decoded
+ character*34 :: c32(MAX_FRAMES)
+ integer :: final_payload(PAYLOAD_BITS)
+ integer*2, intent(in) :: iwave(nchunk)
+ integer :: i,j,i0,ja,jb
+ integer, intent(in) :: nchunk,nsps !size of chunk, nsps at 12000 Sa/s
+ integer :: nchunk6,nana !size of chunk, nana at 6000 Sa/s
+ integer :: nframe6 !size of frame at 6000 Sa/s
+ integer, save :: nsps0=-999
+ integer, save :: nfft,nh2,nss
+ type(jtty_payload_correlator), save :: payload_correlator
+ complex :: zsym(0:3,TOTAL_K),zhalf(0:3,TOTAL_K)
+ integer :: iloc(1)
+ integer :: irxsync(13)
+ integer, intent(out) :: nharderrors,nsync
+ real :: fsample
+ real :: spk,fpk,pa,pt,pn
+ real :: fbest,xdtbest,sbest
+ real, allocatable :: s(:), sm(:), s0(:)
+ real :: a(3)
+ real :: pow(0:3)
+ real, save :: twopi,baud,dt
+ real :: phi,dphi,df2
+ real :: ssnr,db
+ real, intent(in) :: f0,ftol,smin
+ real, intent(out) :: dmin
+ real, intent(inout) :: xdt,f1,snr
+ complex, allocatable :: c(:)
+ complex, allocatable :: c0(:)
+ complex, allocatable :: c1(:)
+ complex, allocatable,save :: csync(:) !Waveform for sync at 6000 s^-1 sample rate
+ complex, allocatable,save :: ctones(:,:)
+ complex :: z
+ logical, intent(out) :: success
+ logical, intent(inout) :: synced
+ logical :: source_valid
+
+ success=.false.
+ decoded=' '
+ nharderrors=-1
+ nsync=0
+ dmin=0.0
+ if(sum(abs(iwave)).eq.0) return
+
+ if(nsps.ne.nsps0) then
+ nsps0=nsps
+ nss=nsps/2 ! samples per symbol at 6000 sa/s
+ nfft=8192 ! FFT size for sync search, gives df2=0.732
+ nh2=nfft/2 ! spectrum size for sync search
+
+! allocate saved arrays
+ if(allocated(csync)) deallocate(csync)
+ allocate(csync(0:13*nss-1))
+ if(allocated(ctones)) deallocate(ctones)
+ allocate(ctones(0:nss-1,0:3))
+
+! Generate complex waveform for sync
+ twopi=8.0*atan(1.0)
+ baud=6000.0/real(nss) !31.25 for nss=192
+ dt=1/6000.0
+ call gen_syncwave(csync,nss)
+
+ do i=0,3
+ phi=0.0
+ dphi=twopi*i*baud*dt
+ do j=0,nss-1
+ ctones(j,i)=cmplx(cos(phi),sin(phi))
+ phi=phi+dphi
+ enddo
+ enddo
+ endif
+
+ nchunk6=nchunk/2 ! chunk size at 6000 Sa/s
+ nframe6=59*nss ! frame size at 6000 Sa/s
+
+! make size of c0 next power of 2 larger than nchunk
+ nana = 2**nint(log(real(nchunk))/log(2.0)+0.5)
+ allocate(c0(0:nana-1))
+
+! convert integer samples at 12K Sa/s to complex analytic signal at 6K Sa/s
+ call ana64a(iwave,nchunk,c0,nana)
+ c0(nchunk6:)=0.
+
+ allocate(c(0:nfft-1)) !
+ allocate(c1(0:nchunk6-1))
+ allocate(s(0:nh2))
+ allocate(sm(0:nh2))
+ allocate(s0(0:nh2))
+
+ fsample=6000.0
+ dt=1.0/fsample
+ df2=fsample/nfft
+ decoded=' '
+
+ if(.not.synced) then
+ sbest=0.
+ fbest=0.
+ xdtbest=0.
+ fpk=0.
+ ja=(f0-ftol)/df2
+ jb=(f0+ftol)/df2
+ if(ja .lt. 3) ja=3
+ if(jb .gt. nh2-2) jb=nh2-2 !Keep s(j-2:j+2) within s(0:nh2)
+ do i0=0,nframe6/4,12 !Search over quarter-frame segments
+ xdt=i0*dt
+ c(0:13*nss-1)=conjg(csync(0:13*nss-1))*c0(i0:i0+13*nss-1)
+ c(13*nss:)=0.
+ call four2a(c,nfft,1,-1,1) !Compute the sync-shifted spectrum
+ spk=0.
+ do j=ja-2,jb+2
+ s(j)=real(c(j))**2 + aimag(c(j))**2
+ enddo
+ do j=ja,jb
+ sm(j)=s(j-2)+2*s(j-1)+3*s(j)+2*s(j+1)+s(j+2)
+ if(sm(j).gt.spk) then
+ spk=sm(j)
+ fpk=j*df2
+ xdt=i0*dt
+ endif
+ enddo
+ if(spk.gt.sbest) then
+ s0=sm
+ sbest=spk
+ fbest=fpk
+ xdtbest=xdt
+ endif
+ enddo
+
+ xdt=xdtbest
+ snr=db(sbest)
+ f1=fbest
+
+! call jtty_peakup(c0,c1,csync,xdtbest,fbest,xdt,f1,snr)
+ endif
+
+ a=0.
+ a(1)=-f1 !Shift peak to zero frequency
+ call twkfreq(c0,c1,nchunk6,6000.0,a)
+
+ pt=0.
+ pa=0.
+ do j=1,13 ! find tone powers for sync symbols
+ i0=nint(xdt/dt) + (j-1)*nss
+ if(i0+nss.gt.nchunk6) exit
+
+ do i=0,3
+ c(0:nss-1)=conjg(ctones(0:nss-1,i))*c1(i0:i0+nss-1)
+ z=sum(c(0:nss-1))
+ pow(i)=abs(z)**2
+ enddo
+ iloc=maxloc(pow)-1
+ irxsync(j)=iloc(1)
+ pt=pt+pow(is13(j)) !signal plus noise
+ pa=pa+sum(pow) !signal plus 4*noise
+ enddo
+ ssnr=-99.0
+ pn=(pa-pt)/3.0
+ if(pn.gt.0.) ssnr=db(pt/pn) ! pt/pn instead of pt/pn-1 to avoid negative snr estimates
+ snr=ssnr ! replace the snr derived from sync-shifted spectrum
+ nsync=count(is13.eq.irxsync) ! nsync is the number of correct hard-decoded sync tones.
+
+ if(nsync .gt. 6 .and. snr .gt. smin) go to 10
+ return
+
+10 synced=.true.
+
+
+ call jtty_payload_correlator_prepare(payload_correlator,nss)
+ call jtty_correlate_payload_symbols(payload_correlator,c1, &
+ nint(xdt/dt)+13*nss,zsym,zhalf)
+ call jtty_tbcc_decode(zsym,zhalf,final_payload,success)
+ nharderrors=-1
+ if(success) nharderrors=0
+
+ decoded=' '
+ if( success ) then
+ write(c32(1),'(34i1)') final_payload
+ call unpack_jtty(c32,1,decoded,source_valid=source_valid)
+ if(.not.source_valid) success=.false.
+ endif
+ return
+end subroutine jtty_decode
diff --git a/lib/jtty/jtty_design.md b/lib/jtty/jtty_design.md
new file mode 100644
index 00000000..9448c8db
--- /dev/null
+++ b/lib/jtty/jtty_design.md
@@ -0,0 +1,145 @@
+# JTTY Design
+
+JTTY is a new digital mode designed for fast RTTY-like contest exchanges and other keyboard-to-keyboard communication on the amateur radio bands. It has an operational feel similar to standard RTTY, but far better weak-signal performance and a lower error rate. JTTY transmissions can start at any time and typically last a few seconds. Any arbitrary message can be sent using letters, digits, spaces, and punctuation. Source encoding is especially well optimized for the short, fixed-format messages generally used in RTTY-style radio contesting.
+
+## Frame and waveform
+
+A transmission contains one or more 1.888-second frames. Each frame carries a 32-bit source-grammar word followed by two universal control bits: a reserved bit that is always zero and an end-of-message (EOM) bit set only on the final source atom. A 12-bit CRC extends this 34-bit payload to 46 bits. A tail-biting, rate-1/2 convolutional code with constraint length K=10 produces 92 coded bits.
+
+The waveform is Gaussian-smoothed four-tone frequency-shift keying (4-GFSK), with two coded bits per tone symbol. A frame contains a 13-symbol synchronization sequence followed by 46 coded symbols. At 12000/384 = 31.25 baud, its duration is (13+46)/31.25 = 1.888 seconds. The occupied bandwidth (99% of transmitted power) is 127 Hz.
+
+The receiver verifies FEC, CRC, the universal reserved-zero bit, and the complete source grammar. A structurally invalid source word is discarded before display, EOM handling, slot creation, or signal subtraction.
+
+## Source contracts
+
+JTTY separates automatic text packing from typed native actions.
+
+Ordinary keyboard text, `sjtty` input, externally queued strings, and untagged N1MM/MMTTY text use the literal source interface. Text is folded to uppercase, spaces are normalized, and unsupported characters become `#`. The explicit RTTY Roundup profile also canonicalizes report-prefixed serials as described below. The encoder chooses the minimum-frame combination of recognized compact atoms and five-character TEXT5 frames that preserves the resulting normalized text exactly. "Literal" identifies the text interface, not a requirement to use TEXT5 or bypass profile normalization.
+
+The eight shipped JTTY function-key templates use a NativeMacro contract. When a default template is selected, it is compiled to typed call and exchange atoms before placeholder expansion. Native atoms provide compact transmission and unambiguous fields for future logger integration. A customized template that does not match a native form falls back to automatic text packing after normal placeholder expansion. A recognized native template with invalid runtime data is rejected rather than silently transmitted with different semantics.
+
+Earlier JTTY packing minimized frames using compact calls, a generic `599 ` plus five-character format, and TEXT5. STRUCT30 replaced that generic exchange format with richer typed atoms. Restricting ordinary input to TEXT5 avoided guessing whether `05` meant a serial, zone, or check, but also lost unambiguous callsign compaction. Automatic packing retains the minimum-frame algorithm, with context-free recognition and an explicit exchange profile that can normalize serials and enable additional typed candidates.
+
+## Automatic text packing
+
+At complete token boundaries, the packer considers the six callsign forms below, registered control phrases (including within longer messages), and these STRUCT30 forms:
+
+| Text form | Automatic atom |
+| --- | --- |
+| Canonical unsigned decimal, optionally preceded by `599` | GENERIC_NUMERIC, 0-131071, with no leading zeros except `0` |
+| `599 <location>` | GENERIC_QTH, exactly two or three base-36 characters including at least one letter |
+| Valid four-character Maidenhead locator, optionally preceded by `599` | GRID4 |
+| `<count><class> <section>` | CLASS_SECTION, count 1-32, class A-F, registered ARRL/RAC section |
+
+Every candidate must pass the existing codec validation and render exactly as its span in the normalized text. Calls must round-trip through the standard callsign codec; QTH tokens must obey the wire format's canonical length rules.
+
+The GUI captures an exchange profile from the existing special operating activity when each message is submitted: Unknown, Field Day, or RTTY Roundup. No activity means Unknown even though native macros default to serial exchanges. All profiles retain the context-free candidates above. Only RTTY Roundup adds candidates: full `599 <number>` as SERIAL and full `599 <location>` as STATE_PROVINCE, using the native exchange rules and requiring a location token to contain a letter. Bare numbers are never inferred as serials. Field Day adds no candidates because class/section syntax is already self-identifying. No new configuration or wire format is needed.
+
+Zones, checks, ages, power, license years, other specific location categories, zone/location pairs, and serial/time pairs are not inferred. Under RTTY Roundup, equally compact serial or state/province candidates take precedence over their generic equivalents through the subtype ordering below.
+
+A dynamic program over character offsets selects the fewest frames under this recognition policy, rather than greedily taking the first compact form. TEXT5 consumes exactly five characters except at the end; an interior short fragment cannot be padded to reach a compact candidate because that would change the text. Structured atoms supply an implicit single space when followed by another token. Equal-cost alternatives prefer a structured atom, then the longest consumed span, then atom kind/subtype/role order.
+
+Before packing, the explicit RTTY Roundup profile canonicalizes a decimal token following a complete `599` token as a serial: `599 05` becomes `599 005`, and `599 0123` becomes `599 123`. Both use one SERIAL frame. Eligible tokens contain one to six digits with value 0-131071; unsupported tokens retain their spelling and use the normal fallback. Bare digits and all text under Unknown or Field Day retain their spelling after ordinary normalization. The canonical message is returned to the GUI for display and logging. If serial normalization expands the message beyond 80 characters, submission is rejected rather than truncating it.
+
+The result need not match the theoretical minimum with perfect knowledge of exchange semantics. Under Unknown or Field Day, `599 001` and `599 05` still take two frames. An explicit codec caller can encode `599 05` as a CQ zone in one frame, but the current GUI macros do not expose that numeric kind; RTTY Roundup explicitly selects serial meaning instead.
+
+`sjtty` defaults to Unknown. An optional leading `--exchange-profile=unknown|field-day|rtty-roundup` selects the profile for either its one-message packing invocation or its eight-argument waveform invocation. Invalid profile values are errors. For example, `sjtty --exchange-profile=rtty-roundup "599 001"` selects the one-frame serial interpretation.
+
+## Source grammar
+
+Bits 31-32 select one of four message types. The complete normative definition, including field ranges, enum assignments, validity rules, and golden vectors, is in [jtty_source_encoding.txt](jtty_source_encoding.txt).
+
+| `i2.n2` | Contents | Canonical rendering |
+| --- | --- | --- |
+| `0.0` | CQ call action | `CQ <call> CQ` |
+| `0.1` | CALL action | `<call>` |
+| `0.2` | TU/CQ call action | `TU <call> CQ` |
+| `0.3` | CALL/TU action | `<call> TU` |
+| `1.0` | CALL/AGN call action | `<call> AGN?` |
+| `1.1` | TU NOW/CALL action | `TU NOW <call>` |
+| `1.2`, `1.3` | Reserved | Invalid in version 1 |
+| `2` | STRUCT30 | Typed exchange, pair, time, control, or GRID4 atom |
+| `3` | TEXT5 | Five six-bit JTTY characters |
+
+STRUCT30 places a 27-bit family body before a three-bit family selector:
+
+| Family | Name | Fields, in transmitted bit order |
+| --- | --- | --- |
+| `000` | EXCH_NUM | `role1 + number_kind4 + value17 + zero5` |
+| `001` | EXCH_LOC | `role1 + location_kind4 + length1 + base36_token16 + zero5` |
+| `010` | EXCH_PAIR | `pair_schema3 + pair_data23 + zero1` |
+| `011` | EXCH_NUM_TIME | `role1 + serial14 + minute_of_day11 + zero1` |
+| `100` | MISC | `subtype4 + subtype_data23` |
+| `101` | Profiled/dense extension | Reserved |
+| `110` | Versioned extension | Reserved |
+| `111` | Guard space | Invalid |
+
+The assigned fields cover serials, zones, ages, power, checks, four-digit first-license years, generic numbers, two- or three-character locations, zone/location pairs, Field Day class/section pairs, serial/time pairs, GRID4, and 18 common control phrases. Native values render canonically: serials use at least three digits, zones and checks at least two, UTC time exactly four, and license years exactly four. A full exchange adds `599`; a field-only atom omits it. Decimal width, separator style, `5NN` spelling, and visible repetition do not consume wire bits.
+
+The former `i2=2` meaning, literal `599 ` followed by five characters, has been intentionally replaced by STRUCT30. There is no discriminator: old receivers display new STRUCT30 bits as `599` text, and some old type-2 frames are valid new STRUCT30 words with different meanings. JTTY is unreleased, so there is no legacy decoder mode. Automatic packing uses only the current grammar; unrecognized `599 ...` text remains available through TEXT5.
+
+## Native function keys
+
+Current native templates and control phrases match after case folding and
+whitespace normalization, before placeholders are expanded. The three
+superseded serial templates are accepted only in their exact saved-default
+form so edited variants remain literal.
+
+| Key | Template | Native meaning |
+| --- | --- | --- |
+| F1 | `CQ %M CQ` | CQ with the configured call |
+| F2 | `%H %E` | His call, then configured full exchange |
+| F3 | `%H TU CQ %M CQ` | His call/TU, then CQ with the configured call |
+| F4 | `%M` | Configured call |
+| F5 | `%H` | His call |
+| F6 | `TU NOW %Q %E` | Queued call, then configured full exchange |
+| F7 | `%H AGN?` | Request repeat from his call |
+| F8 | `%E` | Configured full exchange |
+
+Keyboard shortcuts and the clickable F1-F8 buttons select the same actions. Native atom sequences use an implicit single-space separator and set EOM only on the last atom. Consecutive queued native messages do not need an intervening TEXT5 space frame.
+
+`%E` parses the selected contest profile: the default is a decimal serial, FIELD_DAY is exactly `<count><class> <section>`, and RTTY is a decimal serial or canonical two- or three-character state/province. `%G` is a field-only GRID4; the exact `599 %G` template selects its full-exchange role. The exact old F2, F6, and F8 defaults using `599 %N` remain recognized during migration and are replaced only when unchanged in saved settings. Edited variants remain literal.
+
+The practical native GUI and N1MM transmit subset covers Call8, serial or RTTY state/province exchanges, Field Day class/section, GRID4, and registered control phrases. Automatic text packing additionally uses GENERIC_NUMERIC and GENERIC_QTH without assigning contest-specific meanings. Other normative STRUCT30 types are decoded, validated, and rendered canonically but are not inferred from text or exposed as general-purpose macros yet.
+
+## Tagged N1MM actions
+
+N1MM may explicitly request native encoding by starting TXTEXT with `[[JTTY:<ACTION>]]`. The assigned actions are `CQ`, `CALL_EXCH`, `CALL_TU_CQ`, `MYCALL`, `HISCALL`, `TU_NOW_EXCH`, `CALL_MY`, `CALL_TU_MY`, `EXCH`, `GRID`, and `CONTROL`. N1MM expands `{MYCALL}`, `!` or `{CALL}`, and `{EXCH}` before WSJT-X validates the action payload under the active profile.
+
+Untagged N1MM text remains literal. A malformed tag, unknown action, invalid call, invalid exchange or grid, unregistered control phrase, or profile mismatch is rejected rather than transmitted as literal bracket text. The exact grammar and action payloads are in [jtty_source_encoding.txt](jtty_source_encoding.txt), with operating examples in [jtty_n1mm_integration.md](jtty_n1mm_integration.md).
+
+## Contest exchange example
+
+The native defaults keep the usual run sequence compact while retaining explicit meanings:
+
+| Run station | S+P stations | Frames |
+| --- | --- | ---: |
+| `CQ KA1ABC CQ` | | 1 |
+| | `WB9XYZ` | 1 |
+| | `JA6DEF` | 1 |
+| `WB9XYZ 599 101` | | 2 |
+| | `599 057` | 1 |
+| `TU NOW JA6DEF 599 102` | | 2 |
+| | *(no decode)* | 1 |
+| `JA6DEF AGN?` | | 1 |
+| | `599 292` | 1 |
+| `TU KA1ABC CQ` | | 1 |
+
+Typed exchanges such as `599 05 NWT`, `599 156 1749`, and `1D EMA` fit one STRUCT30 frame. Automatic text packing recognizes `1D EMA`, but does not infer the zone/location or serial/time meanings of the other two examples. Strong FEC makes repeated visible fields unnecessary; when RF redundancy is desired, repeating the protected atom provides another independent synchronization, FEC, and CRC opportunity.
+
+These frame counts apply to ordinary text, without a native template or contest profile:
+
+| Input | Frames | Reason |
+| --- | ---: | --- |
+| `CQ K1ABC CQ` or `CQ KA1ABC CQ` | 1 | CQ call atom |
+| `WB9XYZ` | 1 | Call atom |
+| `WB9XYZ TU CQ KA1ABC CQ` | 2 | Two call atoms |
+| `WB9XYZ 599 123` | 2 | Call and generic numeric exchange |
+| `599 123` | 1 | Generic numeric exchange |
+| `599 MA` | 1 | Generic QTH exchange |
+| `599 FN42` | 1 | Full-role GRID4 |
+| `1D EMA` | 1 | Class/section pair |
+| `599 001` or `599 05` | 2 | No numeric kind is inferred to preserve leading zeros |
+| `599 BRUCE` | 2 | No current generic five-character exchange atom |
+
+With the RTTY Roundup profile, `599 001` takes one frame and `K1ABC 599 001` takes two. `599 05` becomes `599 005` in one frame. The other examples retain their frame counts, although `599 123` and `599 MA` use typed SERIAL and STATE_PROVINCE atoms instead of generic atoms.
diff --git a/lib/jtty/jtty_design.txt b/lib/jtty/jtty_design.txt
new file mode 100644
index 00000000..b117e77c
--- /dev/null
+++ b/lib/jtty/jtty_design.txt
@@ -0,0 +1,231 @@
+JTTY: A possible WSJT mode for fast RTTY-like contest exchanges
+
+JTTY aims for an operational feel similar to conventional amateur RTTY,
+with much better weak-signal performance and a much lower error rate.
+Transmissions may start at any time and normally last a few seconds.
+
+FRAME AND WAVEFORM
+
+Each frame carries 32 message-grammar bits, a reserved-zero bit, and a
+universal end-of-message bit. A 12-bit CRC extends the payload to 46 bits.
+A tail-biting rate-1/2 convolutional code with constraint length K=10
+produces 92 coded bits.
+
+JTTY uses Gaussian-smoothed four-tone frequency-shift keying (4-GFSK).
+A frame has 13 synchronization symbols followed by 46 coded symbols.
+At 12000/384 = 31.25 baud, one frame lasts 1.888 seconds. Nominal
+half-power bandwidth is 125 Hz.
+
+The receiver verifies FEC, CRC, the universal reserved-zero bit, and the
+complete source grammar. An invalid source word is discarded before it can
+be displayed, mark EOM, create a receive slot, or participate in signal
+subtraction.
+
+SOURCE CONTRACTS
+
+Ordinary keyboard text, sjtty input, externally queued strings, and untagged
+N1MM/MMTTY text use the literal source interface. After uppercase and space
+normalization and replacement of unsupported characters with '#', automatic
+packing selects the minimum-frame combination of recognized compact atoms
+and TEXT5 that preserves the normalized text exactly. Explicit RTTY Roundup
+also applies serial normalization below before packing. "Literal" identifies
+the text interface, not a requirement to use TEXT5 or bypass that normalization.
+
+The eight shipped JTTY function-key templates are explicit native actions.
+Their call, profile-exchange, and grid placeholders compile to typed atoms. A
+customized template that does not match a native form uses automatic text
+packing after normal placeholder expansion. If a recognized native template
+has invalid runtime data,
+transmission is rejected instead of changing meaning through a literal
+fallback.
+
+Earlier JTTY packing minimized frames using compact calls, a generic "599 "
+plus five-character format, and TEXT5. STRUCT30 replaced that exchange format
+with richer typed atoms. Restricting ordinary input to TEXT5 avoided guessing
+whether "05" meant a serial, zone, or check, but also lost unambiguous call
+compaction. Automatic packing retains the minimum-frame algorithm with
+context-free recognition and an explicit exchange profile that can normalize
+serials and enable additional typed candidates.
+
+AUTOMATIC TEXT PACKING
+
+At complete token boundaries the packer considers:
+
+ * The six call forms below, with an exact standard-call codec round trip.
+ * Registered CONTROL phrases, including inside longer messages.
+ * Canonical unsigned decimal 0-131071 as GENERIC_NUMERIC, field-only or
+ preceded by "599 ". Leading zeros are not canonical except for "0".
+ * "599 " plus a canonical two- or three-character base-36 token containing
+ at least one letter, as GENERIC_QTH. The wire length rules apply.
+ * Valid four-character Maidenhead GRID4, field-only or preceded by "599 ".
+ * CLASS_SECTION: count 1-32, class A-F, registered ARRL/RAC section.
+
+Every candidate must pass codec pack/unpack validation and render exactly as
+its span in the normalized text. At submission the GUI captures Unknown,
+Field Day, or RTTY
+Roundup from the existing special operating activity. No activity means
+Unknown even though native macros default to serial exchanges. All profiles
+retain the context-free candidates above; Field Day adds no further candidates.
+
+Only RTTY Roundup adds full "599 <number>" SERIAL and full "599 <location>"
+STATE_PROVINCE candidates under the native exchange rules. Locations must
+contain a letter. Exact rendering after profile normalization remains
+mandatory; bare serials are never
+inferred. Zone, check, age, power, license-year, other specific location,
+zone/location, and serial/time meanings are not inferred. No new configuration
+or wire format is needed. Native actions retain their typed exchange semantics.
+
+Before packing, explicit RTTY Roundup canonicalizes a decimal token following
+a complete "599" token as a serial: "599 05" becomes "599 005", and
+"599 0123" becomes "599 123". Tokens must contain one to six digits and have
+value 0-131071. Unsupported tokens retain their spelling for normal fallback.
+Bare digits and Unknown or Field Day input retain their spelling after ordinary
+normalization. The canonical message is returned to the GUI for display and
+logging. Expansion beyond 80 characters is rejected rather than truncated.
+
+A dynamic program over source-character offsets chooses the minimum number
+of frames under this recognition policy, rather than a greedy sequence.
+TEXT5 consumes exactly five characters except at the end. Interior padding
+cannot be used to reach a compact candidate because it would change the text.
+Structured candidates consume one source space after their rendered span
+when another token follows, matching the receiver's implicit separator.
+Equal-cost choices prefer a structured atom, then the longest consumed span,
+then ascending atom kind/subtype/role.
+The subtype ordering prefers typed serial and state/province candidates over
+generic candidates of equal frame count and span under RTTY Roundup.
+
+This minimum need not equal the theoretical minimum with perfect knowledge
+of contest semantics. Examples for ordinary text under Unknown or Field Day,
+without a native action:
+
+--------------------------------------------------------------------------------
+Text Frames Encoding or limitation
+--------------------------------------------------------------------------------
+CQ K1ABC CQ 1 CQ call
+CQ KA1ABC CQ 1 CQ call
+WB9XYZ 1 Call
+WB9XYZ TU CQ KA1ABC CQ 2 Two call atoms
+WB9XYZ 599 123 2 Call plus generic number
+599 123 1 Generic numeric exchange
+599 MA 1 Generic QTH exchange
+599 FN42 1 Full-role GRID4
+1D EMA 1 Class/section pair
+599 001 2 Leading zeros must be preserved
+599 05 2 No numeric kind is inferred
+599 BRUCE 2 No generic five-character exchange
+--------------------------------------------------------------------------------
+
+Under RTTY Roundup, "599 001" takes one frame and "K1ABC 599 001" takes two.
+"599 123" and "599 MA" use SERIAL and STATE_PROVINCE instead of generic atoms
+without changing frame counts. "599 05" and "599 0123" become "599 005" and
+"599 123", each in one frame.
+
+sjtty defaults to Unknown. Its optional leading argument
+--exchange-profile=unknown|field-day|rtty-roundup applies to both the
+one-message packing invocation and the eight-argument waveform invocation.
+Invalid values are errors. Example:
+
+ sjtty --exchange-profile=rtty-roundup "599 001"
+
+SOURCE GRAMMAR
+
+--------------------------------------------------------------------------------
+i2.n2 Example Bits Purpose
+--------------------------------------------------------------------------------
+0.0 CQ K1ABC CQ call28 + n2 CQ call action
+0.1 K1ABC call28 + n2 CALL action
+0.2 TU K1ABC CQ call28 + n2 TU/CQ action
+0.3 K1ABC TU call28 + n2 CALL/TU action
+1.0 K1ABC AGN? call28 + n2 CALL/AGN action
+1.1 TU NOW K1ABC call28 + n2 TU NOW/CALL action
+1.2 (reserved; invalid)
+1.3 (reserved; invalid)
+2 599 123 body27 + family3 STRUCT30
+3 HELLO 6 6 6 6 6 TEXT5
+--------------------------------------------------------------------------------
+
+Bits 1-30 contain the form listed above and bits 31-32 contain i2. Bit 33
+is always zero. Bit 34 is one only on the final atom of a source message.
+
+STRUCT30 replaces the former i2=2 "599 " plus five-character form:
+
+--------------------------------------------------------------------------------
+Family Name Body fields, in transmitted bit order
+--------------------------------------------------------------------------------
+000 EXCH_NUM role1 kind4 value17 zero5
+001 EXCH_LOC role1 kind4 length1 token16 zero5
+010 EXCH_PAIR schema3 pair_data23 zero1
+011 EXCH_NUM_TIME role1 serial14 minute11 zero1
+100 MISC subtype4 subtype_data23
+101 PROFILED reserved; invalid in version 1
+110 VERSIONED reserved; invalid in version 1
+111 INVALID source-validity guard space
+--------------------------------------------------------------------------------
+
+EXCH_NUM kinds 0-7 are serial, CQ zone, ITU zone, age, power, check,
+first-license year, and generic numeric. EXCH_LOC kinds 0-4 are
+state/province, ARRL/RAC section, country/prefix, generic QTH, and local
+administrative code. EXCH_PAIR schemas are ZONE_LOC3 and CLASS_SECTION.
+MISC subtypes are CONTROL and GRID4. All other IDs are invalid.
+
+Full-role fields render with a "599 " prefix; field-only fields omit it.
+Serials use at least three digits, zones and checks at least two, UTC time
+exactly four, and first-license year exactly four. Structured atoms supply
+one implicit trailing space; TEXT5 characters are appended verbatim. Final
+trailing spaces and TEXT5 padding are not displayed. Formatting choices and
+visible repetitions are not encoded in typed fields.
+
+NATIVE FUNCTION KEYS
+
+--------------------------------------------------------------------------------
+Key Template Native atoms
+--------------------------------------------------------------------------------
+F1 CQ %M CQ CQ(my_call)
+F2 %H %E CALL(his_call), configured full exchange
+F3 %H TU CQ %M CQ CALL_TU(his_call), CQ(my_call)
+F4 %M CALL(my_call)
+F5 %H CALL(his_call)
+F6 TU NOW %Q %E TU_NOW_CALL(queue_call), configured exchange
+F7 %H AGN? CALL_AGN(his_call)
+F8 %E configured full exchange
+--------------------------------------------------------------------------------
+
+Current templates and control phrases match case-insensitively while ignoring
+whitespace differences, before placeholder expansion. Superseded serial
+templates match only in their exact saved-default form. Keyboard F1-F8
+shortcuts and clickable buttons select the same actions. EOM is set only on
+the final native atom; queued native messages do not require a TEXT5 spacing
+frame between them.
+
+%E uses the selected profile: decimal serial by default, exact
+"<count><class> <section>" for FIELD_DAY, and either decimal serial or a
+canonical two- or three-character state/province for RTTY. %G is field-only
+GRID4; the exact "599 %G" template selects full role. Exact old F2, F6, and F8
+defaults using 599 %N remain recognized during migration and are replaced only
+when unchanged in saved settings; edited variants remain literal.
+
+N1MM can opt into native encoding with a leading [[JTTY:<ACTION>]] marker in
+TXTEXT. Actions are CQ, CALL_EXCH, CALL_TU_CQ, MYCALL, HISCALL, TU_NOW_EXCH,
+CALL_MY, CALL_TU_MY, EXCH, GRID, and CONTROL. Untagged N1MM strings use the
+literal source interface with automatic text packing.
+Invalid or unknown tagged requests are rejected, not transmitted as bracket
+text. See jtty_source_encoding.txt and jtty_n1mm_integration.md for the payload
+grammar.
+
+The practical native transmit subset is Call8, serial and RTTY state/province,
+Field Day class/section, GRID4, and registered controls. Automatic text packing
+also generates GENERIC_NUMERIC and GENERIC_QTH. Other normative atoms have
+canonical receive decoding and rendering but are not inferred from text or
+exposed as general-purpose macros in this version.
+
+The complete normative source definition, field ranges, enum assignments,
+validation rules, and binary/hex vectors are in jtty_source_encoding.txt.
+
+COMPATIBILITY
+
+The old i2=2 form is intentionally incompatible with STRUCT30. There is no
+version discriminator: old receivers display new STRUCT30 bits as "599" text,
+and some old type-2 frames are valid new STRUCT30 words with different
+meanings. JTTY is unreleased, so no legacy decoder mode is retained. Automatic
+packing uses only the current grammar; unrecognized "599 ..." text remains
+available through TEXT5.
diff --git a/lib/jtty/jtty_fec_mod.f90 b/lib/jtty/jtty_fec_mod.f90
new file mode 100644
index 00000000..b73a3e62
--- /dev/null
+++ b/lib/jtty/jtty_fec_mod.f90
@@ -0,0 +1,19 @@
+module jtty_fec
+
+! JTTY's forward-error-correction configuration: the 13-symbol 4-FSK sync
+! sequence and established TBCC/outer-check code.
+! The profile and codec APIs are re-exported so JTTY callers need one module.
+
+ use jtty_tbcc_code_profiles
+ use tbcc
+
+! The ACF of this 4FSK sync sequence has peak sidelobe level of 2/13
+! and 46 such values over the entire 25x7 lag space
+ integer :: is13(13) = [0,2,2,3,0,0,3,2,1,3,1,2,0]
+
+! Bit 33 of the 34-bit payload (see jtty_mod.f90's pack_jtty/unpack_jtty) is
+! reserved-zero in the current protocol. Assigning it requires a coordinated
+! protocol revision. Bit 34 is the "last frame of this message" flag.
+ integer, parameter :: JTTY_RESERVED_BIT = 33
+
+end module jtty_fec
diff --git a/lib/jtty/jtty_mdecode.f90 b/lib/jtty/jtty_mdecode.f90
new file mode 100644
index 00000000..4f77d51f
--- /dev/null
+++ b/lib/jtty/jtty_mdecode.f90
@@ -0,0 +1,1228 @@
+module jtty_mdec
+
+ use iso_fortran_env, only: int64
+ use iso_c_binding, only: c_ptr,c_null_ptr,c_associated,c_f_pointer, &
+ c_float_complex,c_size_t
+ use jtty_mod, only: MAX_FRAMES
+ use jtty_fec, only: PAYLOAD_BITS, TOTAL_K, tbcc_encode
+ use jtty_tbcc_code_profiles, only: JTTY_TBCC_PROFILE_1167_1545_80F
+ use jtty_tbcc_decoder, only: jtty_tbcc_decode
+ use jtty_payload_correlators, only: jtty_payload_correlator, &
+ jtty_payload_correlator_prepare, jtty_correlate_payload_symbols
+
+ type :: decode
+ real :: f1 = 0.0 !Synced audio frequency
+ real :: xdt = 0.0 !Synced DT (0 to 0.5 s)
+ real :: tsync = 0.0 !Time of sync from istart=1
+ real :: snrdb = 0.0 !SNR of decoded frame
+ character(len=80) :: decoded = ''
+ logical :: trailing_sep = .false. !decoded ends with an implicit separator column
+ logical :: is_last_frame = .false. !this frame had the "last frame of message" bit set
+ end type decode
+
+ type :: message_assembly
+ integer(int64) :: message_id = 0_int64
+ real :: f1 = 0.0
+ real :: tsync = 0.0
+ real :: start_tsync = 0.0
+ integer :: k = 0
+ character(len=80) :: decoded = ''
+ logical :: trailing_sep = .false.
+ end type message_assembly
+
+ type :: frame_fingerprint
+ real :: f1 = 0.0
+ real :: tsync = 0.0
+ end type frame_fingerprint
+
+ type :: message_update
+ integer(int64) :: message_id = 0_int64
+ real :: f1 = 0.0
+ real :: start_tsync = 0.0
+ character(len=80) :: decoded = ''
+ logical :: complete = .false.
+ end type message_update
+
+ integer, parameter :: MAX_DECODES = 100
+ integer, parameter :: MAX_ACTIVE_MESSAGES = 30
+ integer, parameter :: MAX_RECENT_FRAMES = MAX_ACTIVE_MESSAGES*MAX_FRAMES
+ integer, parameter :: MAX_CONTINUATION_GAP = 3
+ integer, parameter :: MAX_RETRO_STEPS = 3
+ real, parameter :: FRAME_HISTORY_TIME_TOLERANCE = 0.05
+ real, parameter :: FRAME_HISTORY_FREQ_TOLERANCE = 3.0
+ real, parameter :: NEAR_SIMULTANEOUS_FREQ_TOLERANCE = 12.0
+ real, parameter :: CONTINUATION_TIME_TOLERANCE = 0.1
+ integer :: ndecodes = 0
+ integer :: nactive = 0
+ integer :: nrecent = 0
+ integer :: npending = 0
+ integer :: pending_first = 1
+ integer(int64) :: next_message_id = 1_int64
+ type(message_assembly) :: active_messages(MAX_ACTIVE_MESSAGES)
+ type(frame_fingerprint) :: recent_frames(MAX_RECENT_FRAMES)
+ type(message_update), allocatable :: pending_updates(:)
+
+! Cross-call "retro re-sweep" plumbing (see jtty_mdecode_step): interferer_*
+! requests a pre-search subtraction; nsubtracted/subtracted_* report this
+! call's own subtractions back out.
+ integer, parameter :: MAX_SUBTRACTED = 16
+ logical :: interferer_pending = .false.
+ real :: interferer_f1 = 0.0
+ real :: interferer_tsync = 0.0
+ integer :: interferer_payload(PAYLOAD_BITS) = 0
+ integer :: nsubtracted = 0
+ real :: subtracted_f1(MAX_SUBTRACTED) = 0.0
+ real :: subtracted_tsync(MAX_SUBTRACTED) = 0.0
+ integer :: subtracted_payload(PAYLOAD_BITS,MAX_SUBTRACTED) = 0
+ complex, allocatable, private :: sync_chirp_weights(:),sync_chirp_kernel(:)
+ integer, private :: sync_chirp_samples=0,sync_chirp_first_bin=-1
+ integer, private :: sync_chirp_output_count=0
+ type, private :: sync_fft_cache
+ type(c_ptr) :: forward=c_null_ptr
+ type(c_ptr) :: backward=c_null_ptr
+ type(c_ptr) :: input_storage=c_null_ptr
+ type(c_ptr) :: spectrum_storage=c_null_ptr
+ type(c_ptr) :: inverse_storage=c_null_ptr
+ complex(c_float_complex), pointer, contiguous :: input(:)=>null()
+ complex(c_float_complex), pointer, contiguous :: spectrum(:)=>null()
+ complex(c_float_complex), pointer, contiguous :: inverse(:)=>null()
+ end type sync_fft_cache
+ integer, parameter, private :: MIN_SYNC_FFT_ORDER=11,MAX_SYNC_FFT_ORDER=13
+ type(sync_fft_cache), private :: sync_fft_caches(MIN_SYNC_FFT_ORDER:MAX_SYNC_FFT_ORDER)
+
+contains
+
+ subroutine release_sync_fft_cache(cache)
+ use fftw3, only: fftwf_destroy_plan,fftwf_free
+ type(sync_fft_cache), intent(inout) :: cache
+
+ !$omp critical(fftw)
+ if(c_associated(cache%forward)) call fftwf_destroy_plan(cache%forward)
+ if(c_associated(cache%backward)) call fftwf_destroy_plan(cache%backward)
+ !$omp end critical(fftw)
+ cache%forward=c_null_ptr
+ cache%backward=c_null_ptr
+ nullify(cache%input,cache%spectrum,cache%inverse)
+ if(c_associated(cache%input_storage)) call fftwf_free(cache%input_storage)
+ if(c_associated(cache%spectrum_storage)) call fftwf_free(cache%spectrum_storage)
+ if(c_associated(cache%inverse_storage)) call fftwf_free(cache%inverse_storage)
+ cache%input_storage=c_null_ptr
+ cache%spectrum_storage=c_null_ptr
+ cache%inverse_storage=c_null_ptr
+ end subroutine release_sync_fft_cache
+
+ logical function allocate_sync_fft_buffer(nfft,storage,buffer)
+ use fftw3, only: fftwf_alloc_complex
+ integer, intent(in) :: nfft
+ type(c_ptr), intent(out) :: storage
+ complex(c_float_complex), pointer, contiguous, intent(out) :: buffer(:)
+ complex(c_float_complex), pointer, contiguous :: one_based_buffer(:)
+
+ storage=fftwf_alloc_complex(int(nfft,c_size_t))
+ allocate_sync_fft_buffer=c_associated(storage)
+ if(.not.allocate_sync_fft_buffer) return
+ call c_f_pointer(storage,one_based_buffer,[nfft])
+ buffer(0:nfft-1)=>one_based_buffer
+ end function allocate_sync_fft_buffer
+
+ logical function ensure_sync_fft_cache(nfft,needs_backward,fft_order)
+ use fftw3, only: fftwf_plan_dft_1d,FFTW_FORWARD,FFTW_BACKWARD, &
+ FFTW_MEASURE,FFTW_PRESERVE_INPUT,fftwf_free
+ integer, intent(in) :: nfft
+ logical, intent(in) :: needs_backward
+ integer, intent(out) :: fft_order
+
+ ensure_sync_fft_cache=.false.
+ fft_order=0
+ if(nfft.le.0) return
+ fft_order=trailz(nfft)
+ if(fft_order.lt.MIN_SYNC_FFT_ORDER .or. &
+ fft_order.gt.MAX_SYNC_FFT_ORDER) then
+ fft_order=0
+ return
+ endif
+ if(2**fft_order.ne.nfft) then
+ fft_order=0
+ return
+ endif
+
+ if(.not.c_associated(sync_fft_caches(fft_order)%forward)) then
+ if(.not.allocate_sync_fft_buffer(nfft, &
+ sync_fft_caches(fft_order)%input_storage, &
+ sync_fft_caches(fft_order)%input)) then
+ fft_order=0
+ return
+ endif
+ if(.not.allocate_sync_fft_buffer(nfft, &
+ sync_fft_caches(fft_order)%spectrum_storage, &
+ sync_fft_caches(fft_order)%spectrum)) then
+ call release_sync_fft_cache(sync_fft_caches(fft_order))
+ fft_order=0
+ return
+ endif
+ !$omp critical(fftw)
+ sync_fft_caches(fft_order)%forward=fftwf_plan_dft_1d(nfft, &
+ sync_fft_caches(fft_order)%input, &
+ sync_fft_caches(fft_order)%spectrum,FFTW_FORWARD, &
+ ior(FFTW_MEASURE,FFTW_PRESERVE_INPUT))
+ !$omp end critical(fftw)
+ if(.not.c_associated(sync_fft_caches(fft_order)%forward)) then
+ call release_sync_fft_cache(sync_fft_caches(fft_order))
+ fft_order=0
+ return
+ endif
+ endif
+
+ if(needs_backward .and. &
+ .not.c_associated(sync_fft_caches(fft_order)%backward)) then
+ if(.not.allocate_sync_fft_buffer(nfft, &
+ sync_fft_caches(fft_order)%inverse_storage, &
+ sync_fft_caches(fft_order)%inverse)) then
+ fft_order=0
+ return
+ endif
+ !$omp critical(fftw)
+ sync_fft_caches(fft_order)%backward=fftwf_plan_dft_1d(nfft, &
+ sync_fft_caches(fft_order)%spectrum, &
+ sync_fft_caches(fft_order)%inverse,FFTW_BACKWARD,FFTW_MEASURE)
+ !$omp end critical(fftw)
+ if(.not.c_associated(sync_fft_caches(fft_order)%backward)) then
+ nullify(sync_fft_caches(fft_order)%inverse)
+ call fftwf_free(sync_fft_caches(fft_order)%inverse_storage)
+ sync_fft_caches(fft_order)%inverse_storage=c_null_ptr
+ fft_order=0
+ return
+ endif
+ endif
+
+ ensure_sync_fft_cache=c_associated(sync_fft_caches(fft_order)%forward)
+ if(needs_backward) ensure_sync_fft_cache=ensure_sync_fft_cache .and. &
+ c_associated(sync_fft_caches(fft_order)%backward)
+ if(.not.ensure_sync_fft_cache) then
+ call release_sync_fft_cache(sync_fft_caches(fft_order))
+ fft_order=0
+ endif
+ end function ensure_sync_fft_cache
+
+ subroutine jtty_release_fft_resources() bind(C,name='jtty_release_fft_resources')
+ integer :: index
+
+ do index=MIN_SYNC_FFT_ORDER,MAX_SYNC_FFT_ORDER
+ call release_sync_fft_cache(sync_fft_caches(index))
+ enddo
+ if(allocated(sync_chirp_weights)) deallocate(sync_chirp_weights)
+ if(allocated(sync_chirp_kernel)) deallocate(sync_chirp_kernel)
+ sync_chirp_samples=0
+ sync_chirp_first_bin=-1
+ sync_chirp_output_count=0
+ end subroutine jtty_release_fft_resources
+
+ subroutine reset_decode_search_state()
+ nactive=0
+ nrecent=0
+ end subroutine reset_decode_search_state
+
+ subroutine discard_pending_updates()
+ npending=0
+ pending_first=1
+ end subroutine discard_pending_updates
+
+ pure logical function same_frame(f1_a,tsync_a,f1_b,tsync_b)
+ real, intent(in) :: f1_a,tsync_a,f1_b,tsync_b
+
+ same_frame=abs(f1_a-f1_b).lt.FRAME_HISTORY_FREQ_TOLERANCE .and. &
+ abs(tsync_a-tsync_b).lt.FRAME_HISTORY_TIME_TOLERANCE
+ end function same_frame
+
+ pure logical function same_recent_frame(f1_a,tsync_a,f1_b,tsync_b)
+ real, intent(in) :: f1_a,tsync_a,f1_b,tsync_b
+
+ same_recent_frame=abs(f1_a-f1_b).lt.NEAR_SIMULTANEOUS_FREQ_TOLERANCE .and. &
+ abs(tsync_a-tsync_b).lt.FRAME_HISTORY_TIME_TOLERANCE
+ end function same_recent_frame
+
+ pure function display_message_text(decoded) result(msg)
+ character(len=*), intent(in) :: decoded
+ character(len=80) :: msg
+ integer :: i
+
+ msg=decoded
+ do i=1,len_trim(msg)-4
+ if(msg(i:i+4).eq.'~~~~~') msg(i:i+4)=' ... '
+ enddo
+ do i=1,len_trim(msg)
+ if(msg(i:i).eq.'~') msg(i:i)=' '
+ enddo
+ if(msg(1:1).eq.' ') msg=trim(msg(2:))
+ end function display_message_text
+
+ logical function is_recent_frame(candidate)
+ type(decode), intent(in) :: candidate
+ integer :: i
+
+ is_recent_frame=.false.
+ do i=1,nrecent
+ if(same_recent_frame(candidate%f1,candidate%tsync,recent_frames(i)%f1, &
+ recent_frames(i)%tsync)) then
+ is_recent_frame=.true.
+ return
+ endif
+ enddo
+ end function is_recent_frame
+
+ subroutine remember_recent_frame(candidate)
+ type(decode), intent(in) :: candidate
+
+ if(nrecent.ge.MAX_RECENT_FRAMES) then
+ ! Duplicate history must never prevent an otherwise valid decode.
+ recent_frames(1:MAX_RECENT_FRAMES-1)=recent_frames(2:MAX_RECENT_FRAMES)
+ else
+ nrecent=nrecent+1
+ endif
+ recent_frames(nrecent)%f1=candidate%f1
+ recent_frames(nrecent)%tsync=candidate%tsync
+ end subroutine remember_recent_frame
+
+ subroutine queue_message_update(message,complete)
+ type(message_assembly), intent(in) :: message
+ logical, intent(in) :: complete
+ type(message_update), allocatable :: grown(:)
+ integer :: i,index,new_capacity
+
+ do i=0,npending-1
+ index=pending_first+i
+ if(pending_updates(index)%message_id.eq.message%message_id) then
+ pending_updates(index)%f1=message%f1
+ pending_updates(index)%decoded=message%decoded
+ pending_updates(index)%complete=complete
+ return
+ endif
+ enddo
+
+ if(.not.allocated(pending_updates)) then
+ allocate(pending_updates(MAX_ACTIVE_MESSAGES))
+ else if(pending_first+npending.gt.size(pending_updates)) then
+ if(npending.lt.size(pending_updates)) then
+ pending_updates(1:npending)= &
+ pending_updates(pending_first:pending_first+npending-1)
+ else
+ new_capacity=2*npending
+ allocate(grown(new_capacity))
+ grown(1:npending)=pending_updates(pending_first:pending_first+npending-1)
+ call move_alloc(grown,pending_updates)
+ endif
+ pending_first=1
+ endif
+ npending=npending+1
+ index=pending_first+npending-1
+ pending_updates(index)%message_id=message%message_id
+ pending_updates(index)%f1=message%f1
+ pending_updates(index)%start_tsync=message%start_tsync
+ pending_updates(index)%decoded=message%decoded
+ pending_updates(index)%complete=complete
+ end subroutine queue_message_update
+
+ subroutine remove_active_message(index)
+ integer, intent(in) :: index
+
+ if(index.lt.1 .or. index.gt.nactive) return
+ if(index.lt.nactive) active_messages(index)=active_messages(nactive)
+ nactive=nactive-1
+ end subroutine remove_active_message
+
+ subroutine start_message(candidate,message,accepted)
+ type(decode), intent(in) :: candidate
+ type(message_assembly), intent(out) :: message
+ logical, intent(out) :: accepted
+
+ message=message_assembly()
+ accepted=.false.
+ if(.not.candidate%is_last_frame .and. nactive.ge.MAX_ACTIVE_MESSAGES) return
+ call remember_recent_frame(candidate)
+
+ message%message_id=next_message_id
+ message%f1=candidate%f1
+ message%tsync=candidate%tsync
+ message%start_tsync=candidate%tsync
+ message%decoded=candidate%decoded
+ if(message%decoded(1:4).eq.'599 ') &
+ message%decoded='~'//trim(message%decoded)
+ message%k=len_trim(message%decoded)
+ message%trailing_sep=candidate%trailing_sep
+
+ next_message_id=next_message_id+1_int64
+ call queue_message_update(message,candidate%is_last_frame)
+ if(.not.candidate%is_last_frame) then
+ nactive=nactive+1
+ active_messages(nactive)=message
+ endif
+ accepted=.true.
+ end subroutine start_message
+
+ subroutine append_active_message(index,candidate,nframes_gap,message,accepted)
+ integer, intent(in) :: index,nframes_gap
+ type(decode), intent(in) :: candidate
+ type(message_assembly), intent(out) :: message
+ logical, intent(out) :: accepted
+ integer :: k,kz,n,nchar,nstart
+
+ message=message_assembly()
+ accepted=.false.
+ if(index.lt.1 .or. index.gt.nactive) return
+ call remember_recent_frame(candidate)
+
+ k=active_messages(index)%k
+ n=len_trim(candidate%decoded)
+ if(nframes_gap.gt.1) then
+ nstart=1
+ if(n.ge.1) then
+ if(candidate%decoded(1:1).eq.'~') nstart=2
+ endif
+ kz=min(k+5+(n-nstart+1),80)
+ nchar=max(kz-k-5,0)
+ active_messages(index)%decoded=trim(active_messages(index)%decoded)// &
+ '~~~~~'//candidate%decoded(nstart:nstart+nchar-1)
+ active_messages(index)%k=k+5+nchar
+ else
+ kz=min(k+n,80)
+ if(active_messages(index)%trailing_sep) then
+ active_messages(index)%decoded=trim(active_messages(index)%decoded)// &
+ ' '//candidate%decoded(1:kz-k)
+ else
+ active_messages(index)%decoded=trim(active_messages(index)%decoded)// &
+ candidate%decoded(1:kz-k)
+ endif
+ active_messages(index)%k=kz
+ endif
+ active_messages(index)%trailing_sep=candidate%trailing_sep
+ active_messages(index)%f1=candidate%f1
+ active_messages(index)%tsync=candidate%tsync
+ call queue_message_update(active_messages(index),candidate%is_last_frame)
+ message=active_messages(index)
+ if(candidate%is_last_frame) call remove_active_message(index)
+ accepted=.true.
+ end subroutine append_active_message
+
+ subroutine prune_receive_state(forward_tsync,frame_period)
+ real, intent(in) :: forward_tsync,frame_period
+ real :: oldest_revisit
+ integer :: i,keep
+
+ oldest_revisit=forward_tsync-real(MAX_RETRO_STEPS)*frame_period/4.0
+ ! Retro candidates move backward in time, so only the forward watermark may expire history.
+ keep=0
+ do i=1,nrecent
+ if(recent_frames(i)%tsync.lt. &
+ oldest_revisit-FRAME_HISTORY_TIME_TOLERANCE) cycle
+ keep=keep+1
+ if(keep.ne.i) recent_frames(keep)=recent_frames(i)
+ enddo
+ nrecent=keep
+
+ i=1
+ do while(i.le.nactive)
+ if(oldest_revisit-active_messages(i)%tsync.gt. &
+ real(MAX_CONTINUATION_GAP)*frame_period+ &
+ CONTINUATION_TIME_TOLERANCE) then
+ call queue_message_update(active_messages(i),.false.)
+ call remove_active_message(i)
+ else
+ i=i+1
+ endif
+ enddo
+ end subroutine prune_receive_state
+ subroutine jtty_tbcc_reencode_for_subtraction(payload, tones)
+ integer, intent(in) :: payload(PAYLOAD_BITS)
+ integer, intent(out) :: tones(TOTAL_K)
+
+ call tbcc_encode(payload, tones, JTTY_TBCC_PROFILE_1167_1545_80F)
+ end subroutine jtty_tbcc_reencode_for_subtraction
+
+ pure subroutine jtty_search_window(fc,fwid,nfa,nfb,constrain_to_graph,df, &
+ first_bin,last_bin,ja,jb,usable)
+ implicit none
+ real, intent(inout) :: fc
+ real, intent(in) :: fwid,df
+ integer, intent(in) :: nfa,nfb,first_bin,last_bin
+ integer, intent(out) :: ja,jb
+ logical, intent(in) :: constrain_to_graph
+ logical, intent(out) :: usable
+
+ ja=first_bin
+ jb=last_bin
+ usable=.false.
+ if(df.le.0.0 .or. fwid.lt.0.0 .or. first_bin.gt.last_bin) return
+
+ if(constrain_to_graph) then
+ if(nfa.gt.nfb) return
+ fc=max(real(nfa),min(fc,real(nfb)))
+ endif
+
+ ja=max(first_bin,int((fc-fwid)/df))
+ jb=min(last_bin,int((fc+fwid)/df))
+ if(constrain_to_graph) then
+ ja=max(ja,ceiling(real(nfa)/df))
+ jb=min(jb,floor(real(nfb)/df))
+ endif
+ usable=ja.le.jb
+ end subroutine jtty_search_window
+
+ pure subroutine classify_active_candidate(existing,candidate,frame_period, &
+ match,is_window_dupe,nframes_gap)
+ type(message_assembly), intent(in) :: existing
+ type(decode), intent(in) :: candidate
+ real, intent(in) :: frame_period
+ logical, intent(out) :: match,is_window_dupe
+ integer, intent(out) :: nframes_gap
+ real :: df1,dtsync,qstep,resid,fp_resid,df_tol
+ integer :: nstep,nfp
+
+ df1=candidate%f1-existing%f1
+ dtsync=candidate%tsync-existing%tsync
+ match=.false.
+ nframes_gap=1
+ nfp=nint(dtsync/frame_period)
+ fp_resid=abs(dtsync-frame_period*nfp)
+ if(nfp.ge.1 .and. nfp.le.MAX_CONTINUATION_GAP .and. &
+ fp_resid.lt.CONTINUATION_TIME_TOLERANCE) then
+ df_tol=10.0+3.0*real(nfp-1)
+ match=abs(df1).lt.df_tol
+ if(match) nframes_gap=nfp
+ endif
+
+ ! Retro sweeps revisit only the preceding three quarter-frame windows.
+ is_window_dupe=.false.
+ if(.not.match) then
+ qstep=frame_period/4.0
+ nstep=nint(dtsync/qstep)
+ resid=abs(dtsync-qstep*nstep)
+ if(abs(nstep).le.MAX_RETRO_STEPS .and. abs(df1).lt.10.0 .and. &
+ resid.lt.0.003 .and. &
+ .not.(mod(abs(nstep),4).eq.0 .and. nstep.ne.0)) then
+ match=.true.
+ is_window_dupe=.true.
+ endif
+ endif
+
+ end subroutine classify_active_candidate
+
+ subroutine jtty_mdecode(istart,istart0,iwave,nchunk,nsps,ndebug,nfa,nfb,f0,ftol,smin)
+
+! First try at a multi-decoder for JTTY - replaces the single-decode version in
+! jtty_decode.f90. Does not pass decodes back to rjtty_sub yet - just prints
+! results to the console
+
+! Note: nsps is samples per symbol at 12000 s^-1 sample rate.
+ use iso_fortran_env, only: int16
+ use jtty_mod
+ use jtty_fec
+ implicit none
+ integer, parameter :: MAXCAND = 100
+ integer, parameter :: NSYNC_SYM = 13
+ integer, parameter :: NCHAN_SYM = 46
+ integer, parameter :: NFRAME_SYM = 59
+ real, parameter :: FSAMPLE = 6000.0
+ real, parameter :: TWOPI = 6.283185307179586
+ character(len=80) :: msg
+ character(len=34) :: c32(MAX_FRAMES)
+ integer :: final_payload(PAYLOAD_BITS), tone_symbols_chk(NCHAN_SYM)
+ integer :: tone_symbols_full(NFRAME_SYM), ipass
+ integer(int16), intent(in) :: iwave(nchunk)
+ integer, intent(in) :: istart, istart0, ndebug
+ integer :: i,i0,is,j,ja,jb
+ integer, save :: ntstep, ntgrid
+ integer :: istep,first_sync_bin,last_sync_bin
+ integer :: nchan, ichan
+ integer, intent(in) :: nchunk,nsps !size of chunk, nsps at 12000 Sa/s
+ integer, intent(in) :: nfa,nfb !Wide Graph freq range
+ integer :: nchunk6,nana !size of chunk, nana at 6000 Sa/s
+ integer, save :: nframe6 !size of frame at 6000 Sa/s
+ integer, save :: nsps0=-999
+ type(jtty_payload_correlator), save :: payload_correlator
+ integer, save :: nfft,nh2,nss
+ integer :: iloc(1)
+ integer :: irxsync(NSYNC_SYM), irxchan(NCHAN_SYM)
+ integer :: iactive
+ integer :: nsloc(2),nfz,ntz,ncand,ic,nc,nstep_search
+ integer :: nc0,n_ch0_ok
+ integer :: ja_ch0_ok(16),jb_ch0_ok(16)
+ real :: f1_ch0_ok(16),tsync_ch0_ok(16)
+ integer :: nsync,nsymerrs
+ real :: fc,fwid
+ real :: fpk,pa,pt,pn
+ real :: fbest,xdtbest
+ real :: xdt_retry
+ real, allocatable, save :: s0(:,:)
+ logical, allocatable, save :: mask0(:,:)
+ real :: a(3)
+ real :: pow(0:3,NCHAN_SYM)
+ real, save :: baud,dt,df2
+ real :: phi,dphi
+ real, external :: db
+ real, intent(in) :: f0,ftol,smin
+ real :: snrdb, xdt
+ real :: xdt1, f11, snr0
+ complex, allocatable,save,target :: c(:)
+ complex, allocatable,save :: c0(:)
+ complex, allocatable,save :: c1(:)
+ complex, allocatable,save :: csync(:) !Waveform for sync at 6000 s^-1 sample rate
+ complex, allocatable,save :: ctones(:,:)
+ complex :: z
+ logical :: match
+ logical :: dupe
+ logical :: usable
+ logical :: is_window_dupe
+ logical :: is_pure_dupe
+ logical :: success_dec
+ logical :: channel_decoded, decoded_ok
+ logical :: any_subtracted
+ logical :: s0_valid
+ integer :: ir
+ type(decode) :: cand(MAXCAND) !Candidates for decoding
+ type(decode) :: dec !Current successful decode
+ logical :: use_interferer
+ real :: use_interferer_f1, use_interferer_tsync
+ integer :: use_interferer_payload(PAYLOAD_BITS)
+
+! Capture and clear the retro-resweep interferer request (if any) as the
+! very first thing this call does, before any possible early return below
+! -- otherwise a stale request could leak into a later, unrelated call.
+ use_interferer=interferer_pending
+ use_interferer_f1=interferer_f1
+ use_interferer_tsync=interferer_tsync
+ use_interferer_payload=interferer_payload
+ interferer_pending=.false.
+ nsubtracted=0
+
+ nsync=0
+
+ if(istart.eq.istart0 .and. .not.use_interferer) then
+ ndecodes=0
+ call reset_decode_search_state()
+ endif
+ if(sum(abs(int(iwave))).eq.0) return
+
+ nchunk6=nchunk/2 ! chunk size at 6000 Sa/s
+! nana is the size of c0 - next power of 2 larger than nchunk
+ nana = 2**nint(log(real(nchunk))/log(2.0)+0.5)
+
+ if(nsps.ne.nsps0) then
+ nsps0=nsps
+ nss=nsps/2 ! samples per symbol at 6000 sa/s
+ nfft=8192 ! FFT size for sync search, gives df2=0.732
+ df2=FSAMPLE/nfft
+ nh2=nfft/2 ! spectrum size for sync search
+ nframe6=NFRAME_SYM*nss ! frame size at 6000 Sa/s
+ ntstep=nframe6/4
+ ntgrid=ntstep/12
+
+! allocate saved arrays once
+ if(allocated(csync)) deallocate(csync)
+ allocate(csync(0:NSYNC_SYM*nss-1))
+ if(allocated(ctones)) deallocate(ctones)
+ allocate(ctones(0:nss-1,0:3))
+ if(allocated(c0)) deallocate(c0)
+ allocate(c0(0:nana-1))
+ if(allocated(c)) deallocate(c)
+ allocate(c(0:nfft-1)) !
+ if(allocated(c1)) deallocate(c1)
+ allocate(c1(0:nchunk6-1))
+ if(allocated(s0)) deallocate(s0)
+ allocate(s0(0:nh2,0:ntgrid))
+ s0=0.
+ if(allocated(mask0)) deallocate(mask0)
+ allocate(mask0(0:nh2,0:ntgrid))
+
+! Generate complex waveform for sync
+ baud=FSAMPLE/real(nss) !31.25 for nss=192
+ dt=1/FSAMPLE
+ call gen_syncwave(csync,nss)
+
+ do i=0,3
+ phi=0.0
+ dphi=i*TWOPI/real(nss)
+ do j=0,nss-1
+ ctones(j,i)=cmplx(cos(phi),sin(phi))
+ phi=phi+dphi
+ enddo
+ enddo
+ endif
+
+ call jtty_payload_correlator_prepare(payload_correlator,nss)
+
+! convert integer samples at 12K Sa/s to complex analytic signal at 6K Sa/s
+ call ana64a(iwave,nchunk,c0,nana)
+ c0(nchunk6:)=0.
+
+ if(use_interferer) then
+ ! Retro re-sweep call: subtract the already-known signal out of
+ ! this window's own c0 before searching, on the theory that this
+ ! window's own candidates (whose frame spans reach ~ntstep to
+ ! nframe6 forward of this window's own [0,ntstep] search range)
+ ! may have been corrupted by that signal's energy even though this
+ ! window never itself searched for that signal's own sync. See
+ ! jtty_mdecode_step.
+ tone_symbols_full(1:NSYNC_SYM)=is13
+ call jtty_tbcc_reencode_for_subtraction(use_interferer_payload, tone_symbols_chk)
+ tone_symbols_full(NSYNC_SYM+1:NFRAME_SYM)=tone_symbols_chk
+ call subtract_jtty(c0, nana, nchunk6, tone_symbols_full, NFRAME_SYM, &
+ nss, use_interferer_f1, use_interferer_tsync-(istart-1)/12000.0)
+ endif
+
+! Look for up to 2 sync candidates in each quarter-frame (0.424 second) by 2*FTol rectangle in
+! the time/frequency plane. Find the peak in the search rectangle, then zero a small region
+! of size nfz by ntz centered on the peak location and find the location of the next peak.
+
+ nfz=nint(10.0/df2) ! 14
+ ntz=nint(0.016*6000.0/12.0) ! 8
+
+ ! Every channel reads inside this span; unsearched bins may remain stale.
+ nchan=2
+ first_sync_bin=nh2-2
+ last_sync_bin=3
+ do ichan=0,nchan
+ call channel_window()
+ if(.not.usable) cycle
+ first_sync_bin=min(first_sync_bin,ja)
+ last_sync_bin=max(last_sync_bin,jb)
+ enddo
+
+ nc=2 ! look for 2 candidates in each channel
+ ncand=0
+ any_subtracted=.false.
+ s0_valid=.false.
+
+ ! Phase A: channel 0 gets first claim on every signal -- runs its own
+ ! full up-to-2-pass sweep to completion, accumulating n_ch0_ok across
+ ! both passes, before channels 1/2 (Phase B) ever run.
+ n_ch0_ok=0
+ do ipass=1,2
+ if(ipass.eq.2 .and. .not.any_subtracted) exit
+ if(.not.s0_valid) call build_s0()
+ ichan=0
+ call process_channel()
+ enddo
+
+ ! Channel 0 masks candidates privately, so an unchanged surface can
+ ! also serve channels 1/2. Their suppression modifies s0 directly.
+ any_subtracted=.false.
+ do ipass=1,2
+ if(ipass.eq.2 .and. .not.any_subtracted) exit
+ if(.not.s0_valid) call build_s0()
+ do ichan=1,nchan
+ call process_channel()
+ enddo
+ s0_valid=.false.
+ enddo
+
+ return
+
+ contains
+
+ subroutine build_s0()
+ use fftw3, only: fftwf_execute_dft
+ real(8), parameter :: CHIRP_TWOPI=6.2831853071795864769d0
+ real(8) :: phase
+ real :: p0,p1,p2,p3,p4,chirp_scale
+ integer :: chirp_nfft,output_count,convolution_length
+ integer :: sync_fft_order
+ integer :: index,distance,first_output_bin
+ complex :: cz
+ complex, pointer :: fft_output(:)
+ logical :: use_chirp,full_fft_available
+ ! Rebuild s0, the FFT-correlation sync-search surface, from the
+ ! current c0 (may already reflect earlier-phase subtractions).
+ first_output_bin=first_sync_bin-2
+ output_count=last_sync_bin-first_sync_bin+5
+ convolution_length=NSYNC_SYM*nss+output_count-1
+ chirp_nfft=1
+ do while(chirp_nfft.lt.convolution_length)
+ chirp_nfft=2*chirp_nfft
+ enddo
+ use_chirp=output_count.gt.0 .and. &
+ chirp_nfft.lt.nfft .and. chirp_nfft.le.nfft/2
+
+ if(use_chirp) &
+ use_chirp=ensure_sync_fft_cache(chirp_nfft,.true.,sync_fft_order)
+ if(use_chirp .and. (sync_chirp_samples.ne.NSYNC_SYM*nss .or. &
+ sync_chirp_first_bin.ne.first_output_bin .or. &
+ sync_chirp_output_count.ne.output_count)) then
+ if(allocated(sync_chirp_weights)) deallocate(sync_chirp_weights)
+ if(allocated(sync_chirp_kernel)) deallocate(sync_chirp_kernel)
+ allocate(sync_chirp_weights(0:NSYNC_SYM*nss-1))
+ allocate(sync_chirp_kernel(0:chirp_nfft-1))
+ do index=0,NSYNC_SYM*nss-1
+ phase=-CHIRP_TWOPI*(dble(first_output_bin)*dble(index)+ &
+ 0.5d0*dble(index)*dble(index))/dble(nfft)
+ sync_chirp_weights(index)=conjg(csync(index))* &
+ cmplx(cos(phase),sin(phase))
+ enddo
+ sync_fft_caches(sync_fft_order)%input=0.
+ do distance=0,max(NSYNC_SYM*nss,output_count)-1
+ phase=0.5d0*CHIRP_TWOPI*dble(distance)*dble(distance)/dble(nfft)
+ if(distance.lt.output_count) &
+ sync_fft_caches(sync_fft_order)%input(distance)= &
+ cmplx(cos(phase),sin(phase))
+ if(distance.gt.0 .and. distance.lt.NSYNC_SYM*nss) &
+ sync_fft_caches(sync_fft_order)%input(chirp_nfft-distance)= &
+ cmplx(cos(phase),sin(phase))
+ enddo
+ call fftwf_execute_dft(sync_fft_caches(sync_fft_order)%forward, &
+ sync_fft_caches(sync_fft_order)%input, &
+ sync_fft_caches(sync_fft_order)%spectrum)
+ sync_chirp_kernel=sync_fft_caches(sync_fft_order)%spectrum
+ sync_chirp_samples=NSYNC_SYM*nss
+ sync_chirp_first_bin=first_output_bin
+ sync_chirp_output_count=output_count
+ endif
+
+ ! Wider searches retain the full FFT path.
+ full_fft_available=.false.
+ if(.not.use_chirp) &
+ full_fft_available=ensure_sync_fft_cache(nfft,.false.,sync_fft_order)
+ if(use_chirp) then
+ sync_fft_caches(sync_fft_order)%input(NSYNC_SYM*nss:)=0.
+ chirp_scale=1.0/real(chirp_nfft)
+ else if(full_fft_available) then
+ ! Preserving the input keeps this padding intact for every time column.
+ sync_fft_caches(sync_fft_order)%input(NSYNC_SYM*nss:)=0.
+ endif
+ if(full_fft_available) then
+ fft_output=>sync_fft_caches(sync_fft_order)%spectrum
+ else
+ fft_output=>c
+ endif
+ istep=0
+ do i0=0,ntstep,12 !Search over quarter-frame segment
+ xdt=i0*dt
+ if(use_chirp) then
+ sync_fft_caches(sync_fft_order)%input(0:NSYNC_SYM*nss-1)= &
+ sync_chirp_weights* &
+ c0(i0:i0+NSYNC_SYM*nss-1)
+ call fftwf_execute_dft(sync_fft_caches(sync_fft_order)%forward, &
+ sync_fft_caches(sync_fft_order)%input, &
+ sync_fft_caches(sync_fft_order)%spectrum)
+ sync_fft_caches(sync_fft_order)%spectrum= &
+ sync_fft_caches(sync_fft_order)%spectrum*sync_chirp_kernel
+ call fftwf_execute_dft(sync_fft_caches(sync_fft_order)%backward, &
+ sync_fft_caches(sync_fft_order)%spectrum, &
+ sync_fft_caches(sync_fft_order)%inverse)
+ ! Bluestein's omitted output chirp has unit magnitude.
+ cz=sync_fft_caches(sync_fft_order)%inverse(0)*chirp_scale
+ p0=real(cz)**2+aimag(cz)**2
+ cz=sync_fft_caches(sync_fft_order)%inverse(1)*chirp_scale
+ p1=real(cz)**2+aimag(cz)**2
+ cz=sync_fft_caches(sync_fft_order)%inverse(2)*chirp_scale
+ p2=real(cz)**2+aimag(cz)**2
+ cz=sync_fft_caches(sync_fft_order)%inverse(3)*chirp_scale
+ p3=real(cz)**2+aimag(cz)**2
+ do j=first_sync_bin,last_sync_bin
+ cz=sync_fft_caches(sync_fft_order)%inverse( &
+ j-first_sync_bin+4)*chirp_scale
+ p4=real(cz)**2+aimag(cz)**2
+ s0(j,istep)=p0+2*p1+3*p2+2*p3+p4
+ p0=p1
+ p1=p2
+ p2=p3
+ p3=p4
+ enddo
+ else
+ if(full_fft_available) then
+ sync_fft_caches(sync_fft_order)%input(0:NSYNC_SYM*nss-1)= &
+ conjg(csync(0:NSYNC_SYM*nss-1))*c0(i0:i0+NSYNC_SYM*nss-1)
+ call fftwf_execute_dft(sync_fft_caches(sync_fft_order)%forward, &
+ sync_fft_caches(sync_fft_order)%input, &
+ sync_fft_caches(sync_fft_order)%spectrum)
+ else
+ c=0.
+ c(0:NSYNC_SYM*nss-1)=conjg(csync(0:NSYNC_SYM*nss-1))* &
+ c0(i0:i0+NSYNC_SYM*nss-1)
+ call four2a(c,nfft,1,-1,1)
+ endif
+ ! Keep the two-bin halo while advancing the five-bin smoothing kernel.
+ p0=real(fft_output(first_sync_bin-2))**2+ &
+ aimag(fft_output(first_sync_bin-2))**2
+ p1=real(fft_output(first_sync_bin-1))**2+ &
+ aimag(fft_output(first_sync_bin-1))**2
+ p2=real(fft_output(first_sync_bin))**2+ &
+ aimag(fft_output(first_sync_bin))**2
+ p3=real(fft_output(first_sync_bin+1))**2+ &
+ aimag(fft_output(first_sync_bin+1))**2
+ do j=first_sync_bin,last_sync_bin
+ p4=real(fft_output(j+2))**2+aimag(fft_output(j+2))**2
+ s0(j,istep)=p0+2*p1+3*p2+2*p3+p4
+ p0=p1
+ p1=p2
+ p2=p3
+ p3=p4
+ enddo
+ endif
+ istep=istep+1
+ enddo
+ nstep_search=istep-1
+ s0_valid=.true.
+ end subroutine build_s0
+
+ subroutine channel_window()
+ if(ichan.eq.0) then
+ fc=f0
+ fwid=ftol
+ else
+ fc=1350
+ if(ichan.eq.2) fc=1650
+ fwid=150
+ endif
+ call jtty_search_window(fc,fwid,nfa,nfb,ichan.ne.0,df2,3, &
+ ubound(s0,1)-2,ja,jb,usable)
+ end subroutine channel_window
+
+ subroutine process_channel()
+ ! One channel's candidate search plus sticky-sync retry, for the
+ ! host's current ichan/ipass (host-associated with jtty_mdecode).
+ call channel_window()
+ if(.not.usable) return
+ nc0=nc
+ ! A wide QSO band needs more candidates to avoid crowding out its signal.
+ if(ichan.eq.0) nc0=max(2, min(8, nint(fwid/(nfz*df2))))
+ fbest=0.
+ xdtbest=0.
+ fpk=0.
+ channel_decoded=.false.
+
+ if(ichan.ne.0 .and. n_ch0_ok.gt.0) then
+ ! Erase only channel 0's actual successful-decode neighborhoods
+ ! (not its whole nominal band) so channels 1/2 can't rediscover
+ ! them, while staying free to catch what channel 0 missed.
+ do i=1,n_ch0_ok
+ if(max(ja,ja_ch0_ok(i)) .le. min(jb,jb_ch0_ok(i))) &
+ s0(max(ja,ja_ch0_ok(i)):min(jb,jb_ch0_ok(i)),0:nstep_search) = 0.0
+ enddo
+ endif
+
+ if(ichan.eq.0) mask0(ja:jb,0:nstep_search)=.true.
+
+ do ic=1,nc0
+ if(ichan.eq.0) then
+ ! Channel 0 uses a private mask instead of zeroing s0
+ ! directly, so candidates that never pass the decode gate
+ ! don't eat into channels 1/2's shared search surface.
+ nsloc=maxloc(s0(ja:jb,0:nstep_search), &
+ mask=mask0(ja:jb,0:nstep_search))
+ mask0( max( ja, nsloc(1)-nfz+ja ) : min( jb, nsloc(1)+nfz+ja ), &
+ max( 0, nsloc(2)-ntz ) : min( nstep_search, nsloc(2)+ntz ) ) = .false.
+ else
+ nsloc=maxloc(s0(ja:jb,0:nstep_search))
+ s0( max( ja, nsloc(1)-nfz+ja ) : min( jb, nsloc(1)+nfz+ja ), &
+ max( 0, nsloc(2)-ntz ) : min( nstep_search, nsloc(2)+ntz ) ) = 0.0
+ endif
+ fbest = (nsloc(1)-1+ja)*df2
+ xdtbest = (nsloc(2)-1)*dt*12
+
+ if(ichan.eq.0) then
+ call jtty_peakup(c0,c1,csync,nchunk6, nss, xdtbest, fbest, xdt1, f11, snr0)
+ xdtbest=xdt1
+ fbest=f11
+ endif
+
+ if(ncand .ge. MAXCAND) exit
+ ncand=ncand+1
+ cand(ncand)%xdt=xdtbest
+ cand(ncand)%f1=fbest
+
+ a=0.
+ a(1)=-cand(ncand)%f1 !Shift peak to zero frequency
+ call twkfreq(c0,c1,nchunk6,6000.0,a)
+
+ pt=0.
+ pa=0.
+ pow=0.0
+ do j=1,NSYNC_SYM ! find tone powers for sync symbols
+ i0=nint(cand(ncand)%xdt/dt) + (j-1)*nss
+ if(i0+nss.gt.nchunk6) exit
+
+ do i=0,3
+ z = dot_product(ctones(0:nss-1,i), c1(i0:i0+nss-1))
+ pow(i,j)=real(z*conjg(z))
+ enddo
+
+ iloc=maxloc(pow(:,j))-1
+ irxsync(j)=iloc(1)
+ pt=pt+pow(is13(j),j) !signal plus noise
+ pa=pa+sum(pow(:,j)) !signal plus 4*noise
+ enddo
+
+ snrdb=-99.9
+ pn=(pa-pt)/3.0
+ if(pn.gt.0.) snrdb=db(pt/pn)
+ nsync=count(is13.eq.irxsync) ! nsync is the number of correct hard-decoded sync tones.
+ cand(ncand)%snrdb=snrdb
+
+ if( ichan.eq.0 .and. (nsync .le. 6 .or. snrdb .lt. smin)) cycle
+ if( ichan.ne.0 .and. (nsync .le. 8 .or. snrdb .lt. 5.0)) cycle
+
+! looks like a real candidate - try to decode
+ call decode_and_merge(ic, decoded_ok)
+ if(decoded_ok) call record_ch0_success()
+ if(decoded_ok) channel_decoded=.true.
+ enddo ! candidate loop
+
+ if(.not.channel_decoded) then
+ ! Sticky-sync retry: nothing decoded this call. If an active
+ ! message's continuation frame is due almost exactly one frame
+ ! period ago, retry the FEC decode directly at that remembered
+ ! sync point instead of giving up on it.
+ do ir=1,nactive
+ if(active_messages(ir)%f1.lt.fc-fwid .or. &
+ active_messages(ir)%f1.gt.fc+fwid) cycle
+ if(abs(((istart-1)/12000.0 - active_messages(ir)%tsync) - &
+ nframe6/6000.0) &
+ .gt. 0.1) cycle
+ ! Derive the local offset from absolute sync time because the
+ ! assembly may have been updated from a different decode window.
+ xdt_retry=active_messages(ir)%tsync + nframe6/6000.0 - &
+ (istart-1)/12000.0
+ if(xdt_retry.lt.0.0) cycle
+ if(ncand .ge. MAXCAND) exit
+ ncand=ncand+1
+ cand(ncand)%xdt=xdt_retry
+ cand(ncand)%f1=active_messages(ir)%f1
+ ! decode_and_merge reads tone powers from c1, which is only
+ ! valid for whichever frequency the blind-candidate loop
+ ! above last shifted it to -- re-shift it for this retry's
+ ! own frequency, or it silently correlates against the wrong
+ ! signal (dchristle, PR #337).
+ a=0.
+ a(1)=-cand(ncand)%f1
+ call twkfreq(c0,c1,nchunk6,6000.0,a)
+ nsync=-1 ! not meaningful for a sticky-sync retry; flags it in ndebug output
+ call decode_and_merge(-1, decoded_ok)
+ if(decoded_ok) call record_ch0_success()
+ if(decoded_ok) channel_decoded=.true.
+ exit ! at most one retry attempt per channel per call
+ enddo
+ endif
+ end subroutine process_channel
+
+ subroutine record_ch0_success()
+ ! Record channel 0's successful-decode neighborhood so Phase B can
+ ! avoid it, and decode_and_merge's dedup check can catch it too.
+ if(ichan.ne.0) return
+ if(n_ch0_ok.ge.16) return
+ n_ch0_ok=n_ch0_ok+1
+ ja_ch0_ok(n_ch0_ok)=nint(cand(ncand)%f1/df2)-nfz
+ jb_ch0_ok(n_ch0_ok)=nint(cand(ncand)%f1/df2)+nfz
+ f1_ch0_ok(n_ch0_ok)=cand(ncand)%f1
+ tsync_ch0_ok(n_ch0_ok)=cand(ncand)%tsync
+ end subroutine record_ch0_success
+
+ subroutine decode_and_merge(ic_label, decoded_ok)
+ ! Shared by the candidate loop and the sticky-sync retry: given
+ ! cand(ncand)%xdt/%f1, decode the 46 info symbols and merge into
+ ! active_messages(:). ic_label is only for the ndebug print (-1 for a retry).
+ integer, intent(in) :: ic_label
+ logical, intent(out) :: decoded_ok
+ complex :: zsym(0:3,NCHAN_SYM)
+ complex :: zhalf(0:3,NCHAN_SYM)
+ integer :: payload_start
+ integer :: best_cont
+ real :: best_df,dfabs
+ logical :: have_win,accepted,source_valid
+ integer :: gap,best_gap
+ type(message_assembly) :: accepted_message
+
+ decoded_ok=.false.
+ payload_start=nint(cand(ncand)%xdt/dt) + NSYNC_SYM*nss
+ call jtty_correlate_payload_symbols(payload_correlator,c1,payload_start,zsym,zhalf)
+ call jtty_tbcc_decode(zsym,zhalf,final_payload,success_dec)
+ ! Half-symbol off-tone leakage is not a noise estimate; diagnostics use M1.
+ pow=abs(zsym)**2
+ do j=1,NCHAN_SYM
+ iloc=maxloc(pow(:,j))-1
+ irxchan(j)=iloc(1)
+ enddo
+ cand(ncand)%decoded=' '
+ if( .not. success_dec ) return
+
+ write(c32(1),'(34i1)') final_payload
+ call unpack_jtty(c32,1,cand(ncand)%decoded,cand(ncand)%trailing_sep, &
+ cand(ncand)%is_last_frame,source_valid)
+ if(.not.source_valid) return
+
+ ndecodes=ndecodes+1
+ ! Re-encode the decoded payload to recover the expected tone
+ ! per symbol, for the symbol-error-count/SNR diagnostic below
+ ! (mirrors what the old LDPC path got for free from its own
+ ! codeword bits).
+ call jtty_tbcc_reencode_for_subtraction(final_payload, tone_symbols_chk)
+ nsymerrs=13-nsync
+ do j = 1, NCHAN_SYM
+ is=tone_symbols_chk(j)
+ if(is.ne.irxchan(j)) nsymerrs=nsymerrs+1
+ pt=pt+pow(is,j)
+ pa=pa+sum(pow(:,j))
+ enddo
+ pn=(pa-pt)/3.0
+ if(pn.gt.0.) then
+ snrdb=db(pt/pn)
+ cand(ncand)%snrdb=snrdb
+ endif
+ cand(ncand)%tsync=(istart-1)/12000.0 + cand(ncand)%xdt
+ decoded_ok=.true.
+
+! dupe detection
+ dupe=.false.
+ do i=1,ncand-1
+ if( cand(i)%decoded .eq. cand(ncand)%decoded .and. &
+ abs(cand(i)%tsync - cand(ncand)%tsync).lt. 0.032 ) dupe=.true.
+ enddo
+ ! A channel-1/2 candidate matching a frame channel 0 already decoded
+ ! this call is sync-estimation noise, not a distinct signal. 3.0 Hz
+ ! tracks jtty_peakup's coherent-combining frequency precision.
+ if(ichan.ne.0) then
+ do i=1,n_ch0_ok
+ if(same_frame(cand(ncand)%f1,cand(ncand)%tsync, &
+ f1_ch0_ok(i),tsync_ch0_ok(i))) dupe=.true.
+ enddo
+ endif
+ if(dupe) return
+
+ ! Subtract this signal from c0 so a second, weaker one underneath can
+ ! be found by a follow-up sweep over the residual (see the ipass loop
+ ! in jtty_mdecode). tone_symbols_full is the re-encoded, error-
+ ! corrected full frame (sync + info), matching what genjtty.f90
+ ! assembles for TX.
+ tone_symbols_full(1:NSYNC_SYM)=is13
+ tone_symbols_full(NSYNC_SYM+1:NFRAME_SYM)=tone_symbols_chk
+ call subtract_jtty(c0, nana, nchunk6, tone_symbols_full, NFRAME_SYM, &
+ nss, cand(ncand)%f1, cand(ncand)%xdt)
+ any_subtracted=.true.
+ s0_valid=.false.
+
+ if(nsubtracted.lt.MAX_SUBTRACTED) then
+ nsubtracted=nsubtracted+1
+ subtracted_f1(nsubtracted)=cand(ncand)%f1
+ subtracted_tsync(nsubtracted)=cand(ncand)%tsync
+ subtracted_payload(:,nsubtracted)=final_payload
+ endif
+
+ dec=cand(ncand)
+ match=.false.
+ is_pure_dupe=is_recent_frame(dec)
+ iactive=0
+ if(.not.is_pure_dupe .and. nactive.gt.0) then
+ have_win=.false.
+ best_cont=0
+ best_df=1.0e30
+ best_gap=1
+ do i=1,nactive
+ call classify_active_candidate(active_messages(i),dec, &
+ nframe6/6000.0,match,is_window_dupe,gap)
+ if(.not.match) cycle
+ if(is_window_dupe) then
+ if(.not.have_win) iactive=i
+ have_win=.true.
+ cycle
+ endif
+ dfabs=abs(dec%f1-active_messages(i)%f1)
+ if(dfabs.lt.best_df) then
+ best_df=dfabs
+ best_cont=i
+ best_gap=gap
+ endif
+ enddo
+ if(have_win) then
+ match=.true.
+ is_pure_dupe=.true.
+ else if(best_cont.gt.0) then
+ match=.true.
+ iactive=best_cont
+ else
+ match=.false.
+ endif
+ endif
+
+ if(.not.is_pure_dupe .and. match) then
+ call append_active_message(iactive,dec,best_gap,accepted_message,accepted)
+ if(.not.accepted) return
+ msg=accepted_message%decoded
+ if(dec%is_last_frame) iactive=0
+ else if(.not.is_pure_dupe) then
+ call start_message(dec,accepted_message,accepted)
+ if(.not.accepted) return
+ msg=accepted_message%decoded
+ if(dec%is_last_frame) then
+ iactive=0
+ else
+ iactive=nactive
+ endif
+ else
+ msg=dec%decoded
+ endif
+ msg=display_message_text(msg)
+ if(ndebug.eq.0) then
+ if(.not.is_pure_dupe) write(*,3001) nint(dec%f1),trim(msg)
+3001 format(i4,2x,a)
+ else if(ndebug.gt.0) then
+ write(*,3002) ichan,ipass,ic_label,ndecodes,iactive,nactive,match, &
+ use_interferer,dec%f1,dec%xdt,dec%tsync,nint(dec%snrdb-20.0), &
+ nsync,nsymerrs,trim(msg)
+3002 format(6i4,2L3,f7.1,f7.3,f9.3,i5,i4,i4,2x,a)
+ endif
+ end subroutine decode_and_merge
+
+ end subroutine jtty_mdecode
+
+ subroutine jtty_mdecode_step(iwave,nwave,istart,istart0,nchunk,nsps,ndebug,nfa,nfb,f0,ftol,smin)
+
+! Wraps jtty_mdecode with "retro" re-sweeps: after the normal forward call,
+! re-run the candidate sweep for up to 3 prior quarter-frame windows for
+! every signal this call newly subtracted, since their candidates' frame
+! spans could overlap that signal's energy. Not cascaded to further retro
+! passes. Both rjtty_sub and rjtty call this instead of jtty_mdecode
+! directly, passing the FULL buffer so retro calls can reach backward into it.
+
+ use iso_fortran_env, only: int16
+ implicit none
+ integer, intent(in) :: nwave
+ integer(int16), intent(in) :: iwave(nwave)
+ integer, intent(in) :: istart, istart0, nchunk, nsps, ndebug, nfa, nfb
+ real, intent(in) :: f0, ftol, smin
+ integer :: n_local, nframe, step, istart_prev, k, i
+ real :: f1_local(MAX_SUBTRACTED)
+ real :: tsync_local(MAX_SUBTRACTED)
+ integer :: payload_local(PAYLOAD_BITS,MAX_SUBTRACTED)
+
+ nframe=59*nsps
+ step=nframe/4
+ call prune_receive_state((istart-1)/12000.0,nframe/12000.0)
+
+ interferer_pending=.false. ! defensive: no stale interferer input
+ call jtty_mdecode(istart,istart0,iwave(istart),nchunk,nsps,ndebug,nfa,nfb, &
+ f0,ftol,smin)
+
+! Copy this call's subtraction events out before any retro call below
+! overwrites the same module-level output arrays with its own results.
+ n_local=nsubtracted
+ if(n_local.gt.0) then
+ f1_local(1:n_local)=subtracted_f1(1:n_local)
+ tsync_local(1:n_local)=subtracted_tsync(1:n_local)
+ payload_local(:,1:n_local)=subtracted_payload(:,1:n_local)
+ endif
+
+ do i=1,n_local
+ do k=1,MAX_RETRO_STEPS
+ istart_prev=istart-k*step
+ if(istart_prev.lt.1) cycle
+ interferer_pending=.true.
+ interferer_f1=f1_local(i)
+ interferer_tsync=tsync_local(i)
+ interferer_payload=payload_local(:,i)
+ call jtty_mdecode(istart_prev,istart0,iwave(istart_prev),nchunk,nsps, &
+ ndebug,nfa,nfb,f0,ftol,smin)
+ enddo
+ enddo
+
+ return
+ end subroutine jtty_mdecode_step
+
+end module jtty_mdec
diff --git a/lib/jtty/jtty_mod.f90 b/lib/jtty/jtty_mod.f90
new file mode 100644
index 00000000..7ff25b5b
--- /dev/null
+++ b/lib/jtty/jtty_mod.f90
@@ -0,0 +1,447 @@
+module jtty_mod
+
+ use jtty_source_codec
+
+ parameter (MAX_FRAMES=16) !Max frames for the encoded message
+ character(len=*), parameter :: JTTY_ALPHABET = ALPHABET
+ integer, parameter :: JTTY_EXCHANGE_UNKNOWN=0,JTTY_EXCHANGE_FIELD_DAY=1,JTTY_EXCHANGE_RTTY=2
+
+contains
+
+subroutine pack_jtty(message,c32,nframes,exchange_profile)
+
+! Input: character*80 message !JTTY message, as it appears to a user
+! Output: character*34 c32 !34-bit payload: 32 bits of existing
+! !grammar (unchanged) + 1 "last frame
+! !of this message" flag (c32(:)(34:34))
+! !+ 1 reserved bit, always '0'
+! !(c32(:)(33:33)), that the decoder
+! !uses as a free extra check beyond
+! !the CRC.
+! integer nframes !Frames in this message (max = 16)
+!
+! Minimize frames after alphabet and exchange-profile normalization.
+
+ use packjt77_grammar, only: pack77_arrl_section_index
+ implicit none
+ character*80 message,msg
+ character*34 c32(MAX_FRAMES)
+ integer, intent(in), optional :: exchange_profile
+ integer, parameter :: INF=999
+ type(jtty_source_atom) :: choice(80),atoms(MAX_FRAMES)
+ integer :: dp(81),successor(80),n,ipos,inext,natoms,nframes,profile
+ logical valid
+
+ call normalize_jtty_message(message,msg)
+ message=msg
+ nframes=0
+ c32=''
+ profile=JTTY_EXCHANGE_UNKNOWN
+ if(present(exchange_profile)) profile=exchange_profile
+ if(profile.lt.JTTY_EXCHANGE_UNKNOWN .or. profile.gt.JTTY_EXCHANGE_RTTY) then
+ nframes=-1
+ return
+ endif
+ if(profile.eq.JTTY_EXCHANGE_RTTY) then
+ call normalize_serials(valid)
+ if(.not.valid) then
+ nframes=-1
+ return
+ endif
+ endif
+ message=msg
+ n=len_trim(msg)
+ if(n.le.0) return
+
+ ! dp(i) is the minimum frame count for msg(i:n).
+ dp=INF
+ successor=0
+ dp(n+1)=0
+ do ipos=n,1,-1
+ inext=min(n+1,ipos+5)
+ call consider(jtty_text5_atom(msg(ipos:inext-1)),inext)
+ if(ipos.gt.1) then
+ if(msg(ipos-1:ipos-1).ne.' ') cycle
+ endif
+ call try_compact()
+ enddo
+
+ if(dp(1).gt.MAX_FRAMES) then
+ nframes=-1
+ return
+ endif
+ ipos=1
+ natoms=0
+ do while(ipos.le.n)
+ natoms=natoms+1
+ atoms(natoms)=choice(ipos)
+ ipos=successor(ipos)
+ enddo
+ call pack_jtty_atoms(atoms,natoms,c32,nframes,valid)
+ if(.not.valid) then
+ c32=''
+ nframes=-1
+ endif
+
+contains
+
+ subroutine normalize_serials(ok)
+ logical, intent(out) :: ok
+ character(len=160) :: result
+ character(len=80) :: rendered
+ integer :: first,last,next,last_field,value,length
+ logical :: numeric
+
+ result=''
+ first=1
+ length=len_trim(msg)
+ do while(first.le.length)
+ last=index(msg(first:length),' ')
+ if(last.eq.0) then
+ last=length
+ else
+ last=first+last-2
+ endif
+ rendered=msg(first:last)
+ next=last+2
+ if(rendered.eq.'599' .and. next.le.length) then
+ last_field=index(msg(next:length),' ')
+ if(last_field.eq.0) then
+ last_field=length
+ else
+ last_field=next+last_field-2
+ endif
+ call decimal_value(msg(next:last_field),value,numeric)
+ if(numeric) then
+ call render_jtty_atom(jtty_exch_num_atom(JTTY_ROLE_FULL,JTTY_NUM_SERIAL,value),rendered,ok)
+ if(.not.ok) return
+ next=last_field+2
+ endif
+ endif
+ if(first.eq.1) then
+ result=trim(rendered)
+ else
+ result=trim(result)//' '//trim(rendered)
+ endif
+ if(len_trim(result).gt.len(msg)) then
+ ok=.false.
+ return
+ endif
+ first=next
+ enddo
+ msg=result
+ ok=.true.
+ end subroutine normalize_serials
+
+ subroutine consider(atom,next)
+ type(jtty_source_atom), intent(in) :: atom
+ integer, intent(in) :: next
+ integer :: cost,rank,best_rank,key,best_key
+
+ cost=1+dp(next)
+ if(cost.gt.MAX_FRAMES .or. cost.gt.dp(ipos)) return
+ rank=merge(1,0,atom%kind.eq.JTTY_ATOM_TEXT5)
+ best_rank=merge(1,0,choice(ipos)%kind.eq.JTTY_ATOM_TEXT5)
+ key=100*atom%kind+2*atom%subtype+atom%role
+ best_key=100*choice(ipos)%kind+2*choice(ipos)%subtype+choice(ipos)%role
+ if(cost.eq.dp(ipos)) then
+ if(rank.gt.best_rank) return
+ if(rank.eq.best_rank) then
+ if(next.lt.successor(ipos)) return
+ if(next.eq.successor(ipos) .and. key.ge.best_key) return
+ endif
+ endif
+ dp(ipos)=cost
+ successor(ipos)=next
+ choice(ipos)=atom
+ end subroutine consider
+
+ subroutine offer(atom)
+ type(jtty_source_atom), intent(in) :: atom
+ type(jtty_source_atom) :: decoded
+ character(len=34) :: frame
+ character(len=80) :: rendered
+ logical :: ok,eom
+ integer :: length,last,next
+
+ call pack_jtty_atom(atom,frame,.false.,ok)
+ if(.not.ok) return
+ call unpack_jtty_atom(frame,decoded,ok,eom)
+ if(.not.ok) return
+ call render_jtty_atom(decoded,rendered,ok)
+ if(.not.ok) return
+ length=len_trim(rendered)
+ if(length.eq.0) return
+ last=ipos+length-1
+ if(last.gt.n) return
+ if(msg(ipos:last).ne.rendered(1:length)) return
+ next=n+1
+ if(last.lt.n) then
+ if(msg(last+1:last+1).ne.' ') return
+ ! Structured frames supply exactly one following separator column.
+ next=last+2
+ endif
+ call consider(atom,next)
+ end subroutine offer
+
+ subroutine try_compact()
+ character(len=80) :: words(3)
+ integer :: first,last,nwords,j,action,role,field,value,length,section_index
+ logical :: numeric
+
+ words=''
+ first=ipos
+ nwords=0
+ do j=1,size(words)
+ if(first.gt.n) exit
+ last=index(msg(first:n),' ')
+ if(last.eq.0) then
+ last=n
+ else
+ last=first+last-2
+ endif
+ nwords=j
+ words(j)=msg(first:last)
+ first=last+2
+ enddo
+
+ do j=1,nwords
+ if(len_trim(words(j)).gt.len(choice(1)%text)) cycle
+ do action=JTTY_CALL_CQ,JTTY_CALL_TU_NOW
+ call offer(jtty_call_atom(action,trim(words(j))))
+ enddo
+ enddo
+ do j=lbound(CONTROL_TEXT,1),ubound(CONTROL_TEXT,1)
+ call offer(jtty_control_atom(j))
+ enddo
+
+ do role=JTTY_ROLE_FIELD_ONLY,JTTY_ROLE_FULL
+ field=1
+ if(role.eq.JTTY_ROLE_FULL) then
+ if(words(1).ne.'599' .or. nwords.lt.2) cycle
+ field=2
+ endif
+ length=len_trim(words(field))
+ call decimal_value(trim(words(field)),value,numeric)
+ if(numeric) call offer(jtty_exch_num_atom(role,JTTY_NUM_GENERIC,value))
+ if(numeric .and. role.eq.JTTY_ROLE_FULL .and. profile.eq.JTTY_EXCHANGE_RTTY) &
+ call offer(jtty_exch_num_atom(role,JTTY_NUM_SERIAL,value))
+ if(length.eq.4) call offer(jtty_grid4_atom(role,words(field)(1:4)))
+ if(role.ne.JTTY_ROLE_FULL .or. length.lt.2 .or. length.gt.3) cycle
+ if(scan(trim(words(field)),'ABCDEFGHIJKLMNOPQRSTUVWXYZ').eq.0) cycle
+ call offer(jtty_exch_loc_atom(role,JTTY_LOC_QTH,trim(words(field))))
+ if(profile.eq.JTTY_EXCHANGE_RTTY) &
+ call offer(jtty_exch_loc_atom(role,JTTY_LOC_STATE_PROVINCE,trim(words(field))))
+ enddo
+
+ length=len_trim(words(1))
+ if(nwords.lt.2 .or. length.lt.2 .or. length.gt.3) return
+ call decimal_value(words(1)(1:length-1),value,numeric)
+ if(.not.numeric) return
+ section_index=pack77_arrl_section_index(trim(words(2)))
+ call offer(jtty_class_section_atom(value,words(1)(length:length),section_index))
+ end subroutine try_compact
+
+ subroutine decimal_value(text,value,valid)
+ character(len=*), intent(in) :: text
+ integer, intent(out) :: value
+ logical, intent(out) :: valid
+ integer :: j
+
+ value=0
+ valid=.false.
+ if(len(text).lt.1 .or. len(text).gt.6) return
+ if(verify(text,'0123456789').ne.0) return
+ do j=1,len(text)
+ value=10*value+ichar(text(j:j))-ichar('0')
+ enddo
+ valid=value.le.131071
+ end subroutine decimal_value
+
+end subroutine pack_jtty
+
+logical function jtty_standard_call(c13)
+
+! True only for tokens safe to carry in a 28-bit structured callsign field.
+
+ use packjt77
+ character*13 c13,c13a
+ character*13 unpacked
+ character*6 bcall_1
+ logical ok1,success
+ integer*4 n28
+
+ jtty_standard_call=.false.
+ c13a=c13
+ ! chkcall is a syntax filter; pack28/unpack28 round-trip defines what this
+ ! protocol field can actually carry.
+ call chkcall(c13a,bcall_1,ok1)
+ if(.not.ok1) return
+ if(index(c13a,'/').gt.0) return
+ if(c13a(1:1).eq.'Q') return
+ if(verify(trim(c13a),'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789').ne.0) return
+
+ call pack28(c13a,n28)
+ call unpack28(n28,unpacked,success)
+ if(.not.success) return
+ jtty_standard_call=trim(unpacked).eq.trim(c13a)
+
+end function jtty_standard_call
+
+subroutine normalize_jtty_message(raw,normalized)
+
+! Fold operator text into the source alphabet used by the JTTY encoder.
+
+ character*80 raw,normalized
+ character*1 c
+ logical last_space
+
+ normalized=''
+ last_space=.true.
+ j=0
+
+ do i=1,len(raw)
+ c=raw(i:i)
+ if(ichar(c).eq.0) c=' '
+ ! The decoder uses '~' as a display marker for space, not a source symbol.
+ if(c.eq.'~') c=' '
+ if(c.ge.'a' .and. c.le.'z') c=char(ichar(c)-32)
+ if(jchar(c).lt.0) c='#'
+ if(c.eq.' ') then
+ if(last_space) cycle
+ j=j+1
+ normalized(j:j)=' '
+ last_space=.true.
+ else
+ j=j+1
+ normalized(j:j)=c
+ last_space=.false.
+ endif
+ enddo
+
+end subroutine normalize_jtty_message
+
+subroutine unpack_jtty(c32,nframes,message,trailing_sep,is_last_frame,source_valid)
+
+! Input: character*34 c32 !34-bit payload: 32 bits of existing
+! !grammar + 1 reserved bit (33) + 1
+! !"last frame of this message" flag (34)
+! integer nframes !Frames in this message (max = 16)
+! Output: character*80 message !JTTY message, as it appears to a user
+! logical trailing_sep (optional) !True if the last frame
+! processed appended an implicit separator column.
+! logical is_last_frame (optional) !True if the last frame
+! processed had its "last frame of message" flag
+! set -- for callers (e.g. jtty_mdecode's slot
+! accumulation) that decode one frame at a time and
+! need to know when a message is complete.
+!
+! Frame decoding flow:
+! 1. Read the class bits once for each 32-bit payload.
+! 2. Dispatch only assigned frame forms.
+! 3. Append through one bounds-safe path.
+
+ character*80 message
+ character*34 c32(MAX_FRAMES)
+ logical, intent(out), optional :: trailing_sep
+ logical, intent(out), optional :: is_last_frame
+ logical, intent(out), optional :: source_valid
+
+ character*80 rendered
+ type(jtty_source_atom) atom
+ logical last_frame_sep
+ logical last_frame_flag
+ logical frame_valid,render_valid,frame_eom,all_valid
+
+ message=''
+ k=1
+ last_frame_sep=.false.
+ last_frame_flag=.false.
+ all_valid=nframes.ge.1 .and. nframes.le.MAX_FRAMES
+ do iframe=1,max(0,min(nframes,MAX_FRAMES))
+ last_frame_sep=.false.
+ last_frame_flag=.false.
+ call unpack_jtty_atom(c32(iframe),atom,frame_valid,frame_eom)
+ if(.not.frame_valid) then
+ all_valid=.false.
+ cycle
+ endif
+ call render_jtty_atom(atom,rendered,render_valid)
+ if(.not.render_valid) then
+ all_valid=.false.
+ cycle
+ endif
+ last_frame_flag=frame_eom
+ if(atom%kind.eq.JTTY_ATOM_TEXT5) then
+ call append_payload_chars()
+ else
+ call append_text(rendered(1:len_trim(rendered)))
+ call append_implicit_separator()
+ endif
+
+ enddo
+
+ if(present(trailing_sep)) trailing_sep=last_frame_sep
+ if(present(is_last_frame)) is_last_frame=last_frame_flag .and. all_valid
+ if(present(source_valid)) source_valid=all_valid
+
+ return
+
+contains
+
+ subroutine append_text(text)
+ character*(*) text
+ integer i
+
+ do i=1,len(text)
+ if(k.le.len(message)) message(k:k)=text(i:i)
+ k=k+1
+ enddo
+ end subroutine append_text
+
+ subroutine append_payload_chars()
+ ! TEXT5 carries five 6-bit JTTY characters in the upper 30 bits.
+ integer n30, j, idx
+ character*1 c
+
+ read(c32(iframe),1006) n30
+1006 format(b30.30)
+ do j=1,5
+ idx=iand(ishft(n30,-6*(5-j)),63)
+ c=charj(idx)
+ if(c.eq.' ') c='~'
+ if(k.le.len(message)) message(k:k)=c
+ k=k+1
+ enddo
+ end subroutine append_payload_chars
+
+ subroutine append_implicit_separator()
+ ! Structured frames leave one blank column before any following frame.
+ k=k+1
+ last_frame_sep=.true.
+ end subroutine append_implicit_separator
+
+end subroutine unpack_jtty
+
+
+character*1 function charj(j)
+
+! Returns the printable character corresponding to JTTY index j (0-63),
+
+ charj=source_char(j)
+
+ return
+end function charj
+
+integer function jchar(c0)
+
+! Returns the JTTY index (0-63) corresponding to character c0.
+
+ character*1 c0
+
+ jchar=source_index(c0)
+
+ return
+end function jchar
+
+end module jtty_mod
diff --git a/lib/jtty/jtty_msgs.txt b/lib/jtty/jtty_msgs.txt
new file mode 100644
index 00000000..f97d8ad1
--- /dev/null
+++ b/lib/jtty/jtty_msgs.txt
@@ -0,0 +1,23 @@
+CQ KA1ABC CQ
+WB9XYZ
+TU KA1ABC CQ
+WB9XYZ TU
+WB9XYZ AGN?
+WB9XYZ TU CQ KA1ABC CQ
+TU NOW JA6DEF 599 123
+WB9XYZ 599 0123
+WB9XYZ NR?
+
+599 1234
+599 MA
+599 FN42
+599 BRUCE
+
+PJ4/KA1ABC
+CQ KA1ABC
+CQ PJ4/KA1ABC CQ
+PJ4/KA1ABC 599 124
+
+
+THE QUICK BROWN FOX JUMPED OVER THE LAZY DOG.
+0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ +-./?!"#$%,&*()_'=[]{}<>|:;
diff --git a/lib/jtty/jtty_n1mm_integration.md b/lib/jtty/jtty_n1mm_integration.md
new file mode 100644
index 00000000..63125cc9
--- /dev/null
+++ b/lib/jtty/jtty_n1mm_integration.md
@@ -0,0 +1,140 @@
+# JTTY and N1MM Logger+ Integration
+
+## Summary
+
+N1MM Logger+ can send either literal JTTY text or an explicit native action. Ordinary TXTEXT uses automatic minimum-frame packing after text and exchange-profile normalization, combining recognized compact forms with TEXT5. Explicit typed exchanges use a leading `[[JTTY:<ACTION>]]` marker in the transmitted text. The marker is consumed by WSJT-X and is never put on the air.
+
+The bundled `JTTY Messages.mc` uses tagged actions for its common Run and S&P messages. This provides compact Call8 and STRUCT30 transmission without asking WSJT-X to infer meaning from visible logger text.
+
+## Setup
+
+- Configure N1MM Logger+ with WSJT-X as for FT8. A starting point is [Operating WW Digi with N1MM and WSJT-X](https://www.rttycontesting.com/tutorials/n1mm/operating-ww-digi-with-n1mm/).
+- Verify radio control, PTT, audio, and the `forEW1` configuration in FT8 before selecting JTTY.
+- Enter `JTTY` in the N1MM callsign field and press Enter to start WSJT-X in JTTY mode.
+- Confirm that the WSJT-X footer shows JTTY and the window title contains `forEW1`.
+- Use radio test mode, zero output power, or a dummy load for initial checks.
+- Save the existing Digital Function Key file before loading the supplied `JTTY Messages.mc` example.
+
+End-to-end validation with N1MM on Windows, including two-radio focus, call selection, queue movement, and Run/S&P state transitions, remains required before release.
+
+## Literal TXTEXT
+
+N1MM expands logger macros before passing TXTEXT to WSJT-X. An untagged result uses the literal source interface:
+
+- lowercase letters become uppercase;
+- leading, trailing, and repeated spaces are removed;
+- unsupported characters become `#`;
+- explicit RTTY Roundup canonicalizes eligible report-prefixed decimal serials;
+- recognized calls, control phrases, generic numbers, full generic QTH exchanges, grids, and class/section pairs compete with TEXT5 for the minimum frame count;
+- every compact candidate must preserve its source text exactly after normalization.
+
+`CQ N9ADG CQ`, `N9ADG`, `599 123`, `599 MA`, `599 FN42`, and `1D EMA` each use one frame without a tag. Recognition works at token boundaries inside longer messages as well. The existing special operating activity supplies a profile captured when each message is submitted. No activity selects Unknown, even though native macros default to serials. Field Day uses the same context-free candidates as Unknown.
+
+RTTY Roundup additionally recognizes full `599 <number>` SERIAL and full `599 <location>` STATE_PROVINCE exchanges under the native rules; locations must contain a letter. Before packing, decimal tokens following a complete `599` token are normalized as serials: `599 05` becomes `599 005`, and `599 0123` becomes `599 123`, each in one frame. Eligible tokens have one to six digits and value 0-131071. Unsupported tokens keep their spelling for normal fallback. `599 001` takes one frame in RTTY Roundup and two otherwise, and `K1ABC 599 001` takes two in RTTY Roundup.
+
+Bare digits and all Unknown or Field Day input retain their spelling after ordinary text normalization. Every compact candidate must exactly match the resulting normalized text. The canonical message is returned to the GUI for display and logging; expansion beyond 80 characters is rejected rather than truncated. Tagged exchanges retain explicit type semantics. The full recognition policy and spacing constraints are in [`jtty_design.md`](jtty_design.md).
+
+The former `i2=2` shortcut for literal `599 ` plus five characters has been replaced by STRUCT30. There is no compatibility discriminator: an old receiver displays new STRUCT30 bits as `599` text, and some old type-2 frames are valid new STRUCT30 words with a different meaning. JTTY is unreleased, so no legacy decoder mode is retained.
+
+## Tagged TXTEXT grammar
+
+Place the marker so it is the leading transmitted text. Non-transmitting N1MM
+commands may execute between `{TX}` and the marker:
+
+```text
+{TX}[[JTTY:<ACTION>]]<payload>{RX}
+```
+
+N1MM expands `{MYCALL}`, `!` or `{CALL}`, and `{EXCH}`. WSJT-X removes the marker, normalizes whitespace and case in the expanded payload, and validates it under the selected action and active JTTY profile. Tag and action matching is case-insensitive, but the tag must start at the first non-space transmitted character.
+
+| Action | Expanded payload | Native sequence |
+| --- | --- | --- |
+| `CQ` | `<mycall>` | CQ with my call |
+| `CALL_EXCH` | `<hiscall> <exchange>` | His call, configured full exchange |
+| `CALL_TU_CQ` | `<hiscall> <mycall>` | His call/TU, CQ with my call |
+| `MYCALL` | `<mycall>` | My call |
+| `HISCALL` | `<hiscall>` | His call |
+| `TU_NOW_EXCH` | `<hiscall> <exchange>` | TU NOW/his call, configured full exchange |
+| `CALL_MY` | `<hiscall> <mycall>` | His call, my call |
+| `CALL_TU_MY` | `<hiscall> <mycall>` | His call/TU, my call |
+| `EXCH` | `<exchange>` | Configured full exchange |
+| `GRID` | `<grid4>` | Field-only GRID4 |
+| `CONTROL` | `<registered phrase>` | Registered control phrase |
+
+Payloads contain dynamic values, not the phrases implied by an action. For
+example, `CQ` receives only the callsign, `CALL_TU_CQ` receives two callsigns,
+and `TU_NOW_EXCH` receives a callsign and exchange. The action supplies `CQ`,
+`TU`, `TU NOW`, and canonical full-exchange report text where applicable. Do
+not add a hardcoded `599` to an exchange payload.
+
+Profile exchange payloads are:
+
+- Default: one decimal serial in the 17-bit serial domain.
+- `FIELD_DAY`: exactly `<count><class> <section>`, with count 1-32, class A-F, and a registered ARRL/RAC section.
+- `RTTY`: either one decimal serial or one canonical two- or three-character state/province token. A three-character token may not have a leading zero because its two-character spelling would be canonical.
+
+For tagged N1MM input, `DX` is an expanded two-letter location token. The
+special `DX` and `#` meanings that select the live serial apply only to the
+local WSJT-X RTTY `%E` configuration.
+
+`GRID` accepts exactly one valid four-character Maidenhead locator. `CONTROL` accepts exactly one of the 18 registered phrases, including spaces and punctuation where shown in `jtty_source_encoding.txt`.
+
+An unknown or malformed leading JTTY marker, unsupported action, missing field, invalid call, invalid profile exchange, invalid grid, or unregistered control phrase is rejected. It never falls back to literal transmission. Untagged messages, including customized N1MM macros, use automatic text packing with the exchange profile captured at submission. A tag-shaped substring later in the text is just literal text.
+
+An all-rejected transaction receives `OUTPUTCOMPLETE` at `XMIT OFF`. When a transaction also contains accepted or pending audio, completion waits until that audio has drained. `ABORT` clears the transaction without reporting a successful output completion.
+
+## Bundled action mappings
+
+The supplied macro file deliberately omits hardcoded `599`. Full-role native exchanges render the report canonically when the selected profile calls for it; Field Day class/section does not.
+
+| Context | Key | Tagged meaning |
+| --- | --- | --- |
+| Run | F1 | `CQ` |
+| Run | F2 | `CALL_EXCH` |
+| Run | F3 | `CALL_TU_CQ` |
+| Run | F4 | `MYCALL` |
+| Run | F5 | `HISCALL` |
+| Run | F6 | `CONTROL NR?` |
+| Run | F8 | `CONTROL AGN?` |
+| S&P | F1 | `CQ` |
+| S&P | F2 | `CALL_EXCH` |
+| S&P | F3 | `CALL_TU_MY` |
+| S&P | F4 | `CALL_MY` |
+| S&P | F5 | `HISCALL` |
+| S&P | F6 | `MYCALL` |
+| S&P | F7 | `EXCH` |
+| S&P | F8 | `CONTROL AGN?` |
+
+Run F11 is intentionally left spare. N1MM call stacking can transmit a call
+correction before `{LOGTHENPOP}` and change the station referenced by subsequent
+callsign and exchange macros. That sequence cannot satisfy the leading-tag
+contract reliably without validated N1MM TXTEXT ordering. `TU_NOW_EXCH` remains
+available for an explicit leading tag whose already-expanded payload names the
+intended station and exchange.
+
+## Native WSJT-X function keys
+
+The WSJT-X JTTY editor offers the same native subset without an N1MM tag. The shipped defaults are:
+
+| Key | Template |
+| --- | --- |
+| F1 | `CQ %M CQ` |
+| F2 | `%H %E` |
+| F3 | `%H TU CQ %M CQ` |
+| F4 | `%M` |
+| F5 | `%H` |
+| F6 | `TU NOW %Q %E` |
+| F7 | `%H AGN?` |
+| F8 | `%E` |
+
+`%E` is the configured profile exchange. `%G` is a field-only GRID4, while the exact template `599 %G` selects full-role GRID4. Current templates and control phrases match before expansion after case and whitespace normalization.
+
+The exact former F2, F6, and F8 defaults (`%H 599 %N`, `TU NOW %Q 599 %N`, and `599 %N`) remain recognized during migration and are replaced by `%E` only when unchanged in saved settings. An edited old default is a customized literal template. Likewise, an unrecognized current template uses automatic text packing after normal expansion. A recognized native template with invalid runtime data is rejected rather than changing semantics through fallback.
+
+Clickable F1-F8 buttons and keyboard shortcuts select the same actions. Native sequences set EOM only on their final atom and do not add a TEXT5 spacing frame between queued messages.
+
+## Current scope
+
+The practical tagged and GUI native transmit subset includes Call8, serial and RTTY state/province exchanges, Field Day class/section, GRID4, and registered controls. Automatic text packing additionally uses GENERIC_NUMERIC and GENERIC_QTH. The full wire codec also validates and canonically renders other STRUCT30 number/location kinds, ZONE_LOC3, and EXCH_NUM_TIME. Those remaining forms are receive-only in the current operator-facing integration unless an explicit native codec caller constructs them; they are not inferred from ordinary text.
+
+The complete wire definition is in [`jtty_source_encoding.txt`](jtty_source_encoding.txt).
diff --git a/lib/jtty/jtty_payload_correlators.f90 b/lib/jtty/jtty_payload_correlators.f90
new file mode 100644
index 00000000..296ffe69
--- /dev/null
+++ b/lib/jtty/jtty_payload_correlators.f90
@@ -0,0 +1,108 @@
+module jtty_payload_correlators
+ use, intrinsic :: iso_fortran_env, only: int32, real32, real64
+ implicit none
+ private
+
+ real(real32), parameter :: TWO_PI = 6.2831853071795864769_real32
+
+ type, public :: jtty_payload_correlator
+ private
+ integer(int32) :: samples_per_symbol = 0_int32
+ real(real32), allocatable :: reference_real(:,:)
+ real(real32), allocatable :: reference_imaginary(:,:)
+ end type jtty_payload_correlator
+
+ public :: jtty_payload_correlator_prepare
+ public :: jtty_correlate_payload_symbols
+
+contains
+
+ subroutine jtty_payload_correlator_prepare(correlator, samples_per_symbol)
+ type(jtty_payload_correlator), intent(inout) :: correlator
+ integer(int32), intent(in) :: samples_per_symbol
+ real(real32) :: phase, phase_step
+ integer :: sample, tone
+
+ if (samples_per_symbol <= 0_int32 .or. modulo(samples_per_symbol,2_int32) /= 0_int32) &
+ error stop 'invalid JTTY payload symbol length'
+ if (correlator%samples_per_symbol == samples_per_symbol .and. &
+ allocated(correlator%reference_real) .and. &
+ allocated(correlator%reference_imaginary)) return
+
+ correlator%samples_per_symbol = samples_per_symbol
+ if (allocated(correlator%reference_real)) deallocate(correlator%reference_real)
+ if (allocated(correlator%reference_imaginary)) &
+ deallocate(correlator%reference_imaginary)
+ allocate(correlator%reference_real(0:3,0:samples_per_symbol-1))
+ allocate(correlator%reference_imaginary(0:3,0:samples_per_symbol-1))
+
+ do tone = 0, 3
+ phase = 0.0_real32
+ phase_step = TWO_PI*real(tone,real32)/real(samples_per_symbol,real32)
+ do sample = 0, samples_per_symbol - 1
+ correlator%reference_real(tone,sample) = cos(phase)
+ correlator%reference_imaginary(tone,sample) = sin(phase)
+ phase = phase + phase_step
+ end do
+ end do
+ end subroutine jtty_payload_correlator_prepare
+
+ subroutine jtty_correlate_payload_symbols(correlator, samples, payload_start, &
+ correlations, half_correlations)
+ ! Samples are candidate-centered analytic baseband; payload_start is zero-based.
+ type(jtty_payload_correlator), intent(in) :: correlator
+ complex(real32), intent(in) :: samples(0:)
+ integer(int32), intent(in) :: payload_start
+ complex(real32), intent(out) :: correlations(0:,:), half_correlations(0:,:)
+ real(real32) :: sample_real, sample_imaginary
+ real(real32) :: full_real(0:3), full_imaginary(0:3)
+ real(real32) :: half_real(0:3), half_imaginary(0:3)
+ real(real32) :: product_rr(0:3), product_ii(0:3), product_ri(0:3), product_ir(0:3)
+ real(real64) :: energy(0:3)
+ integer :: available_symbols, first, offset, segment, half_length, symbol, tone
+
+ if (.not.allocated(correlator%reference_real) .or. &
+ correlator%samples_per_symbol <= 0_int32) &
+ error stop 'unprepared JTTY payload correlator'
+ if (size(correlations,1) /= 4 .or. any(shape(correlations) /= shape(half_correlations))) &
+ error stop 'invalid JTTY payload correlation shape'
+ if (payload_start < 0_int32) error stop 'invalid JTTY payload offset'
+ correlations = cmplx(0.0_real32,0.0_real32,real32)
+ half_correlations = cmplx(0.0_real32,0.0_real32,real32)
+ if (payload_start >= size(samples)) return
+ available_symbols = min(size(correlations,2), &
+ (size(samples)-payload_start)/correlator%samples_per_symbol)
+ half_length = correlator%samples_per_symbol/2
+
+ do symbol = 1, available_symbols
+ first = payload_start + (symbol - 1)*correlator%samples_per_symbol
+ full_real = 0.0_real32
+ full_imaginary = 0.0_real32
+ energy = 0.0_real64
+ do segment = 0, 1
+ half_real = 0.0_real32
+ half_imaginary = 0.0_real32
+ do offset = segment*half_length, (segment+1)*half_length-1
+ sample_real = real(samples(first+offset),real32)
+ sample_imaginary = aimag(samples(first+offset))
+ product_rr = correlator%reference_real(:,offset)*sample_real
+ product_ii = correlator%reference_imaginary(:,offset)*sample_imaginary
+ product_ri = correlator%reference_real(:,offset)*sample_imaginary
+ product_ir = correlator%reference_imaginary(:,offset)*sample_real
+ ! Preserve each observation's accumulation order while sharing products.
+ full_real = full_real + product_rr + product_ii
+ full_imaginary = full_imaginary + product_ri - product_ir
+ half_real = half_real + product_rr + product_ii
+ half_imaginary = half_imaginary + product_ri - product_ir
+ end do
+ energy = energy + real(half_real*half_real + half_imaginary*half_imaginary,real64)
+ end do
+ do tone = 0, 3
+ correlations(tone,symbol) = cmplx(full_real(tone),full_imaginary(tone),real32)
+ half_correlations(tone,symbol) = &
+ cmplx(real(sqrt(max(0.0_real64,energy(tone))),real32),0.0_real32,real32)
+ end do
+ end do
+ end subroutine jtty_correlate_payload_symbols
+
+end module jtty_payload_correlators
diff --git a/lib/jtty/jtty_peakup.f90 b/lib/jtty/jtty_peakup.f90
new file mode 100644
index 00000000..80afcbe2
--- /dev/null
+++ b/lib/jtty/jtty_peakup.f90
@@ -0,0 +1,146 @@
+subroutine jtty_peakup(c0,c1,csync,nchunk,nss,xdt0,f0,xdt,f1,snr)
+ implicit none
+
+ complex, intent(in) :: c0(0:nchunk-1) !Complex data at 6000 S/s
+ complex :: c1(0:nchunk-1) !Work array
+ complex, intent(in) :: csync(0:13*nss-1)
+ complex :: c(0:13*nss-1) !Lengh of Barker sequence
+ complex :: z
+ complex :: zcur(0:12), zbest(0:12), ztot
+ complex :: qstep(0:12)
+ real :: a(3)
+ real :: fsample, dt, pmax, fpk, xdtpk, xnorm, p
+ real :: phase(0:12), uw(0:12)
+ real :: dphi, xm, ym, sxy, sxx, slope, intercept
+ real :: resid, resid_rms, dfhz, tsym
+ integer, intent(in) :: nchunk, nss
+ integer :: i, i0, ia, ib, idf, istart, iend, npsync, r
+ integer, parameter :: hop=4
+ real, intent(in) :: xdt0, f0
+ real, intent(out) :: xdt, f1, snr
+ real, parameter :: TWOPI = 6.283185307179586
+ real, parameter :: PI = 3.141592653589793
+
+ npsync=13*nss ! size of the sync waveform array
+ do i=0,12
+ istart=i*nss
+ qstep(i)=csync(istart+hop)*conjg(csync(istart))
+ enddo
+ fsample=6000.0
+ dt=1.0/fsample
+ ia=max(0,nint((xdt0-0.004)/dt))
+ ! ib must bound the i0 loop against c1's actual size (nchunk), not
+ ! npsync (an unrelated length) -- else ib<ia silently returns f1=xdt=0.
+ ib=min(nchunk-npsync,nint((xdt0+0.004)/dt))
+
+ pmax=0.
+ fpk=0.
+ xdtpk=0.
+ c1=cmplx(0.,0.)
+ xnorm=sum(abs(c0(0:nchunk-1)))/real(nchunk)
+ do idf=-5,5
+ a=0.
+ a(1)=-f0 + 0.5*idf !Shift assumed peak to zero frequency
+ call twkfreq(c0,c1,ib+npsync,fsample,a)
+ if(ia.le.ib) then
+ c(0:npsync-1)=conjg(csync)*c1(ia:ia+npsync-1)
+ do i=0,12
+ istart=i*nss
+ iend=istart+nss-1
+ zcur(i)=sum(c(istart:iend))
+ enddo
+ endif
+ do i0=ia,ib,hop !Search over xdt for sync pattern
+ xdt=i0*dt
+ if(ia.le.ib) then
+! Coherent only within a symbol (32ms) here; this locates the sync
+! instant. Stage 2 below refines f1 with a coherent combination across
+! all 13 symbols once that instant is known.
+ p=0
+ do i=0,12
+ z=zcur(i)
+ p=p+real(z)**2+aimag(z)**2
+ enddo
+ if(p.gt.pmax) then
+ pmax=p
+ fpk=-a(1)
+ xdtpk=i0*dt
+ zbest=zcur
+ endif
+ if(i0+hop.le.ib) then
+ do i=0,12
+ istart=i*nss
+ z=cmplx(0.,0.)
+ do r=0,hop-1
+ z=z+conjg(csync(istart+r))*c1(i0+istart+r)
+ enddo
+ zcur(i)=qstep(i)*(zcur(i)-z)
+ z=cmplx(0.,0.)
+ do r=0,hop-1
+ z=z+conjg(csync(istart+nss-hop+r))* &
+ c1(i0+istart+nss+r)
+ enddo
+ zcur(i)=zcur(i)+z
+ enddo
+ endif
+ endif
+ enddo
+ enddo
+
+ ! Stage 2: the winning candidate's 13 per-symbol phasors carry a near-
+ ! linear phase ramp vs. symbol index, from the sub-0.5-Hz residual
+ ! frequency error the coarse idf grid above can't resolve. Fit and
+ ! remove that ramp, then combine all 13 symbols coherently for a
+ ! sharper f1.
+ if(pmax.gt.0.) then
+ tsym=nss/fsample
+ do i=0,12
+ phase(i)=atan2(aimag(zbest(i)),real(zbest(i)))
+ enddo
+ uw(0)=phase(0)
+ do i=1,12
+ dphi=phase(i)-phase(i-1)
+ do while(dphi.gt.PI)
+ dphi=dphi-TWOPI
+ enddo
+ do while(dphi.lt.-PI)
+ dphi=dphi+TWOPI
+ enddo
+ uw(i)=uw(i-1)+dphi
+ enddo
+ xm=6.0 !mean symbol index (0..12)
+ ym=sum(uw)/13.0
+ sxy=0.
+ sxx=0.
+ do i=0,12
+ sxy=sxy+(real(i)-xm)*(uw(i)-ym)
+ sxx=sxx+(real(i)-xm)**2
+ enddo
+ slope=sxy/sxx
+ intercept=ym-slope*xm
+ resid_rms=0.
+ do i=0,12
+ resid=uw(i)-(slope*real(i)+intercept)
+ resid_rms=resid_rms+resid**2
+ enddo
+ resid_rms=sqrt(resid_rms/13.0)
+ dfhz=slope/(TWOPI*tsym)
+
+ ! Guardrails: only trust the refinement when the fit is clean (this
+ ! sharpens the coarse estimate, it doesn't replace it) and the
+ ! correction stays within the coarse grid's own 0.5 Hz step.
+ if(resid_rms.lt.1.0 .and. abs(dfhz).le.0.5) then
+ ztot=cmplx(0.,0.)
+ do i=0,12
+ ztot=ztot+zbest(i)*cmplx(cos(-slope*i),sin(-slope*i))
+ enddo
+ fpk=fpk+dfhz
+ pmax=real(ztot)**2+aimag(ztot)**2
+ endif
+ endif
+
+ f1=fpk
+ xdt=xdtpk
+ snr=pmax
+ return
+end subroutine jtty_peakup
diff --git a/lib/jtty/jtty_source_codec.f90 b/lib/jtty/jtty_source_codec.f90
new file mode 100644
index 00000000..e73a62ad
--- /dev/null
+++ b/lib/jtty/jtty_source_codec.f90
@@ -0,0 +1,470 @@
+module jtty_source_codec
+ use iso_c_binding, only: c_char,c_int,c_int8_t,c_int32_t
+ use packjt77, only: pack28,unpack28
+ use packjt77_grammar, only: PACK77_NSEC,PACK77_ARRL_SECTIONS
+ implicit none
+
+! i2.n2 Example Bits Total Purpose
+! 0.0 CQ K1ABC CQ 28+2+2 32 CQ call action
+! 0.1 K1ABC 28+2+2 32 bare call action
+! 0.2 TU K1ABC CQ 28+2+2 32 TU/CQ call action
+! 0.3 K1ABC TU 28+2+2 32 call/TU action
+! 1.0 K1ABC AGN? 28+2+2 32 call/AGN action
+! 1.1 TU NOW K1ABC 28+2+2 32 TU NOW/call action
+! 1.2-3 reserved 28+2+2 32 invalid in version 1
+! 2.x STRUCT30 27+3+2 32 typed structured source atom
+! 3.x TEXT5 30+2 32 five six-bit JTTY characters
+!
+! family Name Body fields, from bit 1 toward bit 27
+! 000 EXCH_NUM role1 + number_kind4 + value17 + zero5
+! 001 EXCH_LOC role1 + location_kind4 + length1 + token16 + zero5
+! 010 EXCH_PAIR pair_schema3 + pair_data23 + zero1
+! 011 EXCH_NUM_TIME role1 + serial14 + minute_of_day11 + zero1
+! 100 MISC subtype4 + subtype_data23
+! 101-110 reserved invalid in version 1
+! 111 guard space always invalid
+
+ integer, parameter :: I8=selected_int_kind(18)
+ character(len=*), parameter :: ALPHABET = &
+ '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ +-./?!"#$%,&*()_''=[]{}<>|:;'
+ integer, parameter :: JTTY_ATOM_CALL=0,JTTY_ATOM_EXCH_NUM=1
+ integer, parameter :: JTTY_ATOM_EXCH_LOC=2,JTTY_ATOM_EXCH_PAIR=3
+ integer, parameter :: JTTY_ATOM_EXCH_NUM_TIME=4,JTTY_ATOM_CONTROL=5
+ integer, parameter :: JTTY_ATOM_GRID4=6,JTTY_ATOM_TEXT5=7
+ integer, parameter :: JTTY_CALL_CQ=0,JTTY_CALL_CALL=1,JTTY_CALL_TU_CQ=2
+ integer, parameter :: JTTY_CALL_CALL_TU=3,JTTY_CALL_CALL_AGN=4,JTTY_CALL_TU_NOW=5
+ integer, parameter :: JTTY_ROLE_FIELD_ONLY=0,JTTY_ROLE_FULL=1
+ integer, parameter :: JTTY_NUM_SERIAL=0,JTTY_NUM_CQ_ZONE=1,JTTY_NUM_ITU_ZONE=2
+ integer, parameter :: JTTY_NUM_AGE=3,JTTY_NUM_POWER=4,JTTY_NUM_CHECK=5
+ integer, parameter :: JTTY_NUM_LICENSE_YEAR=6,JTTY_NUM_GENERIC=7
+ integer, parameter :: JTTY_LOC_STATE_PROVINCE=0,JTTY_LOC_SECTION=1
+ integer, parameter :: JTTY_LOC_COUNTRY_PREFIX=2,JTTY_LOC_QTH=3,JTTY_LOC_ADMIN_CODE=4
+ integer, parameter :: JTTY_PAIR_ZONE_LOC3=0,JTTY_PAIR_CLASS_SECTION=1
+ integer, parameter :: JTTY_MISC_CONTROL=0,JTTY_MISC_GRID4=1
+ integer(c_int), parameter :: JTTY_ENCODE_OK=0,JTTY_ENCODE_INVALID_DESCRIPTOR=1
+ integer(c_int), parameter :: JTTY_ENCODE_UNKNOWN_SECTION=2
+ integer, parameter :: JTTY_CONTROL_AGN=0,JTTY_CONTROL_CALL=1,JTTY_CONTROL_AGN_CALL=2
+ integer, parameter :: JTTY_CONTROL_NR=3,JTTY_CONTROL_AGN_NR=4,JTTY_CONTROL_EXCH=5
+ integer, parameter :: JTTY_CONTROL_STATE=6,JTTY_CONTROL_SECTION=7,JTTY_CONTROL_ZONE=8
+ integer, parameter :: JTTY_CONTROL_GRID=9,JTTY_CONTROL_RPRT=10,JTTY_CONTROL_QSL_TU=11
+ integer, parameter :: JTTY_CONTROL_TU=12,JTTY_CONTROL_QRZ=13,JTTY_CONTROL_QSO_B4=14
+ integer, parameter :: JTTY_CONTROL_WAIT=15,JTTY_CONTROL_NIL=16,JTTY_CONTROL_OK=17
+ character(len=8), parameter :: CONTROL_TEXT(0:17)=[character(len=8) :: &
+ 'AGN?','CALL?','AGN CALL','NR?','AGN NR','EXCH?','STATE?','SECTION?', &
+ 'ZONE?','GRID?','RPRT?','QSL TU','TU','QRZ?','QSO B4','WAIT','NIL?','OK?']
+
+ type :: jtty_source_atom
+ integer :: kind=-1,subtype=0,role=JTTY_ROLE_FIELD_ONLY,value=0,value2=0
+ character(len=13) :: text=''
+ end type jtty_source_atom
+
+ type, bind(C) :: jtty_source_atom_c
+ integer(c_int8_t) :: kind,subtype,role,reserved
+ integer(c_int32_t) :: value
+ character(kind=c_char) :: text(9)
+ end type jtty_source_atom_c
+
+contains
+
+subroutine pack_jtty_atom(atom,frame,eom,valid)
+ type(jtty_source_atom), intent(in) :: atom
+ character(len=34), intent(out) :: frame
+ logical, intent(in) :: eom
+ logical, intent(out) :: valid
+ integer(I8) :: body,top30,n32,token_value,pair_data,data
+ integer :: i,n28,i2,n2,n,grid_index,class_index
+ character(len=13) :: call_text,roundtrip
+ character(len=5) :: text5
+ logical :: success
+ frame=''; valid=.false.; n32=0
+ select case(atom%kind)
+ case(JTTY_ATOM_CALL)
+ if(atom%subtype.lt.0 .or. atom%subtype.gt.5) return
+ call_text=atom%text
+ if(.not.standard_call(call_text)) return
+ call pack28(call_text,n28); call unpack28(n28,roundtrip,success)
+ if(.not.success .or. trim(roundtrip).ne.trim(call_text)) return
+ if(atom%subtype.le.3) then; i2=0; n2=atom%subtype
+ else; i2=1; n2=atom%subtype-4; endif
+ n32=ishft(int(n28,I8),4)+4*n2+i2
+ case(JTTY_ATOM_EXCH_NUM)
+ if(.not.valid_role(atom%role) .or. .not.valid_number(atom%subtype,atom%value)) return
+ body=ishft(int(atom%role,I8),26)+ishft(int(atom%subtype,I8),22)+ishft(int(atom%value,I8),5)
+ call finish_struct(body,0,n32)
+ case(JTTY_ATOM_EXCH_LOC)
+ if(.not.valid_role(atom%role) .or. atom%subtype.lt.0 .or. atom%subtype.gt.4) return
+ n=len_trim(atom%text); if(n.ne.2 .and. n.ne.3) return
+ call pack_base36(atom%text(1:n),token_value,success); if(.not.success) return
+ body=ishft(int(atom%role,I8),26)+ishft(int(atom%subtype,I8),22)+ &
+ ishft(int(n-2,I8),21)+ishft(token_value,5)
+ call finish_struct(body,1,n32)
+ case(JTTY_ATOM_EXCH_PAIR)
+ select case(atom%subtype)
+ case(JTTY_PAIR_ZONE_LOC3)
+ if(atom%value.lt.1 .or. atom%value.gt.40) return
+ n=len_trim(atom%text); if(n.ne.2 .and. n.ne.3) return
+ call pack_base36(atom%text(1:n),token_value,success); if(.not.success) return
+ pair_data=ishft(int(atom%value,I8),17)+ishft(int(n-2,I8),16)+token_value
+ case(JTTY_PAIR_CLASS_SECTION)
+ if(atom%value.lt.1 .or. atom%value.gt.32) return
+ if(atom%value2.lt.1 .or. atom%value2.gt.PACK77_NSEC .or. len_trim(atom%text).ne.1) return
+ class_index=ichar(atom%text(1:1))-ichar('A'); if(class_index.lt.0 .or. class_index.gt.5) return
+ pair_data=ishft(int(atom%value,I8),17)+ishft(int(class_index,I8),14)+ &
+ ishft(int(atom%value2,I8),7)
+ case default; return
+ end select
+ body=ishft(int(atom%subtype,I8),24)+ishft(pair_data,1); call finish_struct(body,2,n32)
+ case(JTTY_ATOM_EXCH_NUM_TIME)
+ if(.not.valid_role(atom%role) .or. atom%value.lt.0 .or. atom%value.gt.16383) return
+ if(atom%value2.lt.0 .or. atom%value2.gt.1439) return
+ body=ishft(int(atom%role,I8),26)+ishft(int(atom%value,I8),12)+ishft(int(atom%value2,I8),1)
+ call finish_struct(body,3,n32)
+ case(JTTY_ATOM_CONTROL)
+ if(atom%subtype.lt.0 .or. atom%subtype.gt.17) return
+ body=ishft(int(JTTY_MISC_CONTROL,I8),23)+ishft(int(atom%subtype,I8),16)
+ call finish_struct(body,4,n32)
+ case(JTTY_ATOM_GRID4)
+ if(.not.valid_role(atom%role)) return
+ call grid4_to_index(atom%text,grid_index,success); if(.not.success) return
+ data=ishft(int(atom%role,I8),22)+ishft(int(grid_index,I8),7)
+ body=ishft(int(JTTY_MISC_GRID4,I8),23)+data; call finish_struct(body,4,n32)
+ case(JTTY_ATOM_TEXT5)
+ text5=atom%text(1:5); top30=0
+ do i=1,5
+ if(source_index(text5(i:i)).lt.0) return
+ top30=64*top30+source_index(text5(i:i))
+ enddo
+ n32=4*top30+3
+ case default; return
+ end select
+ write(frame(1:32),'(b32.32)') n32
+ frame(33:33)='0'
+ frame(34:34)=merge('1','0',eom)
+ valid=.true.
+end subroutine pack_jtty_atom
+
+subroutine finish_struct(body,family,n32)
+ integer(I8), intent(in) :: body
+ integer, intent(in) :: family
+ integer(I8), intent(out) :: n32
+ n32=4*(8*body+family)+2
+end subroutine finish_struct
+
+subroutine unpack_jtty_atom(frame,atom,valid,eom)
+ character(len=34), intent(in) :: frame
+ type(jtty_source_atom), intent(out) :: atom
+ logical, intent(out) :: valid,eom
+ integer(I8) :: top30,body,pair_data,data,token_value
+ integer :: i,i2,family,n28,n2,zero,n,grid_index,class_index
+ character(len=13) :: call_text
+ logical :: success
+ atom=jtty_source_atom(); valid=.false.; eom=.false.
+ if(verify(frame,'01').ne.0 .or. frame(33:33).ne.'0') return
+ if(frame(1:32).eq.repeat('0',32)) return
+ read(frame,'(b30.30,b2.2)') top30,i2
+ select case(i2)
+ case(0,1)
+ read(frame,'(b28.28,b2.2)') n28,n2
+ if(i2.eq.1 .and. n2.gt.1) return
+ call unpack28(n28,call_text,success)
+ if(.not.success .or. .not.standard_call(call_text)) return
+ atom=jtty_call_atom(merge(n2,n2+4,i2.eq.0),call_text)
+ case(2)
+ family=int(iand(top30,7_I8)); body=ishft(top30,-3)
+ select case(family)
+ case(0)
+ atom%kind=JTTY_ATOM_EXCH_NUM; atom%role=int(ibits(body,26,1))
+ atom%subtype=int(ibits(body,22,4)); atom%value=int(ibits(body,5,17))
+ zero=int(ibits(body,0,5))
+ if(zero.ne.0 .or. .not.valid_number(atom%subtype,atom%value)) return
+ case(1)
+ atom%kind=JTTY_ATOM_EXCH_LOC; atom%role=int(ibits(body,26,1))
+ atom%subtype=int(ibits(body,22,4)); n=int(ibits(body,21,1))+2
+ token_value=ibits(body,5,16); zero=int(ibits(body,0,5))
+ if(zero.ne.0 .or. atom%subtype.gt.4 .or. token_value.ge.36_I8**n) return
+ if(n.eq.3 .and. token_value.lt.36_I8**2) return
+ call unpack_base36(token_value,n,atom%text)
+ case(2)
+ atom%kind=JTTY_ATOM_EXCH_PAIR; atom%subtype=int(ibits(body,24,3))
+ pair_data=ibits(body,1,23); zero=int(ibits(body,0,1)); if(zero.ne.0) return
+ select case(atom%subtype)
+ case(JTTY_PAIR_ZONE_LOC3)
+ atom%value=int(ibits(pair_data,17,6)); n=int(ibits(pair_data,16,1))+2
+ token_value=ibits(pair_data,0,16)
+ if(atom%value.lt.1 .or. atom%value.gt.40 .or. token_value.ge.36_I8**n) return
+ if(n.eq.3 .and. token_value.lt.36_I8**2) return
+ call unpack_base36(token_value,n,atom%text)
+ case(JTTY_PAIR_CLASS_SECTION)
+ atom%value=int(ibits(pair_data,17,6)); class_index=int(ibits(pair_data,14,3))
+ atom%value2=int(ibits(pair_data,7,7)); zero=int(ibits(pair_data,0,7))
+ if(atom%value.lt.1 .or. atom%value.gt.32 .or. class_index.gt.5) return
+ if(atom%value2.lt.1 .or. atom%value2.gt.PACK77_NSEC .or. zero.ne.0) return
+ atom%text(1:1)=char(ichar('A')+class_index)
+ case default; return
+ end select
+ case(3)
+ atom%kind=JTTY_ATOM_EXCH_NUM_TIME; atom%role=int(ibits(body,26,1))
+ atom%value=int(ibits(body,12,14)); atom%value2=int(ibits(body,1,11))
+ zero=int(ibits(body,0,1)); if(zero.ne.0 .or. atom%value2.gt.1439) return
+ case(4)
+ i=int(ibits(body,23,4)); data=ibits(body,0,23)
+ select case(i)
+ case(JTTY_MISC_CONTROL)
+ atom%kind=JTTY_ATOM_CONTROL; atom%subtype=int(ibits(data,16,7))
+ zero=int(ibits(data,0,16)); if(zero.ne.0 .or. atom%subtype.gt.17) return
+ case(JTTY_MISC_GRID4)
+ atom%kind=JTTY_ATOM_GRID4; atom%role=int(ibits(data,22,1))
+ grid_index=int(ibits(data,7,15)); zero=int(ibits(data,0,7))
+ if(zero.ne.0 .or. grid_index.ge.32400) return
+ call index_to_grid4(grid_index,atom%text)
+ case default; return
+ end select
+ case default; return
+ end select
+ case(3)
+ atom%kind=JTTY_ATOM_TEXT5
+ do i=1,5
+ atom%text(i:i)=source_char(int(iand(ishft(top30,-6*(5-i)),63_I8)))
+ enddo
+ end select
+ eom=frame(34:34).eq.'1'
+ valid=.true.
+end subroutine unpack_jtty_atom
+
+subroutine render_jtty_atom(atom,text,valid)
+ type(jtty_source_atom), intent(in) :: atom
+ character(len=80), intent(out) :: text
+ logical, intent(out) :: valid
+ character(len=16) :: first,second
+ character(len=3) :: section
+ integer :: hours,minutes
+ text=''; valid=.true.
+ select case(atom%kind)
+ case(JTTY_ATOM_CALL)
+ select case(atom%subtype)
+ case(JTTY_CALL_CQ); text='CQ '//trim(atom%text)//' CQ'
+ case(JTTY_CALL_CALL); text=trim(atom%text)
+ case(JTTY_CALL_TU_CQ); text='TU '//trim(atom%text)//' CQ'
+ case(JTTY_CALL_CALL_TU); text=trim(atom%text)//' TU'
+ case(JTTY_CALL_CALL_AGN); text=trim(atom%text)//' AGN?'
+ case(JTTY_CALL_TU_NOW); text='TU NOW '//trim(atom%text)
+ case default; valid=.false.
+ end select
+ case(JTTY_ATOM_EXCH_NUM)
+ if(.not.valid_role(atom%role) .or. .not.valid_number(atom%subtype,atom%value)) then
+ valid=.false.; return
+ endif
+ call render_number(atom%subtype,atom%value,first); call render_role(atom%role,trim(first),text)
+ case(JTTY_ATOM_EXCH_LOC)
+ if(atom%subtype.lt.0 .or. atom%subtype.gt.4) then; valid=.false.; return; endif
+ call render_role(atom%role,trim(atom%text),text)
+ case(JTTY_ATOM_EXCH_PAIR)
+ select case(atom%subtype)
+ case(JTTY_PAIR_ZONE_LOC3)
+ write(first,'(i2.2)') atom%value; text='599 '//trim(first)//' '//trim(atom%text)
+ case(JTTY_PAIR_CLASS_SECTION)
+ if(atom%value2.lt.1 .or. atom%value2.gt.PACK77_NSEC) then; valid=.false.; return; endif
+ section=PACK77_ARRL_SECTIONS(atom%value2)
+ write(first,'(i0,a1)') atom%value,atom%text(1:1); text=trim(first)//' '//trim(section)
+ case default; valid=.false.
+ end select
+ case(JTTY_ATOM_EXCH_NUM_TIME)
+ if(.not.valid_role(atom%role) .or. atom%value.lt.0 .or. atom%value.gt.16383 .or. &
+ atom%value2.lt.0 .or. atom%value2.gt.1439) then; valid=.false.; return; endif
+ call render_number(JTTY_NUM_SERIAL,atom%value,first)
+ hours=atom%value2/60; minutes=mod(atom%value2,60)
+ write(second,'(i2.2,i2.2)') hours,minutes
+ call render_role(atom%role,trim(first)//' '//trim(second),text)
+ case(JTTY_ATOM_CONTROL)
+ if(atom%subtype.lt.0 .or. atom%subtype.gt.17) then; valid=.false.; return; endif
+ text=trim(CONTROL_TEXT(atom%subtype))
+ case(JTTY_ATOM_GRID4)
+ call render_role(atom%role,atom%text(1:4),text)
+ case(JTTY_ATOM_TEXT5); text(1:5)=atom%text(1:5)
+ case default; valid=.false.
+ end select
+end subroutine render_jtty_atom
+
+subroutine render_role(role,field,text)
+ integer, intent(in) :: role
+ character(len=*), intent(in) :: field
+ character(len=80), intent(out) :: text
+ if(role.eq.JTTY_ROLE_FULL) then; text='599 '//field; else; text=field; endif
+end subroutine render_role
+
+subroutine render_number(kind,value,text)
+ integer, intent(in) :: kind,value
+ character(len=16), intent(out) :: text
+ select case(kind)
+ case(JTTY_NUM_SERIAL)
+ if(value.lt.1000) then; write(text,'(i3.3)') value; else; write(text,'(i0)') value; endif
+ case(JTTY_NUM_CQ_ZONE,JTTY_NUM_ITU_ZONE,JTTY_NUM_CHECK)
+ if(value.lt.100) then; write(text,'(i2.2)') value; else; write(text,'(i0)') value; endif
+ case(JTTY_NUM_LICENSE_YEAR); write(text,'(i4.4)') value
+ case default; write(text,'(i0)') value
+ end select
+end subroutine render_number
+
+logical function valid_number(kind,value)
+ integer, intent(in) :: kind,value
+ valid_number=kind.ge.0 .and. kind.le.7 .and. value.ge.0 .and. value.le.131071
+ if(.not.valid_number) return
+ if(kind.eq.JTTY_NUM_CQ_ZONE) valid_number=value.ge.1 .and. value.le.40
+ if(kind.eq.JTTY_NUM_ITU_ZONE) valid_number=value.ge.1 .and. value.le.90
+ if(kind.eq.JTTY_NUM_LICENSE_YEAR) valid_number=value.le.9999
+end function valid_number
+
+logical function valid_role(role)
+ integer, intent(in) :: role
+ valid_role=role.eq.JTTY_ROLE_FIELD_ONLY .or. role.eq.JTTY_ROLE_FULL
+end function valid_role
+
+logical function standard_call(call_text)
+ character(len=13), intent(in) :: call_text
+ character(len=13) :: work,unpacked
+ character(len=6) :: base_call
+ logical :: ok,success
+ integer :: n28
+ standard_call=.false.; work=call_text
+ call chkcall(work,base_call,ok)
+ if(.not.ok .or. index(work,'/').gt.0 .or. work(1:1).eq.'Q') return
+ if(verify(trim(work),'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789').ne.0) return
+ call pack28(work,n28); call unpack28(n28,unpacked,success)
+ standard_call=success .and. trim(unpacked).eq.trim(work)
+end function standard_call
+
+type(jtty_source_atom) function jtty_call_atom(action,call) result(atom)
+ integer, intent(in) :: action
+ character(len=*), intent(in) :: call
+ atom%kind=JTTY_ATOM_CALL; atom%subtype=action; atom%text=call
+end function jtty_call_atom
+
+type(jtty_source_atom) function jtty_exch_num_atom(role,kind,value) result(atom)
+ integer, intent(in) :: role,kind,value
+ atom%kind=JTTY_ATOM_EXCH_NUM; atom%role=role; atom%subtype=kind; atom%value=value
+end function jtty_exch_num_atom
+
+type(jtty_source_atom) function jtty_exch_loc_atom(role,kind,token) result(atom)
+ integer, intent(in) :: role,kind
+ character(len=*), intent(in) :: token
+ atom%kind=JTTY_ATOM_EXCH_LOC; atom%role=role; atom%subtype=kind; atom%text=token
+end function jtty_exch_loc_atom
+
+type(jtty_source_atom) function jtty_zone_loc_atom(zone,token) result(atom)
+ integer, intent(in) :: zone
+ character(len=*), intent(in) :: token
+ atom%kind=JTTY_ATOM_EXCH_PAIR; atom%subtype=JTTY_PAIR_ZONE_LOC3
+ atom%value=zone; atom%text=token
+end function jtty_zone_loc_atom
+
+type(jtty_source_atom) function jtty_class_section_atom(count,class,section_index) result(atom)
+ integer, intent(in) :: count,section_index
+ character(len=*), intent(in) :: class
+ atom%kind=JTTY_ATOM_EXCH_PAIR; atom%subtype=JTTY_PAIR_CLASS_SECTION
+ atom%value=count; atom%value2=section_index; atom%text=class
+end function jtty_class_section_atom
+
+type(jtty_source_atom) function jtty_exch_num_time_atom(role,serial,minute_of_day) result(atom)
+ integer, intent(in) :: role,serial,minute_of_day
+ atom%kind=JTTY_ATOM_EXCH_NUM_TIME; atom%role=role
+ atom%value=serial; atom%value2=minute_of_day
+end function jtty_exch_num_time_atom
+
+type(jtty_source_atom) function jtty_control_atom(phrase_id) result(atom)
+ integer, intent(in) :: phrase_id
+ atom%kind=JTTY_ATOM_CONTROL; atom%subtype=phrase_id
+end function jtty_control_atom
+
+type(jtty_source_atom) function jtty_grid4_atom(role,grid) result(atom)
+ integer, intent(in) :: role
+ character(len=*), intent(in) :: grid
+ atom%kind=JTTY_ATOM_GRID4; atom%role=role; atom%text=grid
+end function jtty_grid4_atom
+
+type(jtty_source_atom) function jtty_text5_atom(text) result(atom)
+ character(len=*), intent(in) :: text
+ integer :: n
+ atom%kind=JTTY_ATOM_TEXT5; atom%text=''; n=min(5,len(text))
+ if(n.gt.0) atom%text(1:n)=text(1:n)
+end function jtty_text5_atom
+
+subroutine pack_jtty_atoms(atoms,natoms,frames,nframes,valid)
+ type(jtty_source_atom), intent(in) :: atoms(:)
+ integer, intent(in) :: natoms
+ character(len=34), intent(out) :: frames(:)
+ integer, intent(out) :: nframes
+ logical, intent(out) :: valid
+ integer :: i
+ frames=''; nframes=0
+ valid=natoms.ge.1 .and. natoms.le.16 .and. natoms.le.size(atoms) .and. natoms.le.size(frames)
+ if(.not.valid) return
+ do i=1,natoms
+ call pack_jtty_atom(atoms(i),frames(i),i.eq.natoms,valid)
+ if(.not.valid) then; frames=''; return; endif
+ enddo
+ nframes=natoms
+end subroutine pack_jtty_atoms
+
+subroutine pack_base36(token,value,valid)
+ character(len=*), intent(in) :: token
+ integer(I8), intent(out) :: value
+ logical, intent(out) :: valid
+ integer :: i,digit
+ value=0; valid=len(token).eq.2 .or. len(token).eq.3
+ if(.not.valid) return
+ do i=1,len(token)
+ digit=index('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ',token(i:i))-1
+ if(digit.lt.0) then; valid=.false.; return; endif
+ value=36*value+digit
+ enddo
+ if(len(token).eq.3 .and. value.lt.36_I8**2) valid=.false.
+end subroutine pack_base36
+
+subroutine unpack_base36(value,n,token)
+ integer(I8), intent(in) :: value
+ integer, intent(in) :: n
+ character(len=13), intent(out) :: token
+ integer(I8) :: work
+ integer :: i,digit
+ token=''; work=value
+ do i=n,1,-1
+ digit=int(mod(work,36_I8)); work=work/36
+ token(i:i)='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'(digit+1:digit+1)
+ enddo
+end subroutine unpack_base36
+
+subroutine grid4_to_index(grid,index_value,valid)
+ character(len=*), intent(in) :: grid
+ integer, intent(out) :: index_value
+ logical, intent(out) :: valid
+ integer :: a,b,c,d
+ index_value=0; valid=len_trim(grid).eq.4
+ if(.not.valid) return
+ a=ichar(grid(1:1))-ichar('A'); b=ichar(grid(2:2))-ichar('A')
+ c=ichar(grid(3:3))-ichar('0'); d=ichar(grid(4:4))-ichar('0')
+ valid=a.ge.0 .and. a.lt.18 .and. b.ge.0 .and. b.lt.18 .and. &
+ c.ge.0 .and. c.lt.10 .and. d.ge.0 .and. d.lt.10
+ if(valid) index_value=((a*18+b)*10+c)*10+d
+end subroutine grid4_to_index
+
+subroutine index_to_grid4(index_value,grid)
+ integer, intent(in) :: index_value
+ character(len=13), intent(out) :: grid
+ integer :: work,a,b,c,d
+ grid=''; work=index_value
+ d=mod(work,10); work=work/10; c=mod(work,10); work=work/10
+ b=mod(work,18); a=work/18
+ grid(1:4)=char(ichar('A')+a)//char(ichar('A')+b)//char(ichar('0')+c)//char(ichar('0')+d)
+end subroutine index_to_grid4
+
+integer function source_index(c)
+ character(len=1), intent(in) :: c
+ source_index=index(ALPHABET,c)-1
+end function source_index
+
+character(len=1) function source_char(i)
+ integer, intent(in) :: i
+ source_char=ALPHABET(i+1:i+1)
+end function source_char
+
+end module jtty_source_codec
diff --git a/lib/jtty/jtty_source_encoding.txt b/lib/jtty/jtty_source_encoding.txt
new file mode 100644
index 00000000..efc78c6e
--- /dev/null
+++ b/lib/jtty/jtty_source_encoding.txt
@@ -0,0 +1,380 @@
+JTTY source encoding
+
+Each JTTY frame conveys 34 source bits. Bits are numbered from left to right,
+most significant first. Bits 1-32 are the message grammar, bit 33 is reserved
+and shall be zero, and bit 34 is the universal end-of-message (EOM) flag. EOM
+is one only on the final atom of a source message. It is a sender-intended
+boundary, not evidence that earlier atoms were received or that a QSO is
+complete.
+
+The 32-bit all-zero grammar word is an invalid sentinel. A receiver shall also
+reject a source word if any reserved-zero field is nonzero or if it contains an
+unassigned type, family, subtype, enum value, or out-of-range field. These
+source-validity checks are made after FEC and CRC verification. An invalid
+source word shall not be displayed, create a receive slot, complete a message
+through EOM, or participate in signal subtraction.
+
+Top-level message space
+
+--------------------------------------------------------------------------------
+i2.n2 Example Bits Total Purpose
+--------------------------------------------------------------------------------
+0.0 CQ K1ABC CQ 28 2 30 CQ call action
+0.1 K1ABC 28 2 30 CALL action
+0.2 TU K1ABC CQ 28 2 30 TU/CQ action
+0.3 K1ABC TU 28 2 30 CALL/TU action
+1.0 K1ABC AGN? 28 2 30 CALL/AGN action
+1.1 TU NOW K1ABC 28 2 30 TU NOW/CALL action
+1.2 (reserved; invalid)
+1.3 (reserved; invalid)
+2 599 123 27 3 30 STRUCT30
+3 HELLO 6 6 6 6 6 30 TEXT5
+--------------------------------------------------------------------------------
+
+For i2=0 or 1, bits 1-28 are the existing call28 representation, bits 29-30
+are n2, and bits 31-32 are i2. Only standard calls that round-trip through the
+existing pack28/unpack28 grammar are valid JTTY call atoms. The six assigned
+actions render exactly as shown above after substituting the decoded call.
+
+For i2=3, bits 1-30 contain five six-bit characters in transmission order and
+bits 31-32 are 11. Character values 0-63 index this alphabet:
+
+ 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ +-./?!"#$%,&*()_'=[]{}<>|:;
+
+The final TEXT5 atom is padded on the right with spaces. Padding is not part of
+the rendered message.
+
+STRUCT30
+
+For i2=2, bits 1-27 are body27, bits 28-30 are family3, and bits 31-32
+are 10. Fields below are listed in bit order, from bit 1 toward bit 27.
+
+--------------------------------------------------------------------------------
+Family Name Body fields Total Status
+--------------------------------------------------------------------------------
+000 EXCH_NUM role1 kind4 value17 zero5 27 assigned
+001 EXCH_LOC role1 kind4 length1 token16 zero5 27 assigned
+010 EXCH_PAIR schema3 pair_data23 zero1 27 assigned
+011 EXCH_NUM_TIME role1 serial14 minute11 zero1 27 assigned
+100 MISC subtype4 subtype_data23 27 assigned
+101 PROFILED body27 27 reserved
+110 VERSIONED body27 27 reserved
+111 INVALID body27 27 invalid guard
+--------------------------------------------------------------------------------
+
+Families 101-111 are invalid in version 1. They reserve space for a future
+profiled/dense extension, a versioned extension, and an explicit validity
+guard, respectively. A future assignment requires a protocol revision.
+
+Common fields
+
+role1 is an utterance role:
+
+ 0 field-only; do not render a signal report
+ 1 full exchange; prefix the rendered fields with "599 "
+
+Base-36 fields use digit values 0-9 followed by A-Z. A token is accumulated
+left to right, so ABC is ((10 * 36) + 11) * 36 + 12. length1 is 0 for exactly
+two characters and 1 for exactly three characters. The token16 value shall be
+less than 36^2 for length=0. For length=1 it shall be at least 36^2 and less
+than 36^3; a three-character spelling with a leading zero would have a
+canonical two-character representation and is invalid. Lowercase and
+punctuation do not occur on the wire.
+
+EXCH_NUM, family 000
+
+--------------------------------------------------------------------------------
+Kind Name Values Canonical field rendering
+--------------------------------------------------------------------------------
+0 SERIAL 0-131071 decimal, at least three digits
+1 CQ_ZONE 1-40 decimal, at least two digits
+2 ITU_ZONE 1-90 decimal, at least two digits
+3 AGE 0-131071 decimal
+4 POWER 0-131071 decimal
+5 CHECK 0-131071 decimal, at least two digits
+6 FIRST_LICENSE_YEAR 0-9999 decimal, exactly four digits
+7 GENERIC_NUMERIC 0-131071 decimal
+8-15 (reserved; invalid)
+--------------------------------------------------------------------------------
+
+The role determines whether "599 " precedes the field. Apart from CQ and ITU
+zones and the four-digit license-year domain, the core grammar enforces only
+the 17-bit range; contest-specific limits belong to future profile validation.
+Decimal width, separators, 5NN spelling, and visible repetition are not
+represented.
+
+EXCH_LOC, family 001
+
+--------------------------------------------------------------------------------
+Kind Name
+--------------------------------------------------------------------------------
+0 STATE_PROVINCE
+1 ARRL_RAC_SECTION
+2 COUNTRY_PREFIX
+3 GENERIC_QTH
+4 LOCAL_ADMINISTRATIVE_CODE
+5-15 (reserved; invalid)
+--------------------------------------------------------------------------------
+
+The token has the base-36 and length rules above. The role determines whether
+"599 " precedes it.
+
+EXCH_PAIR, family 010
+
+--------------------------------------------------------------------------------
+Schema Name pair_data fields Valid ranges
+--------------------------------------------------------------------------------
+0 ZONE_LOC3 cq_zone6 length1 token16 zone 1-40; token as above
+1 CLASS_SECTION count6 class3 section7 zero7 count 1-32; class 0-5;
+ section 1-86
+2-7 (reserved; invalid)
+--------------------------------------------------------------------------------
+
+ZONE_LOC3 always renders "599 <zone> <token>" with a two-digit-minimum zone.
+CLASS_SECTION renders "<count><class> <section>". Class values 0-5 mean A-F;
+6-7 are invalid. Section values 1-86 index PACK77_ARRL_SECTIONS in
+lib/77bit/packjt77_grammar.f90; value zero and values 87-127 are invalid. The
+registry is deliberately shared rather than copied into this specification.
+
+EXCH_NUM_TIME, family 011
+
+ role1 + serial14 + minute_of_day11 + zero1
+
+serial is 0-16383. minute_of_day is 0-1439 and maps to UTC HHMM by division
+and remainder by 60. The serial uses at least three digits and UTC time exactly
+four digits. role=1 renders "599 <serial> <HHMM>"; role=0 omits "599 ". Values
+1440-2047 for minute_of_day are invalid.
+
+MISC, family 100
+
+--------------------------------------------------------------------------------
+Subtype Name subtype_data fields
+--------------------------------------------------------------------------------
+0 CONTROL phrase7 zero16
+1 GRID4 role1 grid4_code15 zero7
+2-15 (reserved; invalid)
+--------------------------------------------------------------------------------
+
+CONTROL phrase assignments and canonical renderings are:
+
+--------------------------------------------------------------------------------
+ID Phrase ID Phrase ID Phrase
+--------------------------------------------------------------------------------
+ 0 AGN? 6 STATE? 12 TU
+ 1 CALL? 7 SECTION? 13 QRZ?
+ 2 AGN CALL 8 ZONE? 14 QSO B4
+ 3 NR? 9 GRID? 15 WAIT
+ 4 AGN NR 10 RPRT? 16 NIL?
+ 5 EXCH? 11 QSL TU 17 OK?
+--------------------------------------------------------------------------------
+
+Phrase values 18-127 are invalid. CONTROL's sixteen reserved bits shall be
+zero.
+
+GRID4 accepts only Maidenhead fields AA00 through RR99. With A=0, the code is:
+
+ (((field_1 * 18 + field_2) * 10 + digit_1) * 10 + digit_2)
+
+Thus the valid domain is 0-32399. Values 32400-32767 are invalid. role=1
+renders "599 <GRID4>" and role=0 renders only the four-character grid.
+
+Canonical atom sequences
+
+Structured atoms are rendered independently and supply one implicit trailing
+space; TEXT5 characters are appended verbatim. The final trailing space or
+TEXT5 padding is not part of the displayed message. The receiver truncates
+the accumulated display at 80 characters. A sender
+sets bit 33 to zero on every atom and bit 34 only on the last atom. Queuing a
+second native message does not add a TEXT5 spacing atom.
+
+Ordinary keyboard text, externally queued strings, and N1MM/MMTTY strings use
+the literal source interface. They are normalized to uppercase, leading,
+trailing, and repeated ASCII spaces are removed, and unsupported characters
+become '#'. The literal wrapper accepts an 80-character input field, so longer
+caller strings are truncated before normalization. Automatic packing minimizes
+the frame count while preserving this text exactly after any explicit RTTY
+Roundup serial normalization described below. The result is
+at most sixteen frames because TEXT5 is always available as a fallback.
+
+Candidates at complete token boundaries are:
+
+ * All six call forms, with an exact standard-call codec round trip.
+ * Registered CONTROL phrases, including inside longer messages.
+ * Canonical unsigned decimal 0-131071 as GENERIC_NUMERIC, field-only or
+ preceded by "599 ". Leading zeros are not canonical except for "0".
+ * "599 " followed by a valid two- or three-character base-36 token
+ containing at least one letter, as full-role GENERIC_QTH. Canonical
+ base-36 length rules apply; numeric-only tokens cannot use this path.
+ * Valid GRID4, field-only or preceded by "599 ".
+ * Canonical CLASS_SECTION using the count, class, and section rules above.
+
+Every candidate must pass codec pack/unpack validation and render exactly as
+its span in the normalized text. These context-free candidates remain
+available under every
+exchange profile. The GUI captures Unknown, Field Day, or RTTY Roundup from
+the existing special operating activity when a message is submitted. No
+activity means Unknown; the native macro default of SERIAL does not apply to
+automatic text recognition. Field Day adds no candidates because CLASS_SECTION
+is already self-identifying.
+
+RTTY Roundup additionally considers full "599 <number>" as SERIAL and full
+"599 <location>" as STATE_PROVINCE under the existing native exchange rules.
+Location tokens must contain at least one letter. Before the shared packing
+algorithm, explicit RTTY Roundup canonicalizes decimal tokens following a
+complete "599" token to the SERIAL spelling (at least three digits). Eligible
+tokens have one to six digits and value 0-131071. Unsupported tokens keep their
+spelling and use normal fallback. Bare digits and Unknown or Field Day input
+retain their spelling after ordinary text normalization. The canonical message
+is returned to the GUI for display and logging. A canonical result exceeding
+80 characters is rejected rather than truncated.
+
+The exact-render requirement applies to this profile-normalized text, and no
+bare number is inferred as SERIAL. CQ_ZONE, ITU_ZONE,
+AGE, POWER, CHECK, FIRST_LICENSE_YEAR, other specific location kinds,
+ZONE_LOC3, and EXCH_NUM_TIME are not inferred from ordinary text. The profile
+is per-message encoder context, not a new configuration or wire field.
+
+A dynamic program over source-character offsets selects a minimum-frame
+sequence of candidates and TEXT5. An interior TEXT5 atom consumes exactly five
+characters; only the final TEXT5 atom may be padded. A structured candidate
+consumes its rendering plus one source space when another token follows,
+matching the receiver's implicit separator. Equal-cost choices prefer a
+structured atom, then the longest consumed span, then ascending atom
+kind/subtype/role. Thus equally compact SERIAL and STATE_PROVINCE candidates
+win over their generic equivalents under RTTY Roundup. This minimizes frames
+under the recognition policy, not
+under hypothetical knowledge of the contest exchange's meaning.
+
+For example, "CQ K1ABC CQ", "599 123", "599 MA", "599 FN42", and "1D EMA"
+each use one frame. Under Unknown or Field Day, "599 001" and "599 05" need
+two frames because their leading zeros cannot be preserved with GENERIC_NUMERIC.
+Under RTTY Roundup, "599 001" uses one SERIAL frame and "K1ABC 599 001" uses
+two frames. Under RTTY Roundup, "599 05" becomes "599 005" and "599 0123"
+becomes "599 123", each using one SERIAL frame. Under Unknown or Field Day
+they retain their spelling and use two frames. "599 BRUCE" also needs two:
+STRUCT30 has no generic five-character exchange atom.
+
+sjtty defaults to Unknown. The optional leading argument
+--exchange-profile=unknown|field-day|rtty-roundup applies to both its
+one-message packing and eight-argument waveform invocations. An invalid
+profile value is an error.
+
+The eight shipped JTTY function-key templates are a separate NativeMacro
+contract. Current templates and control phrases match after case folding and
+whitespace normalization, before placeholder expansion. Superseded templates
+use the exact-compatibility rule below.
+
+--------------------------------------------------------------------------------
+Key Template Native atoms
+--------------------------------------------------------------------------------
+F1 CQ %M CQ CQ(my_call)
+F2 %H %E CALL(his_call), configured full exchange
+F3 %H TU CQ %M CQ CALL_TU(his_call), CQ(my_call)
+F4 %M CALL(my_call)
+F5 %H CALL(his_call)
+F6 TU NOW %Q %E TU_NOW_CALL(queue_call), configured full exchange
+F7 %H AGN? CALL_AGN(his_call)
+F8 %E configured full exchange
+--------------------------------------------------------------------------------
+
+%E is the configured profile exchange. The default profile accepts a decimal
+serial. FIELD_DAY accepts exactly "<count><class> <section>" and encodes
+CLASS_SECTION. RTTY accepts either a decimal SERIAL or a canonical two- or
+three-character STATE_PROVINCE token. %G accepts one valid GRID4 and is
+field-only; the exact template "599 %G" selects a full-role GRID4. These are
+semantic placeholders, not text substitution followed by source inference.
+
+The exact former defaults "%H 599 %N", "TU NOW %Q 599 %N", and "599 %N"
+remain recognized during migration and are replaced by their %E forms when
+still unchanged in saved settings. Edited variants are not migrated or matched
+as native templates. An unrecognized customized template uses automatic text
+packing after normal placeholder expansion. A recognized native template
+whose required runtime call, exchange, or grid is invalid is rejected; it
+never changes meaning by falling back to literal transmission.
+
+Practical transmit subset
+
+The wire codec defines and validates every atom in this document. The current
+WSJT-X macro and tagged-N1MM compilers intentionally generate a smaller
+operator-facing subset: the six Call8 actions, SERIAL, RTTY STATE_PROVINCE,
+CLASS_SECTION, GRID4, and registered CONTROL phrases. The automatic text packer
+also generates GENERIC_NUMERIC and GENERIC_QTH. Other number and location kinds,
+ZONE_LOC3, and EXCH_NUM_TIME have canonical receive rendering and remain
+available to explicit native codec callers, but are not inferred from ordinary
+text or exposed as general-purpose transmit macros in this version.
+
+Tagged N1MM TXTEXT
+
+N1MM can opt into the practical native subset by placing this marker at the
+start of the transmitted text, after the normal {TX} command:
+
+ [[JTTY:<ACTION>]]<payload>
+
+N1MM expands {MYCALL}, ! or {CALL}, and {EXCH}; WSJT-X then parses the expanded
+payload under the selected action and active profile. The tag must begin at the
+first non-space character; tag and action matching is case-insensitive. The
+marker is transport metadata and is not transmitted. Assigned actions are:
+
+--------------------------------------------------------------------------------
+Action Expanded payload Native meaning
+--------------------------------------------------------------------------------
+CQ <mycall> CQ(mycall)
+CALL_EXCH <hiscall> <exchange> CALL(hiscall), full exchange
+CALL_TU_CQ <hiscall> <mycall> CALL_TU(hiscall), CQ(mycall)
+MYCALL <mycall> CALL(mycall)
+HISCALL <hiscall> CALL(hiscall)
+TU_NOW_EXCH <hiscall> <exchange> TU_NOW_CALL(hiscall), exchange
+CALL_MY <hiscall> <mycall> CALL(hiscall), CALL(mycall)
+CALL_TU_MY <hiscall> <mycall> CALL_TU(hiscall), CALL(mycall)
+EXCH <exchange> configured full exchange
+GRID <grid4> field-only GRID4
+CONTROL <registered phrase> CONTROL(phrase)
+--------------------------------------------------------------------------------
+
+The exchange payload follows the same default, FIELD_DAY, and RTTY profile
+rules as %E, except that tagged values are already expanded: RTTY "DX" is a
+two-letter location, and the local-configuration "DX" and "#" serial sentinels
+do not apply. It contains the exchange value only: the action supplies CQ, TU,
+TU NOW, and canonical full-exchange report text where applicable. GRID requires
+a valid four-character Maidenhead locator. CONTROL requires one exact
+registered phrase from the CONTROL table above. An untagged N1MM message uses
+the literal source interface with automatic packing described above.
+A tag-shaped substring later in a message has no
+special meaning. An unknown or malformed leading JTTY tag, an unsupported
+action, invalid payload, or profile mismatch is rejected rather than put on
+the air as literal bracket text.
+
+Representative 34-bit vectors
+
+Binary strings below contain bits 1-34 exactly. Hex values interpret the same
+34 bits as an unsigned integer and pad to nine hex digits. Both serial rows
+encode the same atom and demonstrate the EOM difference; changing any final
+atom to non-final clears the final binary bit and subtracts one from its hex
+value.
+
+--------------------------------------------------------------------------------
+Meaning Bits 1-34 Hex
+--------------------------------------------------------------------------------
+CQ K1ABC CQ 0000100110111101111000110101000001 0x026F78D41
+EXCH_NUM full SERIAL 123, more 1000000000000001111011000000001000 0x20007B008
+EXCH_NUM full SERIAL 123, EOM 1000000000000001111011000000001001 0x20007B009
+EXCH_LOC full STATE CA 1000000000000110111010000000011001 0x2001BA019
+ZONE_LOC3 05 NWT 0000001011011110010000110100101001 0x00B790D29
+CLASS_SECTION 1D EMA 0010000010110001011000000000101001 0x082C58029
+EXCH_NUM_TIME full 156 1749 1000000100111001000010110100111001 0x204E42D39
+CONTROL AGN? 0000000000000000000000000001001001 0x000000049
+GRID4 field-only FN42 0001001010000110011000000001001001 0x04A198049
+TEXT5 HELLO 0100010011100101010101010110001101 0x11395558D
+--------------------------------------------------------------------------------
+
+Compatibility
+
+This version deliberately replaces the earlier i2=2 encoding, which meant the
+literal prefix "599 " followed by five six-bit characters. There is no version
+discriminator: an old receiver will render new STRUCT30 payload bits as
+arbitrary text following "599 ", while some old i2=2 frames happen to satisfy
+the new STRUCT30 structural rules and will be accepted with a different
+meaning by a new receiver. JTTY is unreleased, so this incompatibility is
+intentional and no legacy decoder mode is retained. Automatic text packing
+uses only the current grammar; unrecognized "599 ..." text remains available
+through TEXT5.
diff --git a/lib/jtty/jtty_spec.f90 b/lib/jtty/jtty_spec.f90
new file mode 100644
index 00000000..27101200
--- /dev/null
+++ b/lib/jtty/jtty_spec.f90
@@ -0,0 +1,40 @@
+subroutine jtty_spec(iwave,iz)
+
+ parameter (NFFT=262144,NH=NFFT/2)
+ integer*2 iwave(iz)
+ real*4 x(NFFT)
+ real*4 s(0:NH)
+ complex c(0:NH)
+ equivalence (x,c)
+
+ x(1:iz)=iwave
+ x(iz+1:)=0.
+ call four2a(c,NFFT,1,-1,0)
+
+ do i=0,NH
+ c(i)=c(i)/NFFT
+ s(i)=real(c(i))**2 + aimag(c(i))**2
+ enddo
+ do i=1,200
+ call smo121(s,NH+1)
+ enddo
+ smax=maxval(s)
+ s=s/(4.0*smax)
+ tpmax=sum(s)
+
+ df=12000.0/NFFT
+ f1=0.
+ f2=0.
+ tp=0.
+ do i=0,NH
+ if(f1.eq.0.0 .and. db(s(i)).gt.-60.0) f1=i*df
+ if(i*df.gt.1500.0 .and. db(s(i)).gt.-60.0) f2=i*df
+ tp=tp+s(i)
+ write(70,3070) i*df,db(s(i)),100.0*tp/tpmax,s(i)
+3070 format(3f12.3,e12.3)
+ enddo
+ write(*,1000) f1,f2,f2-f1
+1000 format(3f10.1)
+
+ return
+end subroutine jtty_spec
diff --git a/lib/jtty/jtty_tbcc_code_profile.f90 b/lib/jtty/jtty_tbcc_code_profile.f90
new file mode 100644
index 00000000..9037d790
--- /dev/null
+++ b/lib/jtty/jtty_tbcc_code_profile.f90
@@ -0,0 +1,106 @@
+module jtty_tbcc_code_profiles
+ use, intrinsic :: iso_fortran_env, only: int32
+ implicit none
+ private
+
+ integer(int32), parameter, public :: JTTY_TBCC_PAYLOAD_BITS = 34_int32
+ integer(int32), parameter, public :: JTTY_TBCC_OUTER_CHECK_BITS = 12_int32
+ integer(int32), parameter, public :: JTTY_TBCC_INFORMATION_BITS = &
+ JTTY_TBCC_PAYLOAD_BITS + JTTY_TBCC_OUTER_CHECK_BITS
+
+ ! A circular rate-1/2 trellis with memory nu has 2**nu states and a
+ ! constraint-length register of nu+1 bits.
+ type, public :: jtty_tbcc_code_profile
+ integer(int32) :: profile_id = 0_int32
+ integer(int32) :: memory_nu = 0_int32
+ integer(int32) :: constraint_length = 0_int32
+ integer(int32) :: state_count = 0_int32
+ integer(int32) :: state_mask = 0_int32
+ integer(int32) :: register_mask = 0_int32
+ ! Generator masks use integer bit patterns; octal notation is the
+ ! conventional spelling for convolutional codes such as 1167/1545.
+ integer(int32) :: generator_0 = 0_int32
+ integer(int32) :: generator_1 = 0_int32
+ ! The leading term of the outer polynomial is implicit; these masks describe
+ ! the stored feedback coefficients and remainder register.
+ integer(int32) :: outer_polynomial = 0_int32
+ integer(int32) :: outer_top_bit_mask = 0_int32
+ integer(int32) :: outer_register_mask = 0_int32
+ integer(int32) :: payload_bits = 0_int32
+ integer(int32) :: outer_check_bits = 0_int32
+ integer(int32) :: information_bits = 0_int32
+ end type jtty_tbcc_code_profile
+
+ type(jtty_tbcc_code_profile), parameter, public :: &
+ JTTY_TBCC_PROFILE_1167_1545_80F = jtty_tbcc_code_profile( &
+ profile_id=1_int32, memory_nu=9_int32, constraint_length=10_int32, &
+ state_count=512_int32, state_mask=int(z'1FF', int32), &
+ register_mask=int(z'3FF', int32), &
+ generator_0=int(o'1167', int32), generator_1=int(o'1545', int32), &
+ outer_polynomial=int(z'80F', int32), &
+ outer_top_bit_mask=int(z'800', int32), &
+ outer_register_mask=int(z'FFF', int32), &
+ payload_bits=JTTY_TBCC_PAYLOAD_BITS, &
+ outer_check_bits=JTTY_TBCC_OUTER_CHECK_BITS, &
+ information_bits=JTTY_TBCC_INFORMATION_BITS)
+
+ public :: jtty_tbcc_code_profile_is_valid
+ public :: jtty_tbcc_code_profile_is_supported
+
+contains
+
+ pure logical function jtty_tbcc_code_profile_is_valid(profile) result(valid)
+ type(jtty_tbcc_code_profile), intent(in) :: profile
+ integer(int32) :: expected_state_count, expected_register_mask
+
+ valid = .false.
+ if (profile%memory_nu < 1_int32 .or. profile%memory_nu > 20_int32) return
+ if (profile%constraint_length /= profile%memory_nu + 1_int32) return
+ expected_state_count = shiftl(1_int32, profile%memory_nu)
+ expected_register_mask = shiftl(1_int32, profile%constraint_length) - 1_int32
+ if (profile%state_count /= expected_state_count) return
+ if (profile%state_mask /= expected_state_count - 1_int32) return
+ if (profile%register_mask /= expected_register_mask) return
+ if (profile%generator_0 <= 0_int32 .or. &
+ iand(profile%generator_0, not(profile%register_mask)) /= 0_int32) return
+ if (profile%generator_1 <= 0_int32 .or. &
+ iand(profile%generator_1, not(profile%register_mask)) /= 0_int32) return
+ if (profile%payload_bits /= JTTY_TBCC_PAYLOAD_BITS) return
+ if (profile%outer_check_bits /= JTTY_TBCC_OUTER_CHECK_BITS) return
+ if (profile%information_bits /= profile%payload_bits + profile%outer_check_bits) return
+ if (profile%outer_top_bit_mask /= &
+ shiftl(1_int32, profile%outer_check_bits - 1_int32)) return
+ if (profile%outer_register_mask /= &
+ shiftl(1_int32, profile%outer_check_bits) - 1_int32) return
+ if (profile%outer_polynomial <= 0_int32 .or. &
+ iand(profile%outer_polynomial, not(profile%outer_register_mask)) /= 0_int32) return
+ valid = .true.
+ end function jtty_tbcc_code_profile_is_valid
+
+ pure logical function jtty_tbcc_code_profile_is_supported(profile) result(supported)
+ type(jtty_tbcc_code_profile), intent(in) :: profile
+
+ supported = jtty_tbcc_code_profile_is_valid(profile) .and. &
+ jtty_tbcc_code_profiles_equal(profile, JTTY_TBCC_PROFILE_1167_1545_80F)
+ end function jtty_tbcc_code_profile_is_supported
+
+ pure logical function jtty_tbcc_code_profiles_equal(left, right) result(equal)
+ type(jtty_tbcc_code_profile), intent(in) :: left, right
+
+ equal = left%profile_id == right%profile_id .and. &
+ left%memory_nu == right%memory_nu .and. &
+ left%constraint_length == right%constraint_length .and. &
+ left%state_count == right%state_count .and. &
+ left%state_mask == right%state_mask .and. &
+ left%register_mask == right%register_mask .and. &
+ left%generator_0 == right%generator_0 .and. &
+ left%generator_1 == right%generator_1 .and. &
+ left%outer_polynomial == right%outer_polynomial .and. &
+ left%outer_top_bit_mask == right%outer_top_bit_mask .and. &
+ left%outer_register_mask == right%outer_register_mask .and. &
+ left%payload_bits == right%payload_bits .and. &
+ left%outer_check_bits == right%outer_check_bits .and. &
+ left%information_bits == right%information_bits
+ end function jtty_tbcc_code_profiles_equal
+
+end module jtty_tbcc_code_profiles
diff --git a/lib/jtty/jtty_tbcc_decoder.f90 b/lib/jtty/jtty_tbcc_decoder.f90
new file mode 100644
index 00000000..c010331d
--- /dev/null
+++ b/lib/jtty/jtty_tbcc_decoder.f90
@@ -0,0 +1,151 @@
+module jtty_tbcc_decoder
+ use, intrinsic :: iso_fortran_env, only: int32, int64, real32, real64
+ use jtty_tbcc_code_profiles, only: JTTY_TBCC_PROFILE_1167_1545_80F
+ use jtty_tbcc_list_decoder, only: jtty_tbcc_decoder_plan, &
+ jtty_tbcc_decoder_workspace, jtty_tbcc_init_decoder_plan, &
+ jtty_tbcc_init_decoder_workspace, jtty_tbcc_list_wava_optimized, &
+ JTTY_TBCC_INFORMATION_BITS, JTTY_TBCC_MAX_HYPOTHESES
+ use tbcc, only: PAYLOAD_BITS
+ implicit none
+ private
+
+ integer(int32), parameter :: COHERENT_LENGTHS(3) = [1_int32, 2_int32, 4_int32]
+ integer(int32), parameter :: CIRCULAR_PASSES = 2_int32
+
+ type, public :: jtty_tbcc_decode_result
+ integer(int32) :: accepted_hypothesis_rank = 0_int32
+ integer(int32) :: exported_candidate_count = 0_int32
+ integer(int32) :: circular_candidate_count = 0_int32
+ integer(int32) :: coherent_block_length = 0_int32
+ integer(int32) :: evaluated_rung_count = 0_int32
+ integer(int64) :: accepted_identity = 0_int64
+ real(real64) :: accepted_metric = -huge(0.0_real64)
+ logical :: used_half_symbol_observation = .false.
+ end type jtty_tbcc_decode_result
+
+ type :: jtty_tbcc_rung_result
+ integer(int32) :: candidates(JTTY_TBCC_INFORMATION_BITS, &
+ JTTY_TBCC_MAX_HYPOTHESES) = 0_int32
+ integer(int64) :: identities(JTTY_TBCC_MAX_HYPOTHESES) = 0_int64
+ real(real64) :: clean_metrics(JTTY_TBCC_MAX_HYPOTHESES) = &
+ -huge(0.0_real64)
+ logical :: crc_valid(JTTY_TBCC_MAX_HYPOTHESES) = .false.
+ type(jtty_tbcc_decode_result) :: result
+ logical :: accepted = .false.
+ end type jtty_tbcc_rung_result
+
+ logical, save :: decoders_initialized = .false.
+ type(jtty_tbcc_decoder_plan), save :: plans(3)
+ type(jtty_tbcc_decoder_workspace), save :: workspaces(3)
+
+ public :: jtty_tbcc_decode
+
+contains
+
+ subroutine jtty_tbcc_decode(correlations, half_correlations, payload, success, result)
+ complex(real32), intent(in) :: correlations(0:3, JTTY_TBCC_INFORMATION_BITS)
+ complex(real32), intent(in) :: half_correlations(0:3, JTTY_TBCC_INFORMATION_BITS)
+ integer(int32), intent(out) :: payload(PAYLOAD_BITS)
+ logical, intent(out) :: success
+ type(jtty_tbcc_decode_result), intent(out), optional :: result
+ type(jtty_tbcc_decode_result) :: local_result
+
+ !$omp critical(jtty_tbcc_decoder)
+ call initialize_decoders()
+ call decode_ladder(correlations, half_correlations, payload, success, local_result)
+ !$omp end critical(jtty_tbcc_decoder)
+ if (present(result)) result = local_result
+ end subroutine jtty_tbcc_decode
+
+ subroutine initialize_decoders()
+ integer :: coherent_index
+
+ if (decoders_initialized) return
+
+ do coherent_index = 1, size(COHERENT_LENGTHS)
+ call jtty_tbcc_init_decoder_plan(plans(coherent_index), &
+ JTTY_TBCC_PROFILE_1167_1545_80F, &
+ COHERENT_LENGTHS(coherent_index), 4_int32, CIRCULAR_PASSES, &
+ JTTY_TBCC_MAX_HYPOTHESES)
+ call jtty_tbcc_init_decoder_workspace(workspaces(coherent_index), &
+ plans(coherent_index))
+ end do
+ decoders_initialized = .true.
+ end subroutine initialize_decoders
+
+ subroutine decode_ladder(correlations, half_correlations, payload, success, result)
+ complex(real32), intent(in) :: correlations(0:3, JTTY_TBCC_INFORMATION_BITS)
+ complex(real32), intent(in) :: half_correlations(0:3, JTTY_TBCC_INFORMATION_BITS)
+ integer(int32), intent(out) :: payload(PAYLOAD_BITS)
+ logical, intent(out) :: success
+ type(jtty_tbcc_decode_result), intent(out) :: result
+ type(jtty_tbcc_rung_result) :: decoded_rung
+ integer :: rung
+
+ payload = 0_int32
+ success = .false.
+ result = jtty_tbcc_decode_result()
+ do rung = 1, size(COHERENT_LENGTHS)
+ call decode_rung(correlations, rung, decoded_rung)
+ if (.not.decoded_rung%accepted) cycle
+ call accept_rung(decoded_rung, rung, .false., payload, success, result)
+ return
+ end do
+
+ ! Half-symbol energies discard phase, so only L1 is meaningful here.
+ call decode_rung(half_correlations, 1, decoded_rung)
+ if (decoded_rung%accepted) then
+ call accept_rung(decoded_rung, 4, .true., payload, success, result)
+ else
+ result%evaluated_rung_count = 4_int32
+ end if
+ end subroutine decode_ladder
+
+ subroutine decode_rung(correlations, coherent_index, rung)
+ complex(real32), intent(in) :: correlations(0:3, JTTY_TBCC_INFORMATION_BITS)
+ integer, intent(in) :: coherent_index
+ type(jtty_tbcc_rung_result), intent(out) :: rung
+ integer(int32) :: start_states(JTTY_TBCC_MAX_HYPOTHESES)
+ real(real64) :: path_metrics(JTTY_TBCC_MAX_HYPOTHESES)
+ integer(int32) :: candidate_count, pool_count, rank
+
+ rung = jtty_tbcc_rung_result()
+ call jtty_tbcc_list_wava_optimized(plans(coherent_index), &
+ workspaces(coherent_index), correlations, rung%candidates, rung%identities, &
+ rung%clean_metrics, path_metrics, start_states, rung%crc_valid, &
+ candidate_count, pool_count, prune_reserved_zero=.true.)
+
+ rung%result = jtty_tbcc_decode_result( &
+ exported_candidate_count=candidate_count, &
+ circular_candidate_count=pool_count, &
+ coherent_block_length=COHERENT_LENGTHS(coherent_index))
+ do rank = 1, candidate_count
+ if (.not.rung%crc_valid(rank)) cycle
+ ! Do not expand the fixed false-accept budget past the all-zero sentinel.
+ if (all(rung%candidates(1:PAYLOAD_BITS, rank) == 0_int32)) exit
+ rung%accepted = .true.
+ rung%result%accepted_hypothesis_rank = rank
+ rung%result%accepted_identity = rung%identities(rank)
+ rung%result%accepted_metric = rung%clean_metrics(rank)
+ exit
+ end do
+ end subroutine decode_rung
+
+ subroutine accept_rung(rung, evaluated_rung_count, half_symbol, payload, success, result)
+ type(jtty_tbcc_rung_result), intent(in) :: rung
+ integer, intent(in) :: evaluated_rung_count
+ logical, intent(in) :: half_symbol
+ integer(int32), intent(out) :: payload(PAYLOAD_BITS)
+ logical, intent(out) :: success
+ type(jtty_tbcc_decode_result), intent(out) :: result
+ integer :: rank
+
+ rank = rung%result%accepted_hypothesis_rank
+ payload = rung%candidates(1:PAYLOAD_BITS, rank)
+ success = .true.
+ result = rung%result
+ result%evaluated_rung_count = evaluated_rung_count
+ result%used_half_symbol_observation = half_symbol
+ end subroutine accept_rung
+
+end module jtty_tbcc_decoder
diff --git a/lib/jtty/jtty_tbcc_list_decoder.f90 b/lib/jtty/jtty_tbcc_list_decoder.f90
new file mode 100644
index 00000000..ca4a4bd1
--- /dev/null
+++ b/lib/jtty/jtty_tbcc_list_decoder.f90
@@ -0,0 +1,1168 @@
+module jtty_tbcc_list_decoder
+ use, intrinsic :: iso_fortran_env, only: int32, int64, real32, real64
+ use, intrinsic :: ieee_arithmetic, only: ieee_is_finite
+ use jtty_tbcc_code_profiles, only: jtty_tbcc_code_profile, &
+ jtty_tbcc_code_profile_is_supported, JTTY_TBCC_INFORMATION_BITS
+ implicit none
+ private
+
+ ! This module keeps decoder breadth and admission breadth separate. The
+ ! shorthand P1/P4 means retaining one/four distinct paths at every trellis
+ ! merge. H1/H4 means returning at most one/four unique, closed codewords to
+ ! the CRC admission layer. A wider path search therefore does not silently
+ ! increase the number of CRC hypotheses tested.
+
+ public :: JTTY_TBCC_INFORMATION_BITS
+ integer(int32), parameter, public :: JTTY_TBCC_RESERVED_BIT = 33_int32
+ integer(int32), parameter, public :: JTTY_TBCC_MAX_HYPOTHESES = 4_int32
+ real(real64), parameter :: NEGATIVE_METRIC = -huge(0.0_real64)
+
+ type :: survivor_t
+ logical :: valid = .false.
+ real(real64) :: metric = NEGATIVE_METRIC
+ integer(int32) :: origin_state = -1_int32
+ integer(int32) :: bits(JTTY_TBCC_INFORMATION_BITS) = 0_int32
+ end type survivor_t
+
+ type :: pool_candidate_t
+ integer(int32) :: bits(JTTY_TBCC_INFORMATION_BITS) = 0_int32
+ integer(int32) :: start_state = -1_int32
+ integer(int64) :: identity = 0_int64
+ real(real64) :: clean_metric = NEGATIVE_METRIC
+ real(real64) :: wava_metric = NEGATIVE_METRIC
+ logical :: crc_valid = .false.
+ end type pool_candidate_t
+
+ integer(int32), parameter :: PACKED_ORIGIN_BITS = 11_int32
+ integer(int32), parameter :: PACKED_VALID_BIT = JTTY_TBCC_INFORMATION_BITS + PACKED_ORIGIN_BITS
+
+ type :: packed_survivor_t
+ real(real64) :: metric = NEGATIVE_METRIC
+ ! Low bits hold the input word in lexical order, then origin and validity.
+ ! Unwritten input bits stay zero, so integer order also orders every prefix.
+ integer(int64) :: key = 0_int64
+ end type packed_survivor_t
+
+ type, public :: jtty_tbcc_decoder_plan
+ private
+ ! Immutable trellis geometry and coherent branch tables shared by decodes.
+ logical :: initialized = .false.
+ type(jtty_tbcc_code_profile) :: code
+ integer(int32) :: coherent_length = 0_int32
+ integer(int32) :: per_state_width = 0_int32
+ integer(int32) :: wraps = 0_int32
+ integer(int32) :: hypothesis_count = 0_int32
+ integer(int32) :: state_count = 0_int32
+ integer(int32) :: block_count = 0_int32
+ integer(int32) :: max_branch_count = 0_int32
+ integer(int32) :: pool_capacity = 0_int32
+ integer(int32) :: hash_capacity = 0_int32
+ integer(int32) :: energy_count = 0_int32
+ integer(int32), allocatable :: next_state(:,:), tone(:,:)
+ integer(int32), allocatable :: block_starts(:), block_lengths(:)
+ integer(int32), allocatable :: branch_counts(:), energy_offsets(:)
+ integer(int32), allocatable :: branch_end_states(:,:,:)
+ integer(int32), allocatable :: branch_sequence_indices(:,:,:)
+ integer(int64), allocatable :: branch_identities(:,:)
+ end type jtty_tbcc_decoder_plan
+
+ type, public :: jtty_tbcc_decoder_workspace
+ private
+ ! Reusable scratch storage keeps allocation outside the receiver hot path.
+ logical :: initialized = .false.
+ type(packed_survivor_t), allocatable :: previous(:,:), current(:,:)
+ type(pool_candidate_t), allocatable :: pool(:)
+ integer(int32), allocatable :: order(:), sort_scratch(:), hash_indices(:)
+ integer(int64), allocatable :: hash_keys(:)
+ real(real64), allocatable :: sequence_energies(:)
+ logical, allocatable :: hash_used(:)
+ end type jtty_tbcc_decoder_workspace
+
+ public :: jtty_tbcc_transition
+ public :: jtty_tbcc_supertransition
+ public :: jtty_tbcc_coherent_metric
+ public :: jtty_tbcc_score_candidate
+ public :: jtty_tbcc_tailbiting_state
+ public :: jtty_tbcc_candidate_identity
+ public :: jtty_tbcc_crc_valid
+ public :: jtty_tbcc_list_wava
+ public :: jtty_tbcc_list_wava_reference
+ public :: jtty_tbcc_init_decoder_plan
+ public :: jtty_tbcc_init_decoder_workspace
+ public :: jtty_tbcc_list_wava_optimized
+
+contains
+
+ pure subroutine jtty_tbcc_transition(code, state, input_bit, next_state, tone)
+ type(jtty_tbcc_code_profile), intent(in) :: code
+ integer(int32), intent(in) :: state, input_bit
+ integer(int32), intent(out) :: next_state, tone
+ integer(int32) :: output_register, out_b0, out_b1, state_mask
+
+ state_mask = code%state_mask
+ output_register = iand(ior(shiftl(state, 1), input_bit), &
+ code%register_mask)
+ out_b0 = modulo(popcnt(iand(output_register, code%generator_0)), 2)
+ out_b1 = modulo(popcnt(iand(output_register, code%generator_1)), 2)
+ tone = 2_int32*out_b0 + ieor(out_b0, out_b1)
+ next_state = iand(output_register, state_mask)
+ end subroutine jtty_tbcc_transition
+
+ pure subroutine jtty_tbcc_supertransition(code, start_state, input_bits, &
+ end_state, tones)
+ type(jtty_tbcc_code_profile), intent(in) :: code
+ integer(int32), intent(in) :: start_state
+ integer(int32), intent(in) :: input_bits(:)
+ integer(int32), intent(out) :: end_state
+ integer(int32), intent(out) :: tones(size(input_bits))
+ integer(int32) :: offset, state
+
+ state = start_state
+ do offset = 1, size(input_bits)
+ call jtty_tbcc_transition(code, state, input_bits(offset), &
+ end_state, tones(offset))
+ state = end_state
+ end do
+ end_state = state
+ end subroutine jtty_tbcc_supertransition
+
+ pure real(real64) function jtty_tbcc_coherent_metric(correlations, &
+ first_symbol, tones) result(metric)
+ complex(real32), intent(in) :: correlations(0:3, JTTY_TBCC_INFORMATION_BITS)
+ integer(int32), intent(in) :: first_symbol
+ integer(int32), intent(in) :: tones(:)
+ complex(real32) :: coherent_sum
+ integer(int32) :: offset
+
+ coherent_sum = cmplx(0.0_real32, 0.0_real32, real32)
+ do offset = 1, size(tones)
+ coherent_sum = coherent_sum + &
+ correlations(tones(offset), first_symbol + offset - 1)
+ end do
+ metric = real(coherent_sum*conjg(coherent_sum), real64) / &
+ real(size(tones), real64)
+ end function jtty_tbcc_coherent_metric
+
+ pure integer(int32) function jtty_tbcc_tailbiting_state(code, bits) &
+ result(state)
+ type(jtty_tbcc_code_profile), intent(in) :: code
+ integer(int32), intent(in) :: bits(JTTY_TBCC_INFORMATION_BITS)
+ integer(int32) :: bit_index, state_mask
+
+ state = 0_int32
+ state_mask = code%state_mask
+ do bit_index = JTTY_TBCC_INFORMATION_BITS - code%memory_nu + 1, &
+ JTTY_TBCC_INFORMATION_BITS
+ state = iand(ior(shiftl(state, 1), bits(bit_index)), state_mask)
+ end do
+ end function jtty_tbcc_tailbiting_state
+
+ pure subroutine jtty_tbcc_score_candidate(code, correlations, &
+ coherent_length, bits, metric, closed)
+ type(jtty_tbcc_code_profile), intent(in) :: code
+ complex(real32), intent(in) :: correlations(0:3, JTTY_TBCC_INFORMATION_BITS)
+ integer(int32), intent(in) :: coherent_length
+ integer(int32), intent(in) :: bits(JTTY_TBCC_INFORMATION_BITS)
+ real(real64), intent(out) :: metric
+ logical, intent(out) :: closed
+ integer(int32) :: block_length, block_start, end_state, next_state, start_state
+ integer(int32) :: tones(4)
+
+ start_state = jtty_tbcc_tailbiting_state(code, bits)
+ end_state = start_state
+ metric = 0.0_real64
+ do block_start = 1, JTTY_TBCC_INFORMATION_BITS, coherent_length
+ block_length = min(coherent_length, &
+ JTTY_TBCC_INFORMATION_BITS - block_start + 1_int32)
+ call jtty_tbcc_supertransition(code, end_state, &
+ bits(block_start:block_start + block_length - 1), next_state, &
+ tones(1:block_length))
+ metric = metric + jtty_tbcc_coherent_metric(correlations, &
+ block_start, tones(1:block_length))
+ end_state = next_state
+ end do
+ closed = end_state == start_state
+ end subroutine jtty_tbcc_score_candidate
+
+ pure integer(int64) function jtty_tbcc_candidate_identity(bits) &
+ result(identity)
+ integer(int32), intent(in) :: bits(JTTY_TBCC_INFORMATION_BITS)
+ integer(int32) :: bit_index
+
+ identity = 0_int64
+ do bit_index = 1, JTTY_TBCC_INFORMATION_BITS
+ if (bits(bit_index) /= 0_int32) identity = ibset(identity, bit_index - 1)
+ end do
+ end function jtty_tbcc_candidate_identity
+
+ pure logical function jtty_tbcc_crc_valid(code, bits) result(valid)
+ type(jtty_tbcc_code_profile), intent(in) :: code
+ integer(int32), intent(in) :: bits(JTTY_TBCC_INFORMATION_BITS)
+ integer(int32) :: bit_index, crc_register
+
+ crc_register = 0_int32
+ do bit_index = 1, JTTY_TBCC_INFORMATION_BITS
+ crc_register = ieor(crc_register, &
+ shiftl(bits(bit_index), code%outer_check_bits - 1_int32))
+ if (iand(crc_register, code%outer_top_bit_mask) /= 0_int32) then
+ crc_register = ieor(shiftl(crc_register, 1), code%outer_polynomial)
+ else
+ crc_register = shiftl(crc_register, 1)
+ end if
+ crc_register = iand(crc_register, code%outer_register_mask)
+ end do
+ valid = crc_register == 0_int32
+ end function jtty_tbcc_crc_valid
+
+ subroutine jtty_tbcc_init_decoder_plan(plan, code, coherent_length, &
+ per_state_width, wraps, hypothesis_count)
+ type(jtty_tbcc_decoder_plan), intent(out) :: plan
+ type(jtty_tbcc_code_profile), intent(in) :: code
+ integer(int32), intent(in) :: coherent_length, per_state_width, wraps
+ integer(int32), intent(in) :: hypothesis_count
+ integer(int32) :: block_index, block_length, block_start, branch_word
+ integer(int32) :: end_state, input_bit, offset, state, tone_word
+ integer(int32) :: input_bits(4), tones(4)
+ integer(int64) :: branch_identity
+
+ call validate_decoder_arguments(code, coherent_length, per_state_width, &
+ wraps, hypothesis_count)
+ if (code%memory_nu > PACKED_ORIGIN_BITS) error stop 'TBCC state does not fit packed survivor'
+ plan%code = code
+ plan%coherent_length = coherent_length
+ plan%per_state_width = per_state_width
+ plan%wraps = wraps
+ plan%hypothesis_count = hypothesis_count
+ plan%state_count = code%state_count
+ plan%block_count = (JTTY_TBCC_INFORMATION_BITS + coherent_length - 1_int32) / &
+ coherent_length
+ plan%max_branch_count = shiftl(1_int32, coherent_length)
+ plan%pool_capacity = plan%state_count*per_state_width
+ plan%hash_capacity = 1_int32
+ do while (plan%hash_capacity < 2_int32*plan%pool_capacity)
+ plan%hash_capacity = 2_int32*plan%hash_capacity
+ end do
+
+ allocate(plan%next_state(0:plan%state_count - 1, 0:1))
+ allocate(plan%tone(0:plan%state_count - 1, 0:1))
+ do input_bit = 0, 1
+ do state = 0, plan%state_count - 1
+ call jtty_tbcc_transition(code, state, input_bit, &
+ plan%next_state(state, input_bit), plan%tone(state, input_bit))
+ end do
+ end do
+
+ allocate(plan%block_starts(plan%block_count), plan%block_lengths(plan%block_count))
+ allocate(plan%branch_counts(plan%block_count), plan%energy_offsets(plan%block_count))
+ allocate(plan%branch_identities(0:plan%max_branch_count - 1, plan%block_count))
+ allocate(plan%branch_end_states(0:plan%state_count - 1, &
+ 0:plan%max_branch_count - 1, plan%block_count))
+ allocate(plan%branch_sequence_indices(0:plan%state_count - 1, &
+ 0:plan%max_branch_count - 1, plan%block_count))
+ plan%branch_identities = 0_int64
+ plan%branch_end_states = 0_int32
+ plan%branch_sequence_indices = 0_int32
+ plan%energy_count = 0_int32
+ do block_index = 1, plan%block_count
+ block_start = 1_int32 + (block_index - 1_int32)*coherent_length
+ block_length = min(coherent_length, &
+ JTTY_TBCC_INFORMATION_BITS - block_start + 1_int32)
+ plan%block_starts(block_index) = block_start
+ plan%block_lengths(block_index) = block_length
+ plan%branch_counts(block_index) = shiftl(1_int32, block_length)
+ plan%energy_offsets(block_index) = plan%energy_count + 1_int32
+ plan%energy_count = plan%energy_count + shiftl(1_int32, 2_int32*block_length)
+ do branch_word = 0, plan%branch_counts(block_index) - 1
+ call unpack_branch_word(branch_word, block_length, input_bits)
+ branch_identity = 0_int64
+ do offset = 1, block_length
+ if (input_bits(offset) /= 0_int32) &
+ branch_identity = ibset(branch_identity, JTTY_TBCC_INFORMATION_BITS - block_start - offset + 1_int32)
+ end do
+ plan%branch_identities(branch_word, block_index) = branch_identity
+ do state = 0, plan%state_count - 1
+ call planned_supertransition(plan, state, input_bits, block_length, &
+ end_state, tones, tone_word)
+ plan%branch_end_states(state, branch_word, block_index) = end_state
+ plan%branch_sequence_indices(state, branch_word, block_index) = &
+ plan%energy_offsets(block_index) + tone_word
+ end do
+ end do
+ end do
+ plan%initialized = .true.
+ end subroutine jtty_tbcc_init_decoder_plan
+
+ subroutine jtty_tbcc_init_decoder_workspace(workspace, plan)
+ type(jtty_tbcc_decoder_workspace), intent(out) :: workspace
+ type(jtty_tbcc_decoder_plan), intent(in) :: plan
+
+ if (.not.plan%initialized) error stop 'TBCC list decoder plan is not initialized'
+ allocate(workspace%previous(0:plan%state_count - 1, plan%per_state_width))
+ allocate(workspace%current(0:plan%state_count - 1, plan%per_state_width))
+ allocate(workspace%pool(max(1_int32, plan%pool_capacity)))
+ allocate(workspace%order(max(1_int32, plan%pool_capacity)))
+ allocate(workspace%sort_scratch(max(1_int32, plan%pool_capacity)))
+ allocate(workspace%hash_keys(plan%hash_capacity))
+ allocate(workspace%hash_indices(plan%hash_capacity))
+ allocate(workspace%hash_used(plan%hash_capacity))
+ allocate(workspace%sequence_energies(plan%energy_count))
+ workspace%initialized = .true.
+ end subroutine jtty_tbcc_init_decoder_workspace
+
+ subroutine jtty_tbcc_list_wava(correlations, code, coherent_length, &
+ per_state_width, wraps, hypothesis_count, candidate_bits, &
+ candidate_identities, candidate_clean_metrics, candidate_wava_metrics, &
+ candidate_start_states, candidate_crc_valid, candidate_count, pool_count, &
+ prune_reserved_zero, reference_bits, reference_present, &
+ reference_pool_rank, reference_h_rank)
+ complex(real32), intent(in) :: correlations(0:3, JTTY_TBCC_INFORMATION_BITS)
+ type(jtty_tbcc_code_profile), intent(in) :: code
+ integer(int32), intent(in) :: coherent_length, per_state_width, wraps
+ integer(int32), intent(in) :: hypothesis_count
+ integer(int32), intent(out) :: candidate_bits(JTTY_TBCC_INFORMATION_BITS, hypothesis_count)
+ integer(int64), intent(out) :: candidate_identities(hypothesis_count)
+ real(real64), intent(out) :: candidate_clean_metrics(hypothesis_count)
+ real(real64), intent(out) :: candidate_wava_metrics(hypothesis_count)
+ integer(int32), intent(out) :: candidate_start_states(hypothesis_count)
+ logical, intent(out) :: candidate_crc_valid(hypothesis_count)
+ integer(int32), intent(out) :: candidate_count, pool_count
+ logical, intent(in), optional :: prune_reserved_zero
+ integer(int32), intent(in), optional :: reference_bits(JTTY_TBCC_INFORMATION_BITS)
+ logical, intent(out), optional :: reference_present
+ integer(int32), intent(out), optional :: reference_pool_rank, reference_h_rank
+ type(jtty_tbcc_decoder_plan) :: plan
+ type(jtty_tbcc_decoder_workspace) :: workspace
+
+ call jtty_tbcc_init_decoder_plan(plan, code, coherent_length, &
+ per_state_width, wraps, hypothesis_count)
+ call jtty_tbcc_init_decoder_workspace(workspace, plan)
+ call jtty_tbcc_list_wava_optimized(plan, workspace, correlations, &
+ candidate_bits, candidate_identities, candidate_clean_metrics, &
+ candidate_wava_metrics, candidate_start_states, candidate_crc_valid, &
+ candidate_count, pool_count, prune_reserved_zero, reference_bits, &
+ reference_present, reference_pool_rank, reference_h_rank)
+ end subroutine jtty_tbcc_list_wava
+
+ subroutine jtty_tbcc_list_wava_optimized(plan, workspace, correlations, &
+ candidate_bits, candidate_identities, candidate_clean_metrics, &
+ candidate_wava_metrics, candidate_start_states, candidate_crc_valid, &
+ candidate_count, pool_count, prune_reserved_zero, reference_bits, &
+ reference_present, reference_pool_rank, reference_h_rank)
+ type(jtty_tbcc_decoder_plan), intent(in) :: plan
+ type(jtty_tbcc_decoder_workspace), intent(inout) :: workspace
+ complex(real32), intent(in) :: correlations(0:3, JTTY_TBCC_INFORMATION_BITS)
+ integer(int32), intent(out) :: candidate_bits(:, :)
+ integer(int64), intent(out) :: candidate_identities(:)
+ real(real64), intent(out) :: candidate_clean_metrics(:), candidate_wava_metrics(:)
+ integer(int32), intent(out) :: candidate_start_states(:)
+ logical, intent(out) :: candidate_crc_valid(:)
+ integer(int32), intent(out) :: candidate_count, pool_count
+ logical, intent(in), optional :: prune_reserved_zero
+ integer(int32), intent(in), optional :: reference_bits(JTTY_TBCC_INFORMATION_BITS)
+ logical, intent(out), optional :: reference_present
+ integer(int32), intent(out), optional :: reference_pool_rank, reference_h_rank
+ type(packed_survivor_t), allocatable :: swap_survivors(:,:)
+ integer(int32) :: block_index, hash_slot
+ integer(int32) :: output_rank, pool_index, rank, state, wrap
+ integer(int64) :: identity, reference_identity
+ real(real64) :: clean_metric
+ logical :: closed, found, prune, ordered_metrics
+
+ call validate_optimized_storage(plan, workspace, candidate_bits, &
+ candidate_identities, candidate_clean_metrics, candidate_wava_metrics, &
+ candidate_start_states, candidate_crc_valid)
+ call precompute_sequence_energies(plan, correlations, workspace%sequence_energies)
+ ! Nonfinite metrics do not provide the monotone rank order needed by the cutoff.
+ ordered_metrics = all(ieee_is_finite(workspace%sequence_energies))
+ call clear_packed_survivors(workspace%previous)
+ do state = 0, plan%state_count - 1
+ workspace%previous(state, 1)%key = ibset(shiftl(int(state, int64), JTTY_TBCC_INFORMATION_BITS), PACKED_VALID_BIT)
+ workspace%previous(state, 1)%metric = 0.0_real64
+ end do
+
+ prune = .false.
+ if (present(prune_reserved_zero)) prune = prune_reserved_zero
+ do wrap = 1, plan%wraps
+ call reset_packed_frame_identity(workspace%previous)
+ do block_index = 1, plan%block_count
+ call advance_packed_survivors(plan, block_index, prune, workspace%sequence_energies, &
+ workspace%previous, workspace%current, ordered_metrics)
+ call move_alloc(workspace%previous, swap_survivors)
+ call move_alloc(workspace%current, workspace%previous)
+ call move_alloc(swap_survivors, workspace%current)
+ end do
+ end do
+
+ pool_count = 0_int32
+ workspace%hash_used = .false.
+ do state = 0, plan%state_count - 1
+ do rank = 1, plan%per_state_width
+ if (.not.btest(workspace%previous(state, rank)%key, PACKED_VALID_BIT)) cycle
+ ! Tail-biting paths are eligible only when their final and remembered
+ ! initial states agree after the last wrap.
+ if (ibits(workspace%previous(state, rank)%key, &
+ JTTY_TBCC_INFORMATION_BITS, PACKED_ORIGIN_BITS) /= state) cycle
+ identity = reverse_identity(workspace%previous(state, rank)%key)
+ ! The same complete word can close through more than one retained path;
+ ! hash by all 46 bits before applying the global hypothesis limit.
+ call locate_identity(identity, workspace%hash_keys, workspace%hash_indices, &
+ workspace%hash_used, hash_slot, pool_index, found)
+ if (found) then
+ if (workspace%previous(state, rank)%metric > &
+ workspace%pool(pool_index)%wava_metric .or. &
+ (.not.(workspace%previous(state, rank)%metric < &
+ workspace%pool(pool_index)%wava_metric) .and. &
+ state < workspace%pool(pool_index)%start_state)) then
+ workspace%pool(pool_index)%wava_metric = &
+ workspace%previous(state, rank)%metric
+ workspace%pool(pool_index)%start_state = state
+ end if
+ cycle
+ end if
+ pool_count = pool_count + 1_int32
+ pool_index = pool_count
+ workspace%hash_used(hash_slot) = .true.
+ workspace%hash_keys(hash_slot) = identity
+ workspace%hash_indices(hash_slot) = pool_index
+ workspace%pool(pool_index)%identity = identity
+ workspace%pool(pool_index)%start_state = state
+ workspace%pool(pool_index)%wava_metric = workspace%previous(state, rank)%metric
+ call unpack_identity(identity, workspace%pool(pool_index)%bits)
+ ! WAVA survivor metrics include history from earlier wraps. Admission
+ ! order is based on a clean, single-frame score of each complete word.
+ call score_planned_identity(plan, workspace%sequence_energies, identity, &
+ clean_metric, closed)
+ if (.not.closed) error stop 'closed TBCC survivor failed clean scoring closure'
+ workspace%pool(pool_index)%clean_metric = clean_metric
+ ! This flag reports the polynomial remainder only. Message admission,
+ ! including the protocol's all-zero rejection, remains with the caller.
+ workspace%pool(pool_index)%crc_valid = &
+ jtty_tbcc_crc_valid(plan%code, workspace%pool(pool_index)%bits)
+ end do
+ end do
+
+ do pool_index = 1, pool_count
+ workspace%order(pool_index) = pool_index
+ end do
+ call sort_candidate_order_with_scratch(workspace%pool, workspace%order, &
+ workspace%sort_scratch, pool_count)
+ candidate_bits = 0_int32
+ candidate_identities = 0_int64
+ candidate_clean_metrics = NEGATIVE_METRIC
+ candidate_wava_metrics = NEGATIVE_METRIC
+ candidate_start_states = -1_int32
+ candidate_crc_valid = .false.
+ candidate_count = min(plan%hypothesis_count, pool_count)
+ do output_rank = 1, candidate_count
+ pool_index = workspace%order(output_rank)
+ candidate_bits(:, output_rank) = workspace%pool(pool_index)%bits
+ candidate_identities(output_rank) = workspace%pool(pool_index)%identity
+ candidate_clean_metrics(output_rank) = workspace%pool(pool_index)%clean_metric
+ candidate_wava_metrics(output_rank) = workspace%pool(pool_index)%wava_metric
+ candidate_start_states(output_rank) = workspace%pool(pool_index)%start_state
+ candidate_crc_valid(output_rank) = workspace%pool(pool_index)%crc_valid
+ end do
+
+ if (present(reference_present)) reference_present = .false.
+ if (present(reference_pool_rank)) reference_pool_rank = 0_int32
+ if (present(reference_h_rank)) reference_h_rank = 0_int32
+ if (present(reference_bits)) then
+ reference_identity = jtty_tbcc_candidate_identity(reference_bits)
+ do output_rank = 1, pool_count
+ pool_index = workspace%order(output_rank)
+ if (workspace%pool(pool_index)%identity /= reference_identity) cycle
+ if (present(reference_present)) reference_present = .true.
+ if (present(reference_pool_rank)) reference_pool_rank = output_rank
+ if (present(reference_h_rank)) then
+ if (output_rank <= candidate_count) reference_h_rank = output_rank
+ end if
+ exit
+ end do
+ end if
+ end subroutine jtty_tbcc_list_wava_optimized
+
+ subroutine jtty_tbcc_list_wava_reference(correlations, code, coherent_length, &
+ per_state_width, wraps, hypothesis_count, candidate_bits, &
+ candidate_identities, candidate_clean_metrics, candidate_wava_metrics, &
+ candidate_start_states, candidate_crc_valid, candidate_count, pool_count, &
+ prune_reserved_zero, reference_bits, reference_present, &
+ reference_pool_rank, reference_h_rank)
+ complex(real32), intent(in) :: correlations(0:3, JTTY_TBCC_INFORMATION_BITS)
+ type(jtty_tbcc_code_profile), intent(in) :: code
+ integer(int32), intent(in) :: coherent_length, per_state_width, wraps
+ integer(int32), intent(in) :: hypothesis_count
+ integer(int32), intent(out) :: candidate_bits(JTTY_TBCC_INFORMATION_BITS, hypothesis_count)
+ integer(int64), intent(out) :: candidate_identities(hypothesis_count)
+ real(real64), intent(out) :: candidate_clean_metrics(hypothesis_count)
+ real(real64), intent(out) :: candidate_wava_metrics(hypothesis_count)
+ integer(int32), intent(out) :: candidate_start_states(hypothesis_count)
+ logical, intent(out) :: candidate_crc_valid(hypothesis_count)
+ integer(int32), intent(out) :: candidate_count, pool_count
+ logical, intent(in), optional :: prune_reserved_zero
+ integer(int32), intent(in), optional :: reference_bits(JTTY_TBCC_INFORMATION_BITS)
+ logical, intent(out), optional :: reference_present
+ integer(int32), intent(out), optional :: reference_pool_rank
+ integer(int32), intent(out), optional :: reference_h_rank
+ type(survivor_t), allocatable :: previous(:,:), current(:,:)
+ type(pool_candidate_t), allocatable :: pool(:)
+ integer(int32), allocatable :: order(:), hash_indices(:)
+ integer(int32), allocatable :: block_starts(:), block_lengths(:)
+ integer(int32), allocatable :: branch_bits(:,:,:), branch_end_states(:,:,:)
+ integer(int64), allocatable :: hash_keys(:)
+ real(real64), allocatable :: branch_metrics(:,:,:)
+ logical, allocatable :: hash_used(:)
+ integer(int32) :: block_length, block_start, branch_count, branch_word
+ integer(int32) :: block_count, block_index, max_branch_count
+ integer(int32) :: state_count, state, rank, wrap, end_state, output_rank
+ integer(int32) :: input_bits(4), tones(4), pool_capacity, hash_capacity
+ integer(int32) :: pool_index, hash_slot
+ integer(int64) :: identity, reference_identity
+ real(real64) :: branch_metric, clean_metric
+ logical :: prune, closed, found
+ type(survivor_t) :: extension
+
+ call validate_decoder_arguments(code, coherent_length, per_state_width, &
+ wraps, hypothesis_count)
+ state_count = code%state_count
+ block_count = (JTTY_TBCC_INFORMATION_BITS + coherent_length - 1_int32) / coherent_length
+ max_branch_count = shiftl(1_int32, coherent_length)
+ pool_capacity = state_count*per_state_width
+ hash_capacity = 1_int32
+ do while (hash_capacity < 2_int32*pool_capacity)
+ hash_capacity = 2_int32*hash_capacity
+ end do
+
+ allocate(previous(0:state_count - 1, per_state_width))
+ allocate(current(0:state_count - 1, per_state_width))
+ allocate(pool(max(1_int32, pool_capacity)))
+ allocate(order(max(1_int32, pool_capacity)))
+ allocate(hash_keys(hash_capacity), hash_indices(hash_capacity))
+ allocate(hash_used(hash_capacity))
+ allocate(block_starts(block_count), block_lengths(block_count))
+ allocate(branch_bits(4, 0:max_branch_count - 1, block_count))
+ allocate(branch_end_states(0:state_count - 1, 0:max_branch_count - 1, block_count))
+ allocate(branch_metrics(0:state_count - 1, 0:max_branch_count - 1, block_count))
+ branch_bits = 0_int32
+ branch_end_states = 0_int32
+ branch_metrics = 0.0_real64
+ do block_index = 1, block_count
+ block_start = 1_int32 + (block_index - 1_int32)*coherent_length
+ block_length = min(coherent_length, &
+ JTTY_TBCC_INFORMATION_BITS - block_start + 1_int32)
+ block_starts(block_index) = block_start
+ block_lengths(block_index) = block_length
+ branch_count = shiftl(1_int32, block_length)
+ do branch_word = 0, branch_count - 1
+ call unpack_branch_word(branch_word, block_length, input_bits)
+ branch_bits(:, branch_word, block_index) = input_bits
+ do state = 0, state_count - 1
+ call jtty_tbcc_supertransition(code, state, &
+ input_bits(1:block_length), end_state, tones(1:block_length))
+ branch_end_states(state, branch_word, block_index) = end_state
+ branch_metrics(state, branch_word, block_index) = &
+ jtty_tbcc_coherent_metric(correlations, block_start, &
+ tones(1:block_length))
+ end do
+ end do
+ end do
+ call clear_survivors(previous)
+ do state = 0, state_count - 1
+ previous(state, 1)%valid = .true.
+ previous(state, 1)%metric = 0.0_real64
+ previous(state, 1)%origin_state = state
+ end do
+
+ prune = .false.
+ if (present(prune_reserved_zero)) prune = prune_reserved_zero
+ do wrap = 1, wraps
+ call reset_frame_identity(previous)
+ do block_index = 1, block_count
+ block_start = block_starts(block_index)
+ block_length = block_lengths(block_index)
+ branch_count = shiftl(1_int32, block_length)
+ call clear_survivors(current)
+ do state = 0, state_count - 1
+ do rank = 1, per_state_width
+ if (.not.previous(state, rank)%valid) cycle
+ do branch_word = 0, branch_count - 1
+ if (prune .and. block_contains_reserved(block_start, block_length)) then
+ if (branch_bits(JTTY_TBCC_RESERVED_BIT - block_start + 1, &
+ branch_word, block_index) /= &
+ 0_int32) cycle
+ end if
+ end_state = branch_end_states(state, branch_word, block_index)
+ branch_metric = branch_metrics(state, branch_word, block_index)
+ extension = previous(state, rank)
+ extension%metric = extension%metric + branch_metric
+ extension%bits(block_start:block_start + block_length - 1) = &
+ branch_bits(1:block_length, branch_word, block_index)
+ call insert_survivor(current(end_state, :), extension, &
+ block_start + block_length - 1_int32)
+ end do
+ end do
+ end do
+ previous = current
+ end do
+ end do
+
+ pool_count = 0_int32
+ hash_used = .false.
+ hash_keys = 0_int64
+ hash_indices = 0_int32
+ do state = 0, state_count - 1
+ do rank = 1, per_state_width
+ if (.not.previous(state, rank)%valid) cycle
+ if (previous(state, rank)%origin_state /= state) cycle
+ identity = jtty_tbcc_candidate_identity(previous(state, rank)%bits)
+ call locate_identity(identity, hash_keys, hash_indices, hash_used, &
+ hash_slot, pool_index, found)
+ if (found) then
+ if (previous(state, rank)%metric > pool(pool_index)%wava_metric .or. &
+ (.not.(previous(state, rank)%metric < pool(pool_index)%wava_metric) .and. &
+ state < pool(pool_index)%start_state)) then
+ pool(pool_index)%wava_metric = previous(state, rank)%metric
+ pool(pool_index)%start_state = state
+ end if
+ cycle
+ end if
+ pool_count = pool_count + 1_int32
+ pool_index = pool_count
+ hash_used(hash_slot) = .true.
+ hash_keys(hash_slot) = identity
+ hash_indices(hash_slot) = pool_index
+ pool(pool_index)%bits = previous(state, rank)%bits
+ pool(pool_index)%identity = identity
+ pool(pool_index)%start_state = state
+ pool(pool_index)%wava_metric = previous(state, rank)%metric
+ call jtty_tbcc_score_candidate(code, correlations, coherent_length, &
+ pool(pool_index)%bits, clean_metric, closed)
+ if (.not.closed) error stop 'closed TBCC survivor failed clean scoring closure'
+ pool(pool_index)%clean_metric = clean_metric
+ pool(pool_index)%crc_valid = jtty_tbcc_crc_valid(code, pool(pool_index)%bits)
+ end do
+ end do
+
+ do pool_index = 1, pool_count
+ order(pool_index) = pool_index
+ end do
+ call sort_candidate_order(pool, order, pool_count)
+ candidate_bits = 0_int32
+ candidate_identities = 0_int64
+ candidate_clean_metrics = NEGATIVE_METRIC
+ candidate_wava_metrics = NEGATIVE_METRIC
+ candidate_start_states = -1_int32
+ candidate_crc_valid = .false.
+ candidate_count = min(hypothesis_count, pool_count)
+ do output_rank = 1, candidate_count
+ pool_index = order(output_rank)
+ candidate_bits(:, output_rank) = pool(pool_index)%bits
+ candidate_identities(output_rank) = pool(pool_index)%identity
+ candidate_clean_metrics(output_rank) = pool(pool_index)%clean_metric
+ candidate_wava_metrics(output_rank) = pool(pool_index)%wava_metric
+ candidate_start_states(output_rank) = pool(pool_index)%start_state
+ candidate_crc_valid(output_rank) = pool(pool_index)%crc_valid
+ end do
+
+ if (present(reference_present)) reference_present = .false.
+ if (present(reference_pool_rank)) reference_pool_rank = 0_int32
+ if (present(reference_h_rank)) reference_h_rank = 0_int32
+ if (present(reference_bits)) then
+ reference_identity = jtty_tbcc_candidate_identity(reference_bits)
+ do output_rank = 1, pool_count
+ pool_index = order(output_rank)
+ if (pool(pool_index)%identity /= reference_identity) cycle
+ if (.not.all(pool(pool_index)%bits == reference_bits)) cycle
+ if (present(reference_present)) reference_present = .true.
+ if (present(reference_pool_rank)) reference_pool_rank = output_rank
+ if (present(reference_h_rank)) then
+ if (output_rank <= candidate_count) reference_h_rank = output_rank
+ end if
+ exit
+ end do
+ end if
+
+ deallocate(previous, current, pool, order, hash_keys, hash_indices, hash_used)
+ deallocate(block_starts, block_lengths, branch_bits, branch_end_states, branch_metrics)
+ end subroutine jtty_tbcc_list_wava_reference
+
+
+ pure subroutine planned_supertransition(plan, start_state, input_bits, &
+ block_length, end_state, tones, tone_word)
+ type(jtty_tbcc_decoder_plan), intent(in) :: plan
+ integer(int32), intent(in) :: start_state, input_bits(4), block_length
+ integer(int32), intent(out) :: end_state, tones(4), tone_word
+ integer(int32) :: offset, state
+
+ state = start_state
+ tones = 0_int32
+ tone_word = 0_int32
+ do offset = 1, block_length
+ tones(offset) = plan%tone(state, input_bits(offset))
+ tone_word = 4_int32*tone_word + tones(offset)
+ state = plan%next_state(state, input_bits(offset))
+ end do
+ end_state = state
+ end subroutine planned_supertransition
+
+ subroutine precompute_sequence_energies(plan, correlations, energies)
+ type(jtty_tbcc_decoder_plan), intent(in) :: plan
+ complex(real32), intent(in) :: correlations(0:3, JTTY_TBCC_INFORMATION_BITS)
+ real(real64), intent(out) :: energies(:)
+ complex(real32) :: coherent_sum
+ integer(int32) :: block_index, block_length, block_start
+ integer(int32) :: offset, sequence_count, sequence_word, tone
+
+ do block_index = 1, plan%block_count
+ block_start = plan%block_starts(block_index)
+ block_length = plan%block_lengths(block_index)
+ sequence_count = shiftl(1_int32, 2_int32*block_length)
+ do sequence_word = 0, sequence_count - 1
+ coherent_sum = cmplx(0.0_real32, 0.0_real32, real32)
+ do offset = 1, block_length
+ tone = ibits(sequence_word, 2_int32*(block_length - offset), 2)
+ coherent_sum = coherent_sum + correlations(tone, block_start + offset - 1_int32)
+ end do
+ energies(plan%energy_offsets(block_index) + sequence_word) = &
+ real(coherent_sum*conjg(coherent_sum), real64) / real(block_length, real64)
+ end do
+ end do
+ end subroutine precompute_sequence_energies
+
+ subroutine score_planned_identity(plan, energies, identity, metric, closed)
+ type(jtty_tbcc_decoder_plan), intent(in) :: plan
+ real(real64), intent(in) :: energies(:)
+ integer(int64), intent(in) :: identity
+ real(real64), intent(out) :: metric
+ logical, intent(out) :: closed
+ integer(int32) :: bit_index, block_index, branch_word, offset, state, start_state
+
+ start_state = 0_int32
+ do bit_index = JTTY_TBCC_INFORMATION_BITS - plan%code%memory_nu + 1, &
+ JTTY_TBCC_INFORMATION_BITS
+ start_state = iand(ior(shiftl(start_state, 1), &
+ merge(1_int32, 0_int32, btest(identity, bit_index - 1))), &
+ plan%state_count - 1_int32)
+ end do
+ state = start_state
+ metric = 0.0_real64
+ do block_index = 1, plan%block_count
+ branch_word = 0_int32
+ do offset = 0, plan%block_lengths(block_index) - 1
+ branch_word = 2_int32*branch_word + merge(1_int32, 0_int32, &
+ btest(identity, plan%block_starts(block_index) + offset - 1_int32))
+ end do
+ metric = metric + energies( &
+ plan%branch_sequence_indices(state, branch_word, block_index))
+ state = plan%branch_end_states(state, branch_word, block_index)
+ end do
+ closed = state == start_state
+ end subroutine score_planned_identity
+
+ pure integer(int64) function reverse_identity(key) result(identity)
+ integer(int64), intent(in) :: key
+ integer(int32) :: bit_index
+
+ identity = 0_int64
+ do bit_index = 0, JTTY_TBCC_INFORMATION_BITS - 1
+ if (btest(key, bit_index)) identity = ibset(identity, JTTY_TBCC_INFORMATION_BITS - bit_index - 1)
+ end do
+ end function reverse_identity
+
+ pure subroutine unpack_identity(identity, bits)
+ integer(int64), intent(in) :: identity
+ integer(int32), intent(out) :: bits(JTTY_TBCC_INFORMATION_BITS)
+ integer(int32) :: bit_index
+
+ do bit_index = 1, JTTY_TBCC_INFORMATION_BITS
+ bits(bit_index) = merge(1_int32, 0_int32, btest(identity, bit_index - 1))
+ end do
+ end subroutine unpack_identity
+
+ subroutine clear_packed_survivors(survivors)
+ type(packed_survivor_t), intent(inout) :: survivors(0:, :)
+ integer(int32) :: rank, state
+
+ do rank = 1, size(survivors, 2)
+ do state = 0, size(survivors, 1) - 1
+ survivors(state, rank)%key = 0_int64
+ survivors(state, rank)%metric = NEGATIVE_METRIC
+ end do
+ end do
+ end subroutine clear_packed_survivors
+
+ subroutine reset_packed_frame_identity(survivors)
+ type(packed_survivor_t), intent(inout) :: survivors(0:, :)
+ integer(int32) :: rank, state
+
+ do rank = 1, size(survivors, 2)
+ do state = 0, size(survivors, 1) - 1
+ if (.not.btest(survivors(state, rank)%key, PACKED_VALID_BIT)) cycle
+ survivors(state, rank)%key = ibset(shiftl(int(state, int64), JTTY_TBCC_INFORMATION_BITS), PACKED_VALID_BIT)
+ end do
+ end do
+ end subroutine reset_packed_frame_identity
+
+ subroutine advance_packed_survivors(plan, block_index, prune, energies, previous, current, ordered_metrics)
+ type(jtty_tbcc_decoder_plan), intent(in) :: plan
+ integer(int32), intent(in) :: block_index
+ logical, intent(in) :: prune, ordered_metrics
+ real(real64), intent(in) :: energies(:)
+ type(packed_survivor_t), intent(in) :: previous(0:, :)
+ type(packed_survivor_t), intent(inout) :: current(0:, :)
+ type(packed_survivor_t) :: selected(4), extension
+ integer(int32) :: branch_count, branch_word, end_state, state, state_stride
+ integer(int32) :: rank, width
+ integer(int64) :: branch_identity
+ real(real64) :: branch_metric, metric
+ logical :: prune_block
+
+ width = plan%per_state_width
+ branch_count = plan%branch_counts(block_index)
+ state_stride = plan%state_count / branch_count
+ prune_block = prune .and. block_contains_reserved( &
+ plan%block_starts(block_index), plan%block_lengths(block_index))
+ do end_state = 0, plan%state_count - 1
+ selected%key = 0_int64
+ branch_word = iand(end_state, branch_count - 1_int32)
+ branch_identity = plan%branch_identities(branch_word, block_index)
+ if (.not.(prune_block .and. btest(branch_identity, JTTY_TBCC_INFORMATION_BITS - JTTY_TBCC_RESERVED_BIT))) then
+ ! The low L destination bits are the input word; the discarded high
+ ! L source bits enumerate every predecessor in the original order.
+ do state = end_state / branch_count, plan%state_count - 1, state_stride
+ branch_metric = energies(plan%branch_sequence_indices(state, branch_word, block_index))
+ do rank = 1, width
+ if (.not.btest(previous(state, rank)%key, PACKED_VALID_BIT)) cycle
+ metric = previous(state, rank)%metric + branch_metric
+ if (btest(selected(width)%key, PACKED_VALID_BIT)) then
+ if (metric < selected(width)%metric) then
+ ! Lower ranks receive the same branch metric and cannot recover.
+ if (ordered_metrics) exit
+ cycle
+ end if
+ end if
+ extension = previous(state, rank)
+ extension%metric = metric
+ extension%key = ior(extension%key, branch_identity)
+ call insert_packed_survivor(selected, width, extension, block_index == 1)
+ end do
+ end do
+ end if
+ do rank = 1, width
+ current(end_state, rank) = selected(rank)
+ end do
+ end do
+ end subroutine advance_packed_survivors
+
+ subroutine insert_packed_survivor(survivors, width, candidate, deduplicate)
+ type(packed_survivor_t), intent(inout) :: survivors(4)
+ type(packed_survivor_t), intent(in) :: candidate
+ integer(int32), intent(in) :: width
+ logical, intent(in) :: deduplicate
+ integer(int32) :: insertion_slot, slot
+
+ ! Resetting a wrap's origins and identities can duplicate a state's ranks.
+ ! After the first block, an origin and prefix determine exactly one path,
+ ! so extending distinct retained paths cannot create another duplicate.
+ if (deduplicate) then
+ do slot = 1, width
+ if (.not.btest(survivors(slot)%key, PACKED_VALID_BIT)) cycle
+ if (survivors(slot)%key == candidate%key) then
+ if (candidate%metric <= survivors(slot)%metric) return
+ do insertion_slot = 1, 3
+ if (insertion_slot >= slot .and. insertion_slot < width) &
+ survivors(insertion_slot) = survivors(insertion_slot + 1)
+ end do
+ survivors(width)%key = 0_int64
+ exit
+ end if
+ end do
+ end if
+
+ insertion_slot = width + 1_int32
+ do slot = 1, width
+ if (.not.btest(survivors(slot)%key, PACKED_VALID_BIT) .or. &
+ packed_survivor_precedes(candidate, survivors(slot))) then
+ insertion_slot = slot
+ exit
+ end if
+ end do
+ if (insertion_slot > width) return
+ do slot = 4, 2, -1
+ if (slot <= width .and. slot > insertion_slot) survivors(slot) = survivors(slot - 1)
+ end do
+ survivors(insertion_slot) = candidate
+ end subroutine insert_packed_survivor
+
+ pure logical function packed_survivor_precedes(left, right) &
+ result(precedes)
+ type(packed_survivor_t), intent(in) :: left, right
+
+ if (left%metric > right%metric) then
+ precedes = .true.
+ return
+ else if (left%metric < right%metric) then
+ precedes = .false.
+ return
+ end if
+ precedes = left%key < right%key
+ end function packed_survivor_precedes
+
+ subroutine validate_optimized_storage(plan, workspace, candidate_bits, &
+ candidate_identities, candidate_clean_metrics, candidate_wava_metrics, &
+ candidate_start_states, candidate_crc_valid)
+ type(jtty_tbcc_decoder_plan), intent(in) :: plan
+ type(jtty_tbcc_decoder_workspace), intent(in) :: workspace
+ integer(int32), intent(in) :: candidate_bits(:, :)
+ integer(int64), intent(in) :: candidate_identities(:)
+ real(real64), intent(in) :: candidate_clean_metrics(:), candidate_wava_metrics(:)
+ integer(int32), intent(in) :: candidate_start_states(:)
+ logical, intent(in) :: candidate_crc_valid(:)
+
+ if (.not.plan%initialized) error stop 'TBCC list decoder plan is not initialized'
+ if (.not.workspace%initialized) &
+ error stop 'TBCC list decoder workspace is not initialized'
+ if (size(workspace%previous, 1) /= plan%state_count .or. &
+ size(workspace%previous, 2) /= plan%per_state_width .or. &
+ size(workspace%sequence_energies) /= plan%energy_count) &
+ error stop 'TBCC list decoder workspace does not match plan'
+ if (size(candidate_bits, 1) /= JTTY_TBCC_INFORMATION_BITS .or. &
+ size(candidate_bits, 2) < plan%hypothesis_count .or. &
+ size(candidate_identities) < plan%hypothesis_count .or. &
+ size(candidate_clean_metrics) < plan%hypothesis_count .or. &
+ size(candidate_wava_metrics) < plan%hypothesis_count .or. &
+ size(candidate_start_states) < plan%hypothesis_count .or. &
+ size(candidate_crc_valid) < plan%hypothesis_count) &
+ error stop 'TBCC list decoder output storage is too small'
+ end subroutine validate_optimized_storage
+
+
+ subroutine validate_decoder_arguments(code, coherent_length, per_state_width, &
+ wraps, hypothesis_count)
+ type(jtty_tbcc_code_profile), intent(in) :: code
+ integer(int32), intent(in) :: coherent_length, per_state_width, wraps
+ integer(int32), intent(in) :: hypothesis_count
+ if (.not.jtty_tbcc_code_profile_is_supported(code)) &
+ error stop 'TBCC list decoder requires a supported code profile'
+ if (coherent_length /= 1_int32 .and. coherent_length /= 2_int32 .and. &
+ coherent_length /= 4_int32) &
+ error stop 'TBCC list decoder supports coherent lengths 1, 2, and 4'
+ if (per_state_width < 1_int32 .or. per_state_width > 4_int32) &
+ error stop 'TBCC list decoder per-state width must be between 1 and 4'
+ if (wraps < 1_int32 .or. wraps > 2_int32) &
+ error stop 'TBCC list decoder supports one or two wraps'
+ if (hypothesis_count < 1_int32 .or. &
+ hypothesis_count > JTTY_TBCC_MAX_HYPOTHESES) &
+ error stop 'TBCC list decoder hypothesis count must be between 1 and 4'
+ end subroutine validate_decoder_arguments
+
+ subroutine clear_survivors(survivors)
+ type(survivor_t), intent(inout) :: survivors(0:, :)
+ integer(int32) :: rank, state
+
+ do rank = 1, size(survivors, 2)
+ do state = 0, size(survivors, 1) - 1
+ survivors(state, rank)%valid = .false.
+ survivors(state, rank)%metric = NEGATIVE_METRIC
+ survivors(state, rank)%origin_state = -1_int32
+ survivors(state, rank)%bits = 0_int32
+ end do
+ end do
+ end subroutine clear_survivors
+
+ subroutine reset_frame_identity(survivors)
+ type(survivor_t), intent(inout) :: survivors(0:, :)
+ integer(int32) :: rank, state
+
+ do rank = 1, size(survivors, 2)
+ do state = 0, size(survivors, 1) - 1
+ if (.not.survivors(state, rank)%valid) cycle
+ survivors(state, rank)%origin_state = state
+ survivors(state, rank)%bits = 0_int32
+ end do
+ end do
+ end subroutine reset_frame_identity
+
+ pure subroutine unpack_branch_word(branch_word, block_length, input_bits)
+ integer(int32), intent(in) :: branch_word, block_length
+ integer(int32), intent(out) :: input_bits(4)
+ integer(int32) :: offset
+
+ input_bits = 0_int32
+ do offset = 1, block_length
+ input_bits(offset) = ibits(branch_word, block_length - offset, 1)
+ end do
+ end subroutine unpack_branch_word
+
+ pure logical function block_contains_reserved(block_start, block_length) &
+ result(contains_reserved)
+ integer(int32), intent(in) :: block_start, block_length
+
+ contains_reserved = block_start <= JTTY_TBCC_RESERVED_BIT .and. &
+ block_start + block_length > JTTY_TBCC_RESERVED_BIT
+ end function block_contains_reserved
+
+ subroutine insert_survivor(survivors, candidate, prefix_length)
+ type(survivor_t), intent(inout) :: survivors(:)
+ type(survivor_t), intent(in) :: candidate
+ integer(int32), intent(in) :: prefix_length
+ integer(int32) :: slot, insertion_slot
+
+ do slot = 1, size(survivors)
+ if (.not.survivors(slot)%valid) cycle
+ if (survivors(slot)%origin_state /= candidate%origin_state) cycle
+ if (.not.all(survivors(slot)%bits(1:prefix_length) == &
+ candidate%bits(1:prefix_length))) cycle
+ if (candidate%metric <= survivors(slot)%metric) return
+ do insertion_slot = slot, size(survivors) - 1
+ survivors(insertion_slot) = survivors(insertion_slot + 1)
+ end do
+ survivors(size(survivors))%valid = .false.
+ survivors(size(survivors))%metric = NEGATIVE_METRIC
+ survivors(size(survivors))%origin_state = -1_int32
+ survivors(size(survivors))%bits = 0_int32
+ exit
+ end do
+
+ insertion_slot = size(survivors) + 1
+ do slot = 1, size(survivors)
+ if (.not.survivors(slot)%valid .or. &
+ survivor_precedes(candidate, survivors(slot), prefix_length)) then
+ insertion_slot = slot
+ exit
+ end if
+ end do
+ if (insertion_slot > size(survivors)) return
+ do slot = size(survivors), insertion_slot + 1, -1
+ survivors(slot) = survivors(slot - 1)
+ end do
+ survivors(insertion_slot) = candidate
+ end subroutine insert_survivor
+
+ pure logical function survivor_precedes(left, right, prefix_length) result(precedes)
+ type(survivor_t), intent(in) :: left, right
+ integer(int32), intent(in) :: prefix_length
+ integer(int32) :: bit_index
+
+ if (left%metric > right%metric) then
+ precedes = .true.
+ return
+ else if (left%metric < right%metric) then
+ precedes = .false.
+ return
+ else
+ precedes = left%metric > right%metric
+ end if
+ if (left%origin_state /= right%origin_state) then
+ precedes = left%origin_state < right%origin_state
+ return
+ end if
+ do bit_index = 1, prefix_length
+ if (left%bits(bit_index) == right%bits(bit_index)) cycle
+ precedes = left%bits(bit_index) < right%bits(bit_index)
+ return
+ end do
+ precedes = .false.
+ end function survivor_precedes
+
+ subroutine locate_identity(identity, hash_keys, hash_indices, hash_used, &
+ hash_slot, pool_index, found)
+ integer(int64), intent(in) :: identity
+ integer(int64), intent(in) :: hash_keys(:)
+ integer(int32), intent(in) :: hash_indices(:)
+ logical, intent(in) :: hash_used(:)
+ integer(int32), intent(out) :: hash_slot, pool_index
+ logical, intent(out) :: found
+
+ hash_slot = 1_int32 + int(modulo(identity, int(size(hash_keys), int64)), int32)
+ do
+ if (.not.hash_used(hash_slot)) then
+ pool_index = 0_int32
+ found = .false.
+ return
+ end if
+ if (hash_keys(hash_slot) == identity) then
+ pool_index = hash_indices(hash_slot)
+ found = .true.
+ return
+ end if
+ hash_slot = hash_slot + 1_int32
+ if (hash_slot > size(hash_keys)) hash_slot = 1_int32
+ end do
+ end subroutine locate_identity
+
+ subroutine sort_candidate_order(pool, order, count)
+ type(pool_candidate_t), intent(in) :: pool(:)
+ integer(int32), intent(inout) :: order(:)
+ integer(int32), intent(in) :: count
+ integer(int32), allocatable :: scratch(:)
+
+ if (count <= 1_int32) return
+ allocate(scratch(count))
+ call sort_candidate_order_with_scratch(pool, order, scratch, count)
+ deallocate(scratch)
+ end subroutine sort_candidate_order
+
+ subroutine sort_candidate_order_with_scratch(pool, order, scratch, count)
+ type(pool_candidate_t), intent(in) :: pool(:)
+ integer(int32), intent(inout) :: order(:), scratch(:)
+ integer(int32), intent(in) :: count
+ integer(int32) :: left, middle, right, width
+
+ if (count <= 1_int32) return
+ width = 1_int32
+ do while (width < count)
+ left = 1_int32
+ do while (left <= count)
+ middle = min(left + width, count + 1_int32)
+ right = min(left + 2_int32*width - 1_int32, count)
+ call merge_candidate_order(pool, order, scratch, left, middle, right)
+ left = left + 2_int32*width
+ end do
+ order(1:count) = scratch(1:count)
+ width = 2_int32*width
+ end do
+ end subroutine sort_candidate_order_with_scratch
+
+ subroutine merge_candidate_order(pool, order, scratch, left, middle, right)
+ type(pool_candidate_t), intent(in) :: pool(:)
+ integer(int32), intent(in) :: order(:), left, middle, right
+ integer(int32), intent(inout) :: scratch(:)
+ integer(int32) :: left_cursor, right_cursor, output
+
+ left_cursor = left
+ right_cursor = middle
+ do output = left, right
+ if (left_cursor >= middle) then
+ scratch(output) = order(right_cursor)
+ right_cursor = right_cursor + 1_int32
+ else if (right_cursor > right) then
+ scratch(output) = order(left_cursor)
+ left_cursor = left_cursor + 1_int32
+ else if (candidate_precedes(pool(order(left_cursor)), &
+ pool(order(right_cursor)))) then
+ scratch(output) = order(left_cursor)
+ left_cursor = left_cursor + 1_int32
+ else
+ scratch(output) = order(right_cursor)
+ right_cursor = right_cursor + 1_int32
+ end if
+ end do
+ end subroutine merge_candidate_order
+
+ pure logical function candidate_precedes(left, right) result(precedes)
+ type(pool_candidate_t), intent(in) :: left, right
+
+ if (left%clean_metric > right%clean_metric) then
+ precedes = .true.
+ else if (left%clean_metric < right%clean_metric) then
+ precedes = .false.
+ else if (left%identity /= right%identity) then
+ precedes = left%identity < right%identity
+ else if (left%start_state /= right%start_state) then
+ precedes = left%start_state < right%start_state
+ else
+ precedes = left%wava_metric > right%wava_metric
+ end if
+ end function candidate_precedes
+
+end module jtty_tbcc_list_decoder
diff --git a/lib/jtty/jtty_tx_manual_checks.md b/lib/jtty/jtty_tx_manual_checks.md
new file mode 100644
index 00000000..bcb4ff44
--- /dev/null
+++ b/lib/jtty/jtty_tx_manual_checks.md
@@ -0,0 +1,65 @@
+# JTTY transmit manual checks
+
+These checks cover MainWindow, PTT, and backend behavior that is outside the
+FIFO unit-test boundary.
+
+- Soundcard: send one JTTY message and verify the full tail plays before PTT drops.
+- Soundcard: queue two or three messages rapidly and verify playback is contiguous with PTT held.
+- Soundcard: press Stop during playback and verify queued audio is abandoned before PTT drops.
+- Soundcard: press Esc before PTT comes up and during playback and verify clean aborts.
+- Soundcard: send again after a natural drain and verify a fresh transmit session starts.
+- TCI, where available: repeat the same checks and watch for backend enqueue failure warnings.
+- Native macros: activate each default JTTY F1-F8 template by keyboard and by
+ clicking its button; verify both paths show the same canonical message and
+ enqueue the same number of frames.
+- Native macros: enter a valid call and serial, send a call-plus-exchange
+ template, and verify EOM appears only on the final atom.
+- Native macros: make a recognized template's runtime call or serial invalid
+ and verify transmission is rejected rather than sent as literal text.
+- Literal fallback: customize a function-key template so it no longer matches
+ a native form and verify automatic packing preserves its expanded text after
+ the selected profile's normalization.
+- Free entry: with MyCall K1ABC, compare F1 with typing `CQ K1ABC CQ` and
+ selecting Send message; verify the same text and one frame. Repeat with
+ `CQ K1ABC CQ CQ K1ABC CQ`, verifying two frames and unchanged spacing.
+- External text: send `CQ K1ABC CQ`, `599 123`, `599 MA`, `599 FN42`, and
+ `1D EMA` from N1MM/MMTTY; verify each uses one frame and preserves the text.
+ With no special activity or with Field Day, send `599 001`, `599 05`, and
+ `599 BRUCE`; verify each uses two frames and preserves the text.
+- Automatic profile: select RTTY Roundup and send `599 001` and
+ `K1ABC 599 001`; verify one and two frames respectively. Verify `599 123`
+ and `599 MA` use SERIAL and STATE_PROVINCE rather than generic atoms.
+ Verify `599 05` and `599 0123` become `599 005` and `599 123`, each in one
+ frame, with the canonical text shown and logged. Verify bare `001` retains
+ its spelling and is not inferred as SERIAL. Verify unsupported serial
+ tokens (over six digits or above 131071) retain their spelling. Verify a
+ message whose serial normalization expands beyond 80 characters is rejected
+ rather than truncated. Submit a message, change activity
+ before it plays, and verify the submitted message retains its captured
+ profile. Repeat through untagged N1MM/MMTTY and customized macro fallback.
+- sjtty: compare default and leading `--exchange-profile=rtty-roundup` with
+ `599 001`; verify two and one frames. Exercise `unknown` and `field-day`,
+ the eight-argument waveform invocation, and rejection of an invalid value.
+- Mixed text: send `HI WB9XYZ`, `TEST WB9XYZ`, and `K1ABC HELLO`; verify no
+ spaces are inserted or lost where TEXT5 and compact atoms meet. Send a
+ registered control phrase alone and embedded in a longer message.
+- Queueing: queue two native messages and verify no visible or transmitted
+ TEXT5 spacing frame is inserted between them.
+- Profile exchange: exercise `%E` with default serial, FIELD_DAY class/section,
+ and both RTTY serial and state/province payloads; verify canonical rendering
+ and rejection of a payload from the wrong profile.
+- Grid macros: verify `%G` renders field-only GRID4 and exact `599 %G` renders
+ full-role GRID4; reject malformed locators.
+- Settings migration: load unchanged old F2, F6, and F8 defaults using `%N`
+ and verify migration to `%E`; verify any edited variant remains literal.
+- Windows/N1MM: load `JTTY Messages.mc`, exercise every tagged Run and S&P
+ action, and verify the `[[JTTY:ACTION]]` marker is consumed rather than
+ transmitted. Reject malformed tags, invalid profile payloads, and unknown
+ actions; verify untagged TXTEXT remains literal. Verify an all-rejected
+ transaction completes at OFF, and a rejected action followed by a valid
+ action still starts and completes only after the accepted audio drains.
+- Windows/N1MM: in a two-radio configuration, verify entry-window focus, `!`
+ and `{CALL}` expansion, queued-call selection, `{LOGTHENPOP}`, and Run/S&P
+ state changes. Before adding a Run F11 call-stacking macro, capture its
+ TXTEXT ordering and verify that the leading tag, callsign, and exchange all
+ refer to the intended queued station.
diff --git a/lib/ft2/ft2audio.c b/lib/jtty/jttyaudio.c
index b5f19fa4..f4571117 100644
--- a/lib/ft2/ft2audio.c
+++ b/lib/jtty/jttyaudio.c
@@ -1,10 +1,16 @@
#include <stdio.h>
+#include <conio.h>
#include "portaudio.h"
#include <string.h>
#include <time.h>
+// Prototypes for Fortran subroutine update
+void update_(int* ic1, int* ic2);
+
int iaa;
int icc;
+int n2send=0;
+int ndebug=0;
double total_time=0.0;
// Definition of structure pointing to the audio data
@@ -36,7 +42,10 @@ SoundIn( void *inputBuffer, void *outputBuffer,
unsigned int i;
static int ia=0;
+// Don't save audio input samples when we're transmitting
if(*data->Transmitting) return 0;
+
+ if(outputBuffer == timeInfo) i=0; //Suppress 'unused' warnings
if(statusFlags!=0) printf("Status flags %d\n",(int)statusFlags);
@@ -48,21 +57,21 @@ SoundIn( void *inputBuffer, void *outputBuffer,
data->y1[ia] = (*in++);
data->y2[ia] = (*in++);
ia++;
+ if(ia >= data->nring) ia=0; //Wrap buffer pointer if necessary
}
} else { //Use right channel
for(i=0; i<framesPerBuffer; i++) {
data->y2[ia] = (*in++);
data->y1[ia] = (*in++);
ia++;
+ if(ia >= data->nring) ia=0; //Wrap buffer pointer if necessary
}
}
}
- if(ia >= data->nring) ia=0; //Wrap buffer pointer if necessary
*data->iwrite = ia; //Save buffer pointer
iaa=ia;
total_time += (double)framesPerBuffer/12000.0;
- // printf("iwrite: %d\n",*data->iwrite);
return 0;
}
@@ -76,15 +85,16 @@ SoundOut( void *inputBuffer, void *outputBuffer,
{
paTestData *data = (paTestData*)userData;
short *wptr = (short*)outputBuffer;
- unsigned int i,n;
+ unsigned int i;
static short int n2;
static int ic=0;
static int TxOKz=0;
- static clock_t tstart=-1;
- static clock_t tend=-1;
static int nsent=0;
- // printf("txOK: %d %d\n",TxOKz,*data->TxOK);
+ if(inputBuffer == timeInfo) i=0; //Suppress 'unused' warnings
+ if(statusFlags!=0) printf("Status flags %d\n",(int)statusFlags);
+
+ // if(ndebug>0) printf("SoundOut: %d %d %d\n",TxOKz,*data->TxOK,(int)framesPerBuffer);
if(*data->TxOK && (!TxOKz)) ic=0; //Reset buffer pointer to start Tx
*data->Transmitting=*data->TxOK; //Set the "transmitting" flag
@@ -92,25 +102,27 @@ SoundOut( void *inputBuffer, void *outputBuffer,
if(*data->TxOK) {
if(!TxOKz) {
// Start of a transmission
- tstart=clock();
nsent=0;
- // printf("Start Tx\n");
+ if(ndebug>0) printf("Start Tx %d %d\n",TxOKz,*data->TxOK);
}
TxOKz=*data->TxOK;
for(i=0 ; i < framesPerBuffer; i++ ) {
n2=data->iwave[ic];
+ // addnoise_(&n2);
*wptr++ = n2; //left
*wptr++ = n2; //right
ic++;
- if(ic > *data->nwave) {
+ if(ic > n2send) {
*data->TxOK = 0;
*data->Transmitting = 0;
*data->iwrite = 0; //Reset Rx buffer pointer to 0
+ TxOKz=0; //### ??? ###
ic=0;
- tend=clock();
- double TxT=((double)(tend-tstart))/CLOCKS_PER_SEC;
- // printf("End Tx, TxT = %f nSent = %d\n",TxT,nsent);
+ if(ndebug>0) {
+ printf("TxT = %7.3f nSent = %d Frames = %7.3f\n",nsent/12000.0,
+ nsent,nsent/(53.0*384.0));
+ }
break;
}
}
@@ -124,10 +136,10 @@ SoundOut( void *inputBuffer, void *outputBuffer,
}
/*******************************************************************/
-int ft2audio_(int *ndevin, int *ndevout, int *npabuf, int *nright,
+int jttyaudio_(int *ndevin, int *ndevout, int *npabuf, int *nright,
short y1[], short y2[], int *nring, int *iwrite,
int *itx, short iwave[], int *nwave, int *nfsample,
- int *TxOK, int *Transmitting, int *ngo)
+ int *TxOK, int *Transmitting, int *ngo, int *ndebug0)
{
paTestData data;
@@ -140,6 +152,7 @@ int ft2audio_(int *ndevin, int *ndevout, int *npabuf, int *nright,
int ndevice_in = *ndevin;
int ndevice_out = *ndevout;
double dSampleRate = (double) *nfsample;
+ ndebug = *ndebug0;
PaError err_init, err_open_in, err_open_out, err_start_in, err_start_out;
PaError err = 0;
@@ -171,7 +184,7 @@ int ft2audio_(int *ndevin, int *ndevout, int *npabuf, int *nright,
inputParameters.device = ndevice_in;
inputParameters.channelCount = 2;
inputParameters.sampleFormat = paInt16;
- inputParameters.suggestedLatency = 0.2;
+ inputParameters.suggestedLatency = 0.1;
inputParameters.hostApiSpecificStreamInfo = NULL;
// Test if this configuration actually works, so we do not run into an
@@ -259,24 +272,28 @@ int ft2audio_(int *ndevin, int *ndevout, int *npabuf, int *nright,
}
}
- if (err == 0) printf("Audio streams running normally.\n******************************************************************\n");
+ if (err != 0) printf("Error starting audio input or output.\n");
while( Pa_IsStreamActive(instream) && (*ngo != 0) && (err == 0) ) {
int ic1=0;
int ic2=0;
+
if(_kbhit()) ic1 = _getch();
if(_kbhit()) ic2 = _getch();
- // if(ic1!=0 || ic2!=0) printf("%d %d %d\n",iaa,ic1,ic2);
- update_(&total_time,&ic1,&ic2);
+
+ // if(ic1!=0 || ic2!=0) printf("%d %d %d\n",iaa,ic1,ic2);
+ // if(ic1!=0 && ic2==0) putchar(ic1);
+
+ update_(&ic1,&ic2);
Pa_Sleep(100);
}
- Pa_AbortStream(instream); // Abort stream
- Pa_CloseStream(instream); // Close stream, we're done.
- Pa_AbortStream(outstream); // Abort stream
- Pa_CloseStream(outstream); // Close stream, we're done.
+ Pa_AbortStream(instream); // Abort input stream
+ Pa_CloseStream(instream); // Close input stream, we're done.
+ Pa_AbortStream(outstream); // Abort output stream
+ Pa_CloseStream(outstream); // Close output stream, we're done.
- Pa_Terminate();
+ Pa_Terminate(); // Terminate PortAudio
return(err);
}
@@ -313,35 +330,47 @@ int padevsub_(int *idevin, int *idevout)
ndefout = 0;
}
- printf("\nAudio Input Output Device Name\n");
- printf("Device Channels Channels\n");
- printf("------------------------------------------------------------------\n");
+ if(*idevin < 0) {
+ printf("\nAudio Input Output Device Name\n");
+ printf("Device Channels Channels\n");
+ printf("------------------------------------------------------------------\n");
- for( i=0; i < numDevices; i++ ) {
- pdi = Pa_GetDeviceInfo(i);
+ for( i=0; i < numDevices; i++ ) {
+ pdi = Pa_GetDeviceInfo(i);
// if(i == Pa_GetDefaultInputDevice()) ndefin = i;
// if(i == Pa_GetDefaultOutputDevice()) ndefout = i;
- nchin[i]=pdi->maxInputChannels;
- nchout[i]=pdi->maxOutputChannels;
- printf(" %2d %2d %2d %s\n",i,nchin[i],nchout[i],
- pdi->name);
+ nchin[i]=pdi->maxInputChannels;
+ nchout[i]=pdi->maxOutputChannels;
+ printf(" %2d %2d %2d %s\n",i,nchin[i],nchout[i],
+ pdi->name);
+ }
+ printf("\nDefault devices: Input = %2d Output = %2d\n",
+ ndefin,ndefout);
}
- printf("\nUser requested devices: Input = %2d Output = %2d\n",
- *idevin,*idevout);
- printf("Default devices: Input = %2d Output = %2d\n",
- ndefin,ndefout);
+ // printf("\nUser requested devices: Input = %2d Output = %2d\n",
+ // *idevin,*idevout);
if((*idevin<0) || (*idevin>=numdev)) *idevin=ndefin;
if((*idevout<0) || (*idevout>=numdev)) *idevout=ndefout;
if((*idevin==0) && (*idevout==0)) {
*idevin=ndefin;
*idevout=ndefout;
}
- printf("Will open devices: Input = %2d Output = %2d\n",
- *idevin,*idevout);
+ // printf("Will open devices: Input = %2d Output = %2d\n",
+ // *idevin,*idevout);
Pa_Terminate();
return 0;
}
+void set_tx_length_(int* nwave)
+{
+ n2send=*nwave;
+ // printf("n2send = %d\n",n2send);
+}
+
+void putchar_(int *n)
+{
+ putchar(*n);
+}
diff --git a/lib/jtty/jttycom.f90 b/lib/jtty/jttycom.f90
new file mode 100644
index 00000000..d6efab19
--- /dev/null
+++ b/lib/jtty/jttycom.f90
@@ -0,0 +1,31 @@
+module jttycom
+
+ implicit none
+
+! Variable Purpose
+!---------------------------------------------------------------------------
+ integer NMAX
+ parameter(NMAX=30*12000) !Ring buffer at 12000 samples/sec
+ real ftx !Tx audio frequency
+ integer iwrite !Pointer to Rx ring buffer
+ integer itx !Pointer to Tx buffer
+ integer ngo !Set to 0 to terminate audio streams
+ integer nTransmitting !Actually transmitting?
+ integer nTxOK !OK to transmit?
+ integer ndebug
+ logical ltx(5) !True if msg i has been transmitted
+ logical lrx(5) !True if msg i has been received
+ logical autoseq
+ logical QSO_in_progress
+ integer*2 y1(NMAX) !Ring buffer for audio channel 0
+ integer*2 y2(NMAX) !Ring buffer for audio channel 1
+ integer*2 iwave(NMAX) !Data for Tx audio
+ character*6 mycall
+ character*6 hiscall
+ character*6 hiscall_next
+ character*4 mygrid
+ character*4 exch
+ character*80 txmsg
+ save iwave,y1,y2
+
+end module jttycom
diff --git a/lib/ft2/portaudio.h b/lib/jtty/portaudio.h
index 250fba02..250fba02 100644
--- a/lib/ft2/portaudio.h
+++ b/lib/jtty/portaudio.h
diff --git a/lib/jtty/rjtty.f90 b/lib/jtty/rjtty.f90
new file mode 100644
index 00000000..16c6263e
--- /dev/null
+++ b/lib/jtty/rjtty.f90
@@ -0,0 +1,85 @@
+program rjtty
+
+! Decode JTTY data in one or more WAV files.
+
+ use wavhdr
+ use jtty_mod
+ use jtty_mdec
+
+! MAX_FRAMES = 16 in pack_jtty. Each frame is
+! 59 symbols (13 sync + 46 codeword).
+! Maximum length of a transmission is
+! 16*59*(symbol_duration).
+! With baud rate 31.25 s^-1, symbol duration = 32 ms,
+! so maximum txt = 16*59*0.032 = 30.208 s.
+
+ parameter (NMAX=180*12000) !Max length of data
+ type(hdr) h
+ character*80 fname
+ character*8 arg
+ integer*2 iwave(NMAX)
+ logical success,newsig
+
+ f0=1500.0
+ ftol=50.0
+ nsps = 384
+ nfa=200
+ nfb=2800
+
+ nargs=iargc()
+ if(nargs.lt.6) then
+ print*,'Usage: rjtty smin ndebug nsps f0 ftol fname [...]'
+ print*,'Examples: rjtty 4.6 0 384 1500 50 000000_000001.wav'
+ print*,' rjtty 4.6 1 240 1500 50 *.wav'
+ print*,'nsps choices are: 240, 320, 384, 480 samples/symbol'
+ go to 999
+ endif
+ call getarg(1,arg)
+ read(arg,*) smin
+ call getarg(2,arg)
+ read(arg,*) ndebug
+ call getarg(3,arg)
+ read(arg,*) nsps
+ if(nsps .ne. 240 .and. nsps .ne. 320 .and. nsps .ne. 384 .and. nsps .ne. 480) then
+ print*,'nsps choices are: 240, 320, 384, 480 samples/symbol'
+ endif
+ call getarg(4,arg)
+ read(arg,*) f0
+ call getarg(5,arg)
+ read(arg,*) ftol
+
+ nframe = 59*nsps
+ nchunk = nframe + nframe/4
+ ndecodes = 0
+
+ do ifile=1,nargs-5
+ call getarg(ifile+5,fname)
+ open(10,file=fname,status='old',access='stream')
+ read(10) h
+ nwave=min(h%ndata/2,NMAX)
+ read(10) iwave(1:nwave)
+ close(10)
+ if(ndebug.gt.0) then
+ n=len_trim(fname)
+ write(*,'(a)') fname(n-16:n)
+ endif
+ if(nwave.lt.NMAX) iwave(nwave+1:NMAX) = 0
+ ndecodes=0
+ kchar=0
+ istart=1
+ nsync=0
+ f1good = -99.
+ xdtgood = -99.
+ missed_syncs = 0
+ newsig = .false.
+
+! Process data on the fly, one buffer at a time:
+ do while (istart+nchunk-1 .le. nwave)
+ success=.false.
+ call jtty_mdecode_step(iwave,nwave,istart,1,nchunk,nsps,ndebug,nfa,nfb,f0,ftol,smin)
+ call discard_pending_updates()
+ istart=istart+nframe/4
+ enddo
+ enddo !ifile
+
+999 end program rjtty
diff --git a/lib/jtty/rjtty_sub.f90 b/lib/jtty/rjtty_sub.f90
new file mode 100644
index 00000000..333d38b4
--- /dev/null
+++ b/lib/jtty/rjtty_sub.f90
@@ -0,0 +1,102 @@
+subroutine rjtty_sub(iwave,kz,nsps,nfa,nfb,f0,ftol)
+ ! Unwindowed entry point: scans the whole buffer, exactly as before.
+ integer*2 iwave(kz)
+ call rjtty_core(iwave,kz,nsps,nfa,nfb,f0,ftol,1,kz)
+end subroutine rjtty_sub
+
+subroutine rjtty_sub_windowed(iwave,kz,nsps,nfa,nfb,f0,ftol,istart0,istop)
+ ! Bounds the scan to [istart0,istop] (sample indices into iwave) instead
+ ! of the whole buffer -- e.g. a WideGraph click-driven re-decode that only
+ ! needs a window around a known time, not a full "decode again" pass.
+ integer*2 iwave(kz)
+ integer, intent(in) :: istart0,istop
+ call rjtty_core(iwave,kz,nsps,nfa,nfb,f0,ftol,istart0,istop)
+end subroutine rjtty_sub_windowed
+
+subroutine rjtty_core(iwave,kz,nsps,nfa,nfb,f0,ftol,istart0,istop)
+
+ use jtty_mdec
+ integer*2 iwave(kz)
+ integer, intent(in) :: istart0,istop
+ data kz0/9999999/,missed_syncs/0/,istart0_save/0/
+ save istart,kz0,kchar,missed_syncs,ndtol,istart0_save
+
+ if(nsps.ne.240 .and. nsps.ne.320 .and. nsps.ne.384 .and. nsps.ne.480) return
+
+ nframe = 59*nsps
+ nchunk = nframe + nframe/4
+ smin=4.6
+
+ ! A shorter/new buffer always restarts; a windowed call whose window has
+ ! moved (a new click) also restarts, even mid-buffer, so active assemblies
+ ! are not polluted by a previous window's in-progress messages.
+ if(kz .le. kz0 .or. istart0.ne.istart0_save) then
+ kz0=kz
+ istart=istart0
+ kchar=0
+ ndtol=0
+ call reset_decode_search_state()
+ istart0_save=istart0
+ go to 999
+ endif
+ kzeff=min(kz,istop)
+ if(kzeff-istart+1 .lt. nchunk) return ! wait for enough data
+
+ nsync=0
+ do while (istart+nchunk-1 .le. kzeff)
+ ndebug=-1
+ snr=-99.0
+ call jtty_mdecode_step(iwave,kz,istart,istart0,nchunk,nsps,ndebug,nfa,nfb, &
+ f0,ftol,smin)
+ istart=istart+nframe/4
+ enddo
+
+999 return
+end subroutine rjtty_core
+
+subroutine jtty_get_updates(text_blocks,message_ids,frequencies,start_tsync,eom,count)
+
+ use iso_fortran_env, only: int64
+ use jtty_mdec
+ integer, parameter :: BATCH_SIZE = 30
+ integer, parameter :: MESSAGE_LENGTH = 80
+ character(len=BATCH_SIZE*MESSAGE_LENGTH), intent(out) :: text_blocks
+ integer(int64), intent(out) :: message_ids(BATCH_SIZE)
+ real, intent(out) :: frequencies(BATCH_SIZE)
+ real, intent(out) :: start_tsync(BATCH_SIZE)
+ logical*1, intent(out) :: eom(BATCH_SIZE)
+ integer, intent(out) :: count
+ character(len=MESSAGE_LENGTH) :: msg
+ integer :: i,index,offset
+
+ text_blocks=''
+ message_ids=0_int64
+ frequencies=0.0
+ start_tsync=0.0
+ eom=.false.
+ count=min(npending,BATCH_SIZE)
+
+ do i=1,count
+ index=pending_first+i-1
+ msg=display_message_text(pending_updates(index)%decoded)
+ offset=(i-1)*MESSAGE_LENGTH
+ text_blocks(offset+1:offset+MESSAGE_LENGTH)=msg
+ message_ids(i)=pending_updates(index)%message_id
+ frequencies(i)=pending_updates(index)%f1
+ start_tsync(i)=pending_updates(index)%start_tsync
+ eom(i)=pending_updates(index)%complete
+ enddo
+
+ ! Pending membership is the delivery guarantee; remove records only after copying them out.
+ pending_first=pending_first+count
+ npending=npending-count
+ if(npending.eq.0) then
+ pending_first=1
+ if(allocated(pending_updates)) then
+ if(size(pending_updates).gt.MAX_ACTIVE_MESSAGES) then
+ deallocate(pending_updates)
+ allocate(pending_updates(MAX_ACTIVE_MESSAGES))
+ endif
+ endif
+ endif
+end subroutine jtty_get_updates
diff --git a/lib/jtty/sjtty.f90 b/lib/jtty/sjtty.f90
new file mode 100644
index 00000000..16d4324a
--- /dev/null
+++ b/lib/jtty/sjtty.f90
@@ -0,0 +1,258 @@
+program sjtty
+
+ ! Simulate received data for JTTY, a mode operationally similar to RTTY
+ ! but providing much better performance and reliability.
+
+ ! Messages are source-encoded into 34-bit blocks. A 12-bit CRC is
+ ! added to create a 46 bit payload, which is then FEC-encoded using
+ ! a tail-biting rate-1/2 convolutional code (K=10) to create 92-bit
+ ! (46-symbol) codewords.
+
+ ! Modulation is 4FSK at 12000/NSPS = 31.25 baud. Each transmitted frame
+ ! consists of 13 sync symbols followed by 46 codeword symbols.
+
+ use wavhdr
+ use jtty_mod ! This module provides NSPS
+ use jtty_fec
+
+ parameter (MAX_TONES=59*16) !Max number of channel symbols
+ character*12 arg !Command line argument
+ character*2 arg4 !The 4th command-line argument
+ character*80 umsg !User-formatted message
+ character(len=80) :: profile_option
+ integer :: exchange_profile,arg_offset
+ character*40 fname !Output file name
+ character*34 c32(16)
+ complex, allocatable :: cwave(:) !Complex generated waveform (12000 Hz)
+ complex, allocatable :: c0(:) !With propagation degradation
+ complex, allocatable :: c(:) !With propagation degradation
+ real, allocatable :: wave(:) !Real generated waveform (12000 Hz)
+ type(hdr) h !Header for .wav file
+ integer itone(MAX_TONES) !Array of tone frequencies for this message
+ integer*2, allocatable :: iwave(:) !Data written to the *.wav file
+ integer payload(PAYLOAD_BITS)
+ integer tone_symbols(TOTAL_K)
+ logical itu_model !True if fdop, delay are from an ITU model
+
+ nargs=iargc()
+ exchange_profile=JTTY_EXCHANGE_UNKNOWN
+ arg_offset=0
+ if(nargs.gt.0) then
+ call getarg(1,profile_option)
+ if(index(profile_option,'--exchange-profile=').eq.1) then
+ select case(trim(profile_option(20:)))
+ case('unknown'); exchange_profile=JTTY_EXCHANGE_UNKNOWN
+ case('field-day'); exchange_profile=JTTY_EXCHANGE_FIELD_DAY
+ case('rtty-roundup'); exchange_profile=JTTY_EXCHANGE_RTTY
+ case default
+ print*,'Invalid exchange profile: use unknown, field-day, or rtty-roundup'
+ stop 1
+ end select
+ arg_offset=1
+ nargs=nargs-1
+ endif
+ endif
+ if(nargs.eq.1) then
+ call getarg(1+arg_offset,umsg)
+ call pack_jtty(umsg,c32,nframes,exchange_profile)
+ if(nframes.lt.0) then
+ print*,'Message exceeds JTTY encoding limits after exchange normalization'
+ stop 1
+ endif
+ call unpack_jtty(c32,nframes,umsg)
+ do while (index(umsg,'~') .ne. 0)
+ i1=index(umsg,'~')
+ umsg(i1:i1)=' '
+ enddo
+ write(*,'(a,a)') "Message after pack/unpack : ",trim(umsg)
+ nsps=384
+ if(nframes.eq.1) then
+ write(*,'(i4,a,f5.2,a)') nframes," frame, Transmission length ", &
+ 59*nframes*nsps/12000.0," seconds"
+ else
+ write(*,'(i4,a,f5.2,a)') nframes," frames, Transmission length ", &
+ 59*nframes*nsps/12000.0," seconds"
+ endif
+ go to 999
+ else if(nargs.ne.8) then
+ print*,'Usage: sjtty message'
+ print*,'Example: sjtty "CQ DX KA1ABC"'
+ print*,'or'
+ print*,'Usage: sjtty message f0 DT fdop del nsps nfiles SNR'
+ print*,'Example: sjtty "CQ K1ABC CQ" 1500 0.0 0.5 1 384 10 -10'
+ print*,'Optional first argument: --exchange-profile=unknown|field-day|rtty-roundup'
+ print*,'ITU propagation models: set fdop to AW LQ LM LD MQ MM MD HQ HM HD'
+ print*,'nsps: 240, 320, 384, or 480'
+ go to 999
+ endif
+
+ call getarg(1+arg_offset,umsg) !User message
+ call getarg(2+arg_offset,arg)
+ read(arg,*) f0 !Frequency of lowest tone
+ call getarg(3+arg_offset,arg)
+ read(arg,*) xdt !Time offset (positive only)
+ call getarg(4+arg_offset,arg)
+ itu_model=.true.
+ arg4=arg(1:2)
+ if(arg(1:2).eq.'LQ') then !ITU params for Low Latitude Quiet
+ fspread=0.5
+ delay=0.5
+ else if(arg(1:2).eq.'LM') then !Low Latitude Moderate
+ fspread=1.5
+ delay=2.0
+ else if(arg(1:2).eq.'LD') then !Low Latitude Disturbed
+ fspread=10.0
+ delay=6.0
+ else if(arg(1:2).eq.'MQ') then !Mid Latitude ... etc.
+ fspread=0.1
+ delay=0.5
+ else if(arg(1:2).eq.'MM') then
+ fspread=0.5
+ delay=1.0
+ else if(arg(1:2).eq.'MD') then
+ fspread=1.0
+ delay=2.0
+ else if(arg(1:2).eq.'HQ') then
+ fspread=0.5
+ delay=1.0
+ else if(arg(1:2).eq.'HM') then
+ fspread=10.0
+ delay=3.0
+ else if(arg(1:2).eq.'HD') then
+ fspread=30.0
+ delay=7.0
+ else if(arg(1:2).eq.'AW') then
+ fspread=0.0
+ delay=0.0
+ else
+ itu_model=.false.
+ read(arg,*) fspread !Watterson frequency spread (Hz)
+ call getarg(5+arg_offset,arg)
+ read(arg,*) delay !Watterson delay (ms)
+ endif
+ call getarg(6+arg_offset,arg)
+ read(arg,*) nsps !Number of files
+ if(nsps.ne.240 .and. nsps.ne.320 .and. nsps.ne.384 .and. nsps.ne.480) then
+ print*,'nsps: 240, 320, 384, or 480'
+ stop
+ endif
+ call getarg(7+arg_offset,arg)
+ read(arg,*) nfiles !Number of files
+ call getarg(8+arg_offset,arg)
+ read(arg,*) snrdb !SNR in 2500 Hz bandwidth
+
+ fsample=12000.0
+ dt=1.0/fsample
+ twopi=8.0*atan(1.0)
+ bandwidth_ratio=2500.0/(fsample/2.0)
+ sig=sqrt(2*bandwidth_ratio) * 10.0**(0.05*snrdb)
+ if(snrdb.gt.90.0) sig=1.0
+
+ bt=2.0 !Default bt=2 (smaller ==> more smoothing)
+ baud=fsample/nsps !Symbol rate
+ bw=4.0*baud !Signal bandwidth
+ hmod=1.0 !Modulation index
+
+ call pack_jtty(umsg,c32,nframes,exchange_profile)
+ if(nframes.lt.0) then
+ print*,'Message exceeds JTTY encoding limits after exchange normalization'
+ stop 1
+ endif
+ nsym=0
+ do i=1,nframes
+ read(c32(i),'(34i1)') payload
+ call tbcc_encode(payload,tone_symbols,JTTY_TBCC_PROFILE_1167_1545_80F)
+ ib=(i-1)*59+1 ! 59 tones per frame
+ itone(ib:ib+12)=is13
+ itone(ib+13:ib+58)=tone_symbols
+ nsym=nsym+59
+ enddo
+
+ txt=nsym*nsps*dt !Transmission length (s)
+ numsg=len(trim(umsg))
+ write(*,1012) trim(umsg)
+1012 format('User message: ',a)
+ write(*,1013) nsps,txt,nsym,itone(1:nsym)
+1013 format('nsps:',i5,' samples/symbol ','Transmission length:',f5.1, &
+ ' s,',i5,' channel symbols:'/ &
+ (30i2))
+
+ nwave=nsps*nsym !Length of i*2 data written to *.wav file
+ npts=2**(int(log(float(nwave)+xdt/dt)/log(2.0) + 0.9999)) !Round up to integer power of 2
+ iz=nint(xdt/dt) + nwave + nsps*59 !Add one frame of noise at end
+ nbuf=max(nwave,npts,iz)
+
+ allocate(cwave(0:nwave-1))
+ allocate(c0(0:nbuf-1))
+ allocate(c(0:nbuf-1))
+ allocate(wave(1:nbuf))
+ allocate(iwave(1:nbuf))
+
+ icmplx=1
+ call gen_jttywave(itone,nsym,nsps,bt,fsample,f0,cwave,wave,icmplx,nwave)
+
+
+ write(*,1000) f0,xdt,txt,snrdb,bw
+1000 format('f0:',f7.1,' DT:',f6.2,' TxT:',f6.1,' SNR:',f6.1,' BW:',f6.1)
+ cps=baud/7.0
+ cps_effective=numsg/txt
+ write(*,1001) cps,cps_effective
+1001 format('Raw character rate:',f5.1,' c/s Effective character rate:',f5.1,' c/s')
+ write(*,1002) fspread,delay
+1002 format('Fspread:',f5.1,' Hz Delay:',f5.1,' ms')
+ if(itu_model) write(*,1003) arg4
+1003 format('ITU propagation model: ',a2)
+ write(*,*)
+
+! call sgran()
+
+ do ifile=1,nfiles
+ c0=0.
+ c0(0:nwave-1)=cwave(0:nwave-1)
+ c0=cshift(c0,-nint(xdt/dt))
+ if(fspread.ne.0.0 .or. delay.ne.0.0) then
+ ! Apply channel propagation
+ call watterson(c0,npts,nwave,fsample,delay,fspread)
+ endif
+ c=0.
+ c=sig*c0 !Scale to specified SNR
+ wave=0.
+ wave=imag(c) !Signal with SNR and prop degradation
+
+ if(snrdb.lt.90) then
+ do i=1,iz !Add gaussian noise for specified SNR
+ xnoise=gran()
+ wave(i)=wave(i) + xnoise
+ enddo
+ endif
+
+ gain=100.0
+ if(snrdb.lt.90.0) then
+ wave(1:iz)=gain*wave(1:iz)
+ else
+ datpk=maxval(abs(wave(1:iz)))
+ fac=32766.9/datpk
+ wave(1:iz)=fac*wave(1:iz)
+ endif
+
+ iwave(1:iz)=nint(wave(1:iz))
+! call jtty_spec(iwave,iz)
+ h=default_header(12000,iz)
+ write(fname,1102) ifile
+1102 format('000000_',i6.6,'.wav')
+ open(10,file=fname,status='replace',access='stream')
+ write(10) h,iwave(1:iz) !Save to *.wav file
+ close(10)
+ write(*,1110) ifile,xdt,f0,snrdb,fname
+1110 format(i4,f7.2,f8.2,f7.1,2x,a17)
+ enddo
+
+999 if (allocated(cwave)) deallocate(cwave)
+ if (allocated(c0)) deallocate(c0)
+ if (allocated(c)) deallocate(c)
+ if (allocated(wave)) deallocate(wave)
+ if (allocated(iwave)) deallocate(iwave)
+
+end program sjtty
+
+!include 'jtty_spec.f90'
diff --git a/lib/jtty/sjtty_qrm.f90 b/lib/jtty/sjtty_qrm.f90
new file mode 100644
index 00000000..d4038b0b
--- /dev/null
+++ b/lib/jtty/sjtty_qrm.f90
@@ -0,0 +1,238 @@
+program sjtty_qrm
+
+ ! Simulate received data for JTTY, a mode operationally similar to RTTY
+ ! but providing much better performance and reliability.
+
+ ! Messages are source-encoded into 34-bit blocks. A 12-bit CRC is
+ ! added to create a 46 bit payload, which is then FEC-encoded using
+ ! a tail-biting rate-1/2 convolutional code (K=10) to create 92-bit
+ ! (46-symbol) codewords.
+
+ ! Modulation is 4FSK at 12000/NSPS = 31.25 baud. Each transmitted frame
+ ! consists of 13 sync symbols followed by 46 codeword symbols.
+
+ ! This version generates multiple signals spread across nfa to nfb Hz.
+ ! One signal falls at f0 = 1500 Hz and has the message "599 123" (or, if
+ ! an 8th command-line argument is given, that text instead -- a longer,
+ ! multi-frame message there is useful for exercising continuation-frame
+ ! logic, e.g. the sticky-sync retry, that a single-frame message never
+ ! reaches). Others are spread in frequency and DT, and contain just a
+ ! callsign.
+
+ use wavhdr
+ use jtty_mod
+ use jtty_fec
+
+ parameter (NMAX=131072) !Max size of .wav file
+ parameter (MAX_TONES=59*16) !Max number of channel symbols
+ parameter (MAX_SIGS=20) !Max number of signals
+ character*12 arg !Command line argument
+ character*2 arg4 !The 4th command-line argument
+ character*80 umsg !User-formatted message
+ character*80 msg_override !Optional 8th-arg override for f0=1500 signal
+ character*17 fname !Output file name,
+ character*10 flags !Single-character shorthand flags
+ character*34 c32(16)
+ character*6 xcall(25)
+ complex cwave(0:NMAX-1) !Complex generated waveform (12000 Hz)
+ complex c0(0:NMAX-1) !With propagation degradation
+ complex cdat(0:NMAX-1)
+ real wave (NMAX) !Real generated waveform (12000 Hz)
+ real xnoise(NMAX)
+ type(hdr) h !Header for .wav file
+ integer itone(MAX_TONES) !Array of tone frequencies for this message
+ integer*2 iwave(NMAX) !Data written to the *.wav file
+ integer payload(PAYLOAD_BITS)
+ integer tone_symbols(TOTAL_K)
+ data flags/'!@#$%^&*()'/
+ data idum/-1/
+
+ ! Some arbitrary callsigns:
+ data xcall/'AC9QI ','CF7GEM','EA1AAE','GI4FUE','IU8CNE','K2AK ', &
+ 'K5CIA ','K7CAH ','KA9KQH','KE0N ','KM2J ','KP4SX ', &
+ 'LV7QFH','N2PPI ','N6GP ','N8HMG ','NV8B ','PA2GP ', &
+ 'PY7BC ','W0OGH ','W4EIS ','W6RYO ','W8OI ','WA2HIP', &
+ 'WB2KSP'/
+
+ nargs=iargc()
+ if(nargs.ne.7 .and. nargs.ne.8) then
+ print*,'Usage: sjtty_qrm nsps prop nfa nfb nsigs nfiles snr [message]'
+ print*,'Example: sjtty_qrm 384 MM 1200 1800 5 10 -5'
+ print*,'Example: sjtty_qrm 384 MM 1200 1800 5 10 -5 ', &
+ '"LET''S ASK BRIAN WHAT HE THINKS"'
+ print*,'NSPS must be 240, 320, 384, or 480'
+ print*,'ITU propagation models: AW LQ LM LD MQ MM MD HQ HM HD'
+ print*,'Main signal at f0 = 1500 Hz and specified SNR, message'
+ print*,'"599 123" unless the optional 8th argument overrides it --'
+ print*,'quote it if it contains spaces. A message long enough to'
+ print*,'need more than one frame exercises continuation-frame'
+ print*,'decoder logic that "599 123" alone never reaches; frames'
+ print*,'beyond what the fixed-size output buffer can hold at this'
+ print*,'signal''s randomly-drawn DT are silently dropped (matches a'
+ print*,'transmission truncated by a WAV-file boundary), with a'
+ print*,'warning printed when that happens.'
+ print*,'Off-freq signals at random freqs in range nfa to nfb Hz.'
+ print*,'Off-freq SNRs randomized by +/- 5 dB around specified value'
+ print*,'DT values random in range 0.1 to 1.0 s.'
+ go to 999
+ endif
+
+ call getarg(1,arg)
+ read(arg,*) nsps
+ call getarg(2,arg)
+ arg4=arg(1:2)
+ if(arg(1:2).eq.'LQ') then !ITU params for Low Latitude Quiet
+ fspread=0.5
+ delay=0.5
+ else if(arg(1:2).eq.'LM') then !Low Latitude Moderate
+ fspread=1.5
+ delay=2.0
+ else if(arg(1:2).eq.'LD') then !Low Latitude Disturbed
+ fspread=10.0
+ delay=6.0
+ else if(arg(1:2).eq.'MQ') then !Mid Latitude ... etc.
+ fspread=0.1
+ delay=0.5
+ else if(arg(1:2).eq.'MM') then
+ fspread=0.5
+ delay=1.0
+ else if(arg(1:2).eq.'MD') then
+ fspread=1.0
+ delay=2.0
+ else if(arg(1:2).eq.'HQ') then
+ fspread=0.5
+ delay=1.0
+ else if(arg(1:2).eq.'HM') then
+ fspread=10.0
+ delay=3.0
+ else if(arg(1:2).eq.'HD') then
+ fspread=30.0
+ delay=7.0
+ else if(arg(1:2).eq.'AW') then
+ fspread=0.0
+ delay=0.0
+ endif
+ call getarg(3,arg)
+ read(arg,*) nfa
+ call getarg(4,arg)
+ read(arg,*) nfb
+ call getarg(5,arg)
+ read(arg,*) nsigs
+ call getarg(6,arg)
+ read(arg,*) nfiles
+ call getarg(7,arg)
+ read(arg,*) snrdb
+ if(nfa.lt.0 .or. nfb.lt.0) then
+ print*,'Frequency range endpoints must be nonnegative.'
+ stop 1
+ endif
+ msg_override=' '
+ if(nargs.eq.8) call getarg(8,msg_override)
+
+ fsample=12000.0
+ dt=1.0/fsample
+ twopi=8.0*atan(1.0)
+ bandwidth_ratio=2500.0/(fsample/2.0)
+ if(snrdb.gt.90.0) sig=1.0
+ bt=2.0 !Default bt=2 (smaller ==> more smoothing)
+ baud=fsample/nsps !Symbol rate
+ bw=4.0*baud !Signal bandwidth
+ hmod=1.0 !Modulation index
+
+ npts=131072
+ do ifile=1,nfiles
+ write(fname,1002) ifile !Output filename
+1002 format('000000_',i6.6,'.wav')
+ open(10,file=fname,access='stream',status='replace')
+ write(*,1004) ifile,fname
+1004 format(i3,2x,a17)
+ xnoise=0.
+ if(snrdb.lt.90) then
+ do i=1,NMAX
+ xnoise(i)=gran() !Generate gaussian noise, rms=1.0
+ enddo
+ endif
+ cdat=0.
+ i0=25.0*ran1(idum)
+
+ do isig=1,nsigs
+ f0=nfa + (nfb-nfa)*ran1(idum)
+ xdt=0.1 + 3.9*ran1(idum)
+ snr=snrdb + 10.0*(ran1(idum)-0.5)
+ i0=i0+1
+ if(i0.gt.25) i0=1
+ umsg=xcall(i0)
+ if(isig.eq.1) then
+ f0=1500.0
+ snr=snrdb
+ umsg='599 123'
+ if(len_trim(msg_override).gt.0) umsg=msg_override
+ endif
+ sig=sqrt(2*bandwidth_ratio) * 10.0**(0.05*snr)
+ write(*,1006) isig,f0,xdt,snr,sig,trim(umsg)
+1006 format(i4,f8.1,f8.3,f7.1,f10.3,2x,a)
+
+ i1=nint(xdt/dt)
+ call pack_jtty(umsg,c32,nframes)
+ ! itone/cwave/c0 are all fixed at NMAX -- gen_jttywave trusts its
+ ! caller's nwave completely, with no bounds checking of its own,
+ ! so a long enough message combined with this signal's own
+ ! (randomly drawn) start offset i1 could otherwise write past the
+ ! end of those arrays. Clamp to however many frames actually fit
+ ! before building itone, rather than risk that: this can only
+ ! happen with a message overriding the default "599 123" (that
+ ! one frame always fits), so it's silent for existing callers.
+ nframes_fit=max(0,(NMAX-i1)/(nsps*59))
+ if(nframes.gt.nframes_fit) then
+ write(*,1007) nframes,nframes_fit
+1007 format(' WARNING: message needs ',i2,' frames but only ', &
+ i2,' fit in the output buffer at this DT -- truncating')
+ nframes=nframes_fit
+ endif
+ if(nframes.lt.1) then
+ print*,' WARNING: no room for this signal at this DT -- skipping'
+ cycle
+ endif
+ nsym=0
+ do i=1,nframes
+ read(c32(i),'(34i1)') payload
+ call tbcc_encode(payload,tone_symbols,JTTY_TBCC_PROFILE_1167_1545_80F)
+ ib=(i-1)*59+1 ! 59 tones per frame
+ itone(ib:ib+12)=is13
+ itone(ib+13:ib+58)=tone_symbols
+ nsym=nsym+59
+ enddo
+ nwave=nsps*nsym
+ icmplx=1
+ call gen_jttywave(itone,nsym,nsps,bt,fsample,f0,cwave,wave,icmplx,nwave)
+ c0=0.
+ c0(i1:nwave+i1-1)=cwave(0:nwave-1)!
+ if(fspread.ne.0.0 .or. delay.ne.0.0) then
+ ! Apply channel propagation
+ call watterson(c0,npts,nwave,fsample,delay,fspread)
+ endif
+ cdat=cdat + sig*c0
+ enddo ! isig
+
+ c0=cdat
+ wave=0.
+ wave=aimag(c0) !Signal with SNR and prop degradation
+ iz=10*12000
+ if(snrdb.lt.90) wave = wave + xnoise
+
+ gain=100.0
+ if(snrdb.lt.90.0) then
+ wave(1:iz)=gain*wave(1:iz)
+ else
+ datpk=maxval(abs(wave(1:iz)))
+ fac=32766.9/datpk
+ wave(1:iz)=fac*wave(1:iz)
+ endif
+
+ iwave(1:iz)=nint(wave(1:iz))
+ h=default_header(12000,iz)
+ write(10) h,iwave(1:iz) !Save to *.wav file
+ close(10)
+ enddo
+
+999 end program sjtty_qrm
diff --git a/lib/jtty/subtract_jtty.f90 b/lib/jtty/subtract_jtty.f90
new file mode 100644
index 00000000..eeb062a0
--- /dev/null
+++ b/lib/jtty/subtract_jtty.f90
@@ -0,0 +1,99 @@
+subroutine subtract_jtty(c0, n, nvalid, tone_symbols, nsym_total, nss, f1, xdt)
+
+! Subtract a decoded JTTY signal from the complex analytic buffer c0 (at
+! 6000 Sa/s -- the domain jtty_mdecode.f90 already works in, produced from
+! the raw audio by ana64a), so a second, weaker signal at a different
+! time/frequency can be recovered in a follow-up decode pass over the
+! residual. Modeled on lib/ft8/subtractft8.f90: build a unit-amplitude
+! reference waveform for the already re-encoded (error-corrected) tone
+! sequence, estimate its actual complex (amplitude+phase) channel gain via
+! a matched-filter/low-pass correlation against c0, then subtract.
+!
+! Measured signal : c0(t) = a(t) * cref(t) + noise
+! Reference signal : cref(t) = exp( j*(2*pi*f1*t+phi(t)) ), unit amplitude
+! Complex gain : cfilt(t) = LPF[ c0(t) * CONJG(cref(t)) ]
+! Subtract : c0(t) = c0(t) - cref(t) * cfilt(t)
+!
+! Unlike subtractft8 (a real-valued passband buffer, hence its factor-of-2
+! real-part subtraction to reconstruct a real signal from an analytic
+! estimate), c0 here is already complex analytic, so the full complex
+! estimate is subtracted directly with no real-part/factor-of-2 step.
+!
+! Input: complex c0(0:n-1) In/out: buffer to subtract from
+! integer n Size of c0 (must be a power of 2)
+! integer nvalid Number of valid samples in c0 (<=n)
+! integer tone_symbols(nsym_total) Full frame: sync + info tones
+! integer nsym_total Total symbols/frame (sync+info)
+! integer nss Samples per symbol at 6000 Sa/s
+! real f1 Signal's estimated audio frequency, Hz
+! real xdt Signal's estimated DT (start time), s
+
+ implicit none
+ integer, intent(in) :: n, nvalid, nsym_total, nss
+ complex, intent(inout) :: c0(0:n-1)
+ integer, intent(in) :: tone_symbols(nsym_total)
+ real, intent(in) :: f1, xdt
+
+ real, parameter :: FSAMPLE6 = 6000.0
+ integer, save :: nframe_save=-1, nfft_save=-1
+ complex, allocatable, save :: cref(:), camp(:), cfilt(:), cw(:)
+ real, allocatable, save :: window(:)
+ integer :: nframe, nfft, nfilt, i, j, nstart
+ real :: pi, fac, sumw, xjunk(1)
+ complex :: z
+
+ nframe=nsym_total*nss
+ nfft=n
+ ! ~2 symbol periods, matching subtractft8's NFILT (4000 samples @ 12000
+ ! Sa/s = 333 ms) being ~2 FT8 symbol periods (160 ms each) -- smooths the
+ ! channel-gain estimate enough to track slow fading without blurring out
+ ! genuine amplitude structure within the frame.
+ nfilt=2*nss
+
+ if(nframe.ne.nframe_save .or. nfft.ne.nfft_save) then
+ if(allocated(cref)) deallocate(cref,camp,cfilt,cw,window)
+ allocate(cref(nframe), camp(nfft), cfilt(nfft), cw(nfft))
+ allocate(window(-nfilt/2:nfilt/2))
+ pi=4.0*atan(1.0)
+ fac=1.0/float(nfft)
+ sumw=0.0
+ do j=-nfilt/2,nfilt/2
+ window(j)=cos(pi*j/nfilt)**2
+ sumw=sumw+window(j)
+ enddo
+ cw=0.
+ cw(1:nfilt+1)=window/sumw
+ cw=cshift(cw,nfilt/2+1)
+ call four2a(cw,nfft,1,-1,1)
+ cw=cw*fac
+ nframe_save=nframe
+ nfft_save=nfft
+ endif
+
+! Generate a unit-amplitude complex reference waveform for the full frame
+! (sync + info tones), at this signal's own estimated frequency.
+ call gen_jttywave(tone_symbols, nsym_total, nss, 2.0, FSAMPLE6, f1, &
+ cref, xjunk, 1, nframe)
+
+ nstart=nint(xdt*FSAMPLE6) ! 0-based c0 index of the frame's first sample
+ camp=(0.,0.)
+ do i=1,nframe
+ j=nstart+i-1
+ if(j.ge.0 .and. j.lt.nvalid) camp(i)=c0(j)*conjg(cref(i))
+ enddo
+
+ cfilt=camp
+ call four2a(cfilt,nfft,1,-1,1) ! forward FFT
+ cfilt=cfilt*cw ! apply the low-pass filter
+ call four2a(cfilt,nfft,1,1,1) ! inverse FFT -> smoothed complex gain
+
+ do i=1,nframe
+ j=nstart+i-1
+ if(j.ge.0 .and. j.lt.nvalid) then
+ z=cfilt(i)*cref(i)
+ c0(j)=c0(j)-z !Subtract the reconstructed signal
+ endif
+ enddo
+
+ return
+end subroutine subtract_jtty
diff --git a/lib/jtty/tbcc.f90 b/lib/jtty/tbcc.f90
new file mode 100644
index 00000000..c3a89c0c
--- /dev/null
+++ b/lib/jtty/tbcc.f90
@@ -0,0 +1,422 @@
+module tbcc
+ ! Tail-biting rate-1/2 convolutional code: encode, WAVA/list decode,
+ ! CRC-12 append/check, and generator-polynomial selection. Used by JTTY
+ ! mode (lib/jtty/jtty_fec_mod.f90 and callers) and by the standalone
+ ! research tools under lib/jtty/wava/.
+ use, intrinsic :: iso_fortran_env, only: real32, int32, int16
+ use jtty_tbcc_code_profiles, only: jtty_tbcc_code_profile, &
+ jtty_tbcc_code_profile_is_supported, &
+ PROFILE_PAYLOAD_BITS => JTTY_TBCC_PAYLOAD_BITS, &
+ PROFILE_OUTER_CHECK_BITS => JTTY_TBCC_OUTER_CHECK_BITS, &
+ PROFILE_INFORMATION_BITS => JTTY_TBCC_INFORMATION_BITS
+ !$ use omp_lib
+ implicit none
+
+ ! Fixed frame parameters, shared with every caller.
+ integer(int32), parameter :: PAYLOAD_BITS = PROFILE_PAYLOAD_BITS
+ integer(int32), parameter :: CRC_BITS = PROFILE_OUTER_CHECK_BITS
+ integer(int32), parameter :: TOTAL_K = PROFILE_INFORMATION_BITS
+ integer(int32), parameter :: TBCC_OUTER_POLYNOMIAL_80F = int(Z"80F", int32)
+
+ ! Standalone simulation tools retain runtime nu selection through tbcc_init.
+ ! JTTY production callers pass a complete selected profile instead.
+ integer(int32) :: memory_nu, num_states, g0_poly, g1_poly, reg_mask
+
+ integer(int32), allocatable, protected :: incoming_tones(:,:)
+
+ type candidate_t
+ real(real32) :: metric
+ integer(int32) :: bits(TOTAL_K)
+ end type candidate_t
+
+ ! Per-thread RNG state (xorshift32), used only by the channel-simulation
+ ! helpers below (box_muller/generate_random_bits/seed_random_generator).
+ ! tbcc_encode/tbcc_wava_fsk_decode/encode_crc12 never touch it -- a
+ ! production caller that never runs the simulator helpers pays nothing
+ ! for this. The RANDOM_NUMBER intrinsic keeps a single shared generator
+ ! state and is not safe to call concurrently from multiple OpenMP
+ ! threads, so each thread gets its own independent stream instead.
+ ! Threadprivate module variables retain that property for every program
+ ! unit that USEs this module.
+ integer(int32), save :: rng_state = 0
+ !$omp threadprivate(rng_state)
+
+contains
+
+ subroutine tbcc_init(nu)
+ ! Sets memory_nu, num_states, g0_poly, g1_poly, and reg_mask for the
+ ! chosen constraint length K = nu+1. Call once, before any
+ ! encode/decode.
+ integer(int32), intent(in) :: nu
+ memory_nu = nu
+ num_states = 2**nu
+ call select_generator_polynomials(nu, g0_poly, g1_poly)
+ reg_mask = 2**(nu + 1) - 1
+ if (allocated(incoming_tones)) deallocate(incoming_tones)
+ allocate(incoming_tones(0:1, 0:num_states-1))
+ call build_incoming_tones(memory_nu, num_states, g0_poly, g1_poly, incoming_tones)
+ end subroutine tbcc_init
+
+ subroutine tbcc_encode(payload, tone_symbols, code_profile, encoded_bits)
+ ! Encodes a PAYLOAD_BITS-bit payload into a TOTAL_K-symbol 4-FSK
+ ! tone sequence: CRC-12 append, then tail-biting rate-1/2
+ ! convolutional encode with a Gray-coded 2-bit-per-symbol tone
+ ! mapping (00/01/11/10 -> 0/1/2/3). A caller that omits code_profile
+ ! must first initialize the standalone simulation code with tbcc_init().
+ integer(int32), intent(in) :: payload(PAYLOAD_BITS)
+ integer(int32), intent(out) :: tone_symbols(TOTAL_K)
+ type(jtty_tbcc_code_profile), intent(in), optional :: code_profile
+ integer(int32), intent(out), optional :: encoded_bits(2, TOTAL_K)
+ integer(int32) :: info_bits(2, TOTAL_K)
+ integer(int32) :: state, t, bit, g0_out, out_b0, out_b1
+ integer(int32) :: selected_nu, selected_state_count, selected_g0, selected_g1
+ integer(int32) :: selected_register_mask, outer_polynomial, outer_check_bits
+ integer(int32) :: outer_top_bit_mask, outer_register_mask
+
+ call resolve_code_definition(code_profile, selected_nu, selected_state_count, &
+ selected_g0, selected_g1, selected_register_mask, outer_polynomial, &
+ outer_check_bits, outer_top_bit_mask, outer_register_mask)
+ call encode_crc12(payload, info_bits, code_profile)
+
+ ! Tail-biting initialization: preload the shift register with the
+ ! message's own last nu bits, so the encoder's starting
+ ! state equals what it would be after wrapping around the circular
+ ! frame.
+ state = 0
+ do t = 0, selected_nu - 1
+ bit = info_bits(1, TOTAL_K - (selected_nu - 1) + t)
+ state = iand(ior(ishft(state, 1), bit), selected_state_count-1)
+ end do
+
+ do t = 1, TOTAL_K
+ bit = info_bits(1, t)
+ g0_out = iand(ior(ishft(state, 1), bit), selected_register_mask)
+ out_b0 = parity_bit(iand(g0_out, selected_g0))
+ out_b1 = parity_bit(iand(g0_out, selected_g1))
+ state = iand(ior(ishft(state, 1), bit), selected_state_count-1)
+ if (present(encoded_bits)) encoded_bits(:, t) = [out_b0, out_b1]
+
+ if (out_b0 == 0 .and. out_b1 == 0) tone_symbols(t) = 0
+ if (out_b0 == 0 .and. out_b1 == 1) tone_symbols(t) = 1
+ if (out_b0 == 1 .and. out_b1 == 1) tone_symbols(t) = 2
+ if (out_b0 == 1 .and. out_b1 == 0) tone_symbols(t) = 3
+ end do
+ end subroutine tbcc_encode
+
+ subroutine tbcc_wava_fsk_decode(tone_energies, list_size, max_wava_iters, &
+ final_payload, success, reserved_zero_bit, code_profile)
+ real(real32), intent(in) :: tone_energies(0:3, TOTAL_K)
+ integer(int32), intent(in) :: list_size
+ integer(int32), intent(in) :: max_wava_iters
+ integer(int32), intent(out) :: final_payload(PAYLOAD_BITS)
+ logical, intent(out) :: success
+ ! Failed decodes return an all-zero payload; success determines validity.
+ ! Optional 1-based position (within PAYLOAD_BITS) of a payload bit
+ ! that the caller guarantees is always transmitted as 0. When
+ ! present, a list candidate is only accepted if it also satisfies
+ ! this in addition to CRC==0, rather than accepting the first
+ ! CRC-clean candidate regardless -- roughly halves the undetected-
+ ! error rate, since a wrong candidate must now also hit this bit by
+ ! chance. Absent (the default) reproduces the original CRC-only
+ ! behavior exactly.
+ integer(int32), intent(in), optional :: reserved_zero_bit
+ type(jtty_tbcc_code_profile), intent(in), optional :: code_profile
+
+ real(real32), allocatable :: prev_m(:), curr_m(:)
+ integer(int16), allocatable :: traceback_table(:,:)
+ type(candidate_t), allocatable :: sorted_list(:)
+ integer(int32) :: iter, t, s, bit_in, prev_s, curr_s, l, crc_reg, i
+ integer(int32), allocatable :: profile_tones(:,:)
+ integer(int32) :: selected_nu, selected_state_count, selected_g0, selected_g1
+ integer(int32) :: selected_register_mask, outer_polynomial, outer_check_bits
+ integer(int32) :: outer_top_bit_mask, outer_register_mask
+ real(real32) :: m0, m1
+ integer(int32) :: tmp_bits(TOTAL_K)
+
+ final_payload = 0_int32
+ success = .false.
+ call resolve_code_definition(code_profile, selected_nu, selected_state_count, &
+ selected_g0, selected_g1, selected_register_mask, outer_polynomial, &
+ outer_check_bits, outer_top_bit_mask, outer_register_mask)
+ ! Zero iterations means the WAVA loop below never runs, leaving
+ ! curr_m/traceback_table unread-by-design -- but the traceback and
+ ! list-selection code after the loop unconditionally reads them
+ ! regardless. Bail out before allocating rather than let that read
+ ! uninitialized memory (production always passes max_wava_iters=2;
+ ! only reachable via the CLI simulator's --iters option, which
+ ! accepts any caller-supplied value; found by David Christle, PR
+ ! #337, who confirmed it otherwise returns success=.true. with an
+ ! all-zero payload).
+ if (max_wava_iters < 1) return
+ allocate(prev_m(0:selected_state_count-1), curr_m(0:selected_state_count-1))
+ allocate(traceback_table(0:selected_state_count-1, TOTAL_K), sorted_list(list_size))
+
+ allocate(profile_tones(0:1,0:selected_state_count-1))
+ if (present(code_profile)) then
+ call build_incoming_tones(selected_nu, selected_state_count, &
+ selected_g0, selected_g1, profile_tones)
+ else
+ profile_tones = incoming_tones
+ end if
+ prev_m = 0.0_real32
+
+ do l = 1, list_size
+ sorted_list(l)%metric = -1.0e30_real32
+ end do
+
+ ! Forward Trellis WAVA loop
+ do iter = 1, max_wava_iters
+ do t = 1, TOTAL_K
+ curr_m = -1.0e30_real32
+ do s = 0, selected_state_count-1
+ ! For a destination state 's' at time 't' under a left-shift model,
+ ! the two possible predecessor states at time 't-1' are determined
+ ! by shifting 's' right and checking both options for the bit that
+ ! left the window.
+ prev_s = iand(ishft(s, -1), selected_state_count-1)
+
+ m0 = prev_m(prev_s) + tone_energies(profile_tones(0, s), t)
+ prev_s = ior(prev_s, ishft(1, selected_nu-1))
+ m1 = prev_m(prev_s) + tone_energies(profile_tones(1, s), t)
+
+ ! Select and record maximum likelihood trajectory decision
+ if (m0 > m1) then
+ curr_m(s) = m0
+ ! Picked path from state with dropped bit 0
+ traceback_table(s, t) = 0_int16
+ else
+ curr_m(s) = m1
+ ! Picked path from state with dropped bit 1
+ traceback_table(s, t) = 1_int16
+ end if
+ end do
+ prev_m = curr_m
+ end do
+ end do
+
+ ! REVISED TRACEBACK ALIGNMENT
+ do s = 0, selected_state_count-1
+ curr_s = s
+ do t = TOTAL_K, 1, -1
+ ! The input bit that caused the transition into 'curr_s' is its LSB (bit 0)
+ bit_in = iand(curr_s, 1)
+ tmp_bits(t) = bit_in
+
+ ! Recover the parent state index using the recorded history bit flag
+ prev_s = iand(ishft(curr_s, -1), selected_state_count-1)
+ if (traceback_table(curr_s, t) == 1_int16) then
+ prev_s = ior(prev_s, ishft(1, selected_nu-1))
+ end if
+ curr_s = prev_s
+ end do
+
+ ! Check if circular tail-biting constraint condition holds valid
+ if (curr_s == s) then
+ do l = 1, list_size
+ if (curr_m(s) > sorted_list(l)%metric) then
+ do i = list_size, l+1, -1
+ sorted_list(i) = sorted_list(i-1)
+ end do
+ sorted_list(l)%metric = curr_m(s)
+ sorted_list(l)%bits = tmp_bits
+ exit
+ end if
+ end do
+ end if
+ end do
+
+ ! Serial CRC (and, if requested, reserved-bit) filtering pass
+ do l = 1, list_size
+ if (sorted_list(l)%metric <= -1.0e29_real32) cycle
+ if (present(reserved_zero_bit)) then
+ if (sorted_list(l)%bits(reserved_zero_bit) /= 0) cycle
+ end if
+ crc_reg = 0
+ do i = 1, TOTAL_K
+ crc_reg = ieor(crc_reg, ishft(sorted_list(l)%bits(i), &
+ outer_check_bits - 1))
+ if (iand(crc_reg, outer_top_bit_mask) /= 0) then
+ crc_reg = ieor(ishft(crc_reg, 1), outer_polynomial)
+ else
+ crc_reg = ishft(crc_reg, 1)
+ end if
+ crc_reg = iand(crc_reg, outer_register_mask)
+ end do
+
+ if (crc_reg == 0) then
+ final_payload = sorted_list(l)%bits(1:PAYLOAD_BITS)
+ success = .true.
+ exit
+ end if
+ end do
+
+ deallocate(prev_m, curr_m, traceback_table, sorted_list)
+ end subroutine tbcc_wava_fsk_decode
+
+ subroutine encode_crc12(payload, out_buf, code_profile)
+ integer(int32), intent(in) :: payload(PAYLOAD_BITS)
+ integer(int32), intent(out) :: out_buf(2, TOTAL_K)
+ type(jtty_tbcc_code_profile), intent(in), optional :: code_profile
+ integer(int32) :: crc_reg, i
+ integer(int32) :: selected_nu, selected_state_count, selected_g0, selected_g1
+ integer(int32) :: selected_register_mask, outer_polynomial, outer_check_bits
+ integer(int32) :: outer_top_bit_mask, outer_register_mask
+
+ call resolve_code_definition(code_profile, selected_nu, selected_state_count, &
+ selected_g0, selected_g1, selected_register_mask, outer_polynomial, &
+ outer_check_bits, outer_top_bit_mask, outer_register_mask)
+ out_buf(1, 1:PAYLOAD_BITS) = payload
+ crc_reg = 0
+ do i = 1, PAYLOAD_BITS
+ crc_reg = ieor(crc_reg, ishft(payload(i), outer_check_bits - 1))
+ if (iand(crc_reg, outer_top_bit_mask) /= 0) then
+ crc_reg = ieor(ishft(crc_reg, 1), outer_polynomial)
+ else
+ crc_reg = ishft(crc_reg, 1)
+ end if
+ crc_reg = iand(crc_reg, outer_register_mask)
+ end do
+ do i = 1, outer_check_bits
+ out_buf(1, PAYLOAD_BITS + i) = &
+ iand(ishft(crc_reg, -(outer_check_bits - i)), 1)
+ end do
+ end subroutine encode_crc12
+
+ subroutine resolve_code_definition(code_profile, selected_nu, selected_state_count, &
+ selected_g0, selected_g1, selected_register_mask, outer_polynomial, &
+ outer_check_bits, outer_top_bit_mask, outer_register_mask)
+ type(jtty_tbcc_code_profile), intent(in), optional :: code_profile
+ integer(int32), intent(out) :: selected_nu, selected_state_count
+ integer(int32), intent(out) :: selected_g0, selected_g1, selected_register_mask
+ integer(int32), intent(out) :: outer_polynomial, outer_check_bits
+ integer(int32), intent(out) :: outer_top_bit_mask, outer_register_mask
+
+ if (present(code_profile)) then
+ if (.not.jtty_tbcc_code_profile_is_supported(code_profile)) &
+ error stop 'unsupported JTTY TBCC code profile'
+ selected_nu = code_profile%memory_nu
+ selected_state_count = code_profile%state_count
+ selected_g0 = code_profile%generator_0
+ selected_g1 = code_profile%generator_1
+ selected_register_mask = code_profile%register_mask
+ outer_polynomial = code_profile%outer_polynomial
+ outer_check_bits = code_profile%outer_check_bits
+ outer_top_bit_mask = code_profile%outer_top_bit_mask
+ outer_register_mask = code_profile%outer_register_mask
+ else
+ selected_nu = memory_nu
+ selected_state_count = num_states
+ selected_g0 = g0_poly
+ selected_g1 = g1_poly
+ selected_register_mask = reg_mask
+ outer_polynomial = TBCC_OUTER_POLYNOMIAL_80F
+ outer_check_bits = CRC_BITS
+ outer_top_bit_mask = shiftl(1_int32, CRC_BITS - 1_int32)
+ outer_register_mask = shiftl(1_int32, CRC_BITS) - 1_int32
+ end if
+ end subroutine resolve_code_definition
+
+ subroutine build_incoming_tones(nu, state_count, g0, g1, tones)
+ integer(int32), intent(in) :: nu, state_count, g0, g1
+ integer(int32), intent(out) :: tones(0:1,0:state_count-1)
+ integer(int32) :: state, dropped_bit, register_value, b0, b1
+ integer(int32), parameter :: gray_tones(0:3) = [0, 1, 3, 2]
+
+ do state = 0, state_count-1
+ do dropped_bit = 0, 1
+ register_value = ior(state, ishft(dropped_bit, nu))
+ b0 = parity_bit(iand(register_value, g0))
+ b1 = parity_bit(iand(register_value, g1))
+ tones(dropped_bit, state) = gray_tones(2*b0+b1)
+ end do
+ end do
+ end subroutine build_incoming_tones
+
+ subroutine box_muller(rand_normal)
+ real(real32), intent(out) :: rand_normal
+ real(real32) :: u1, u2
+ u1 = thread_uniform(); u2 = thread_uniform()
+ if (u1 < 1.0e-30_real32) u1 = 1.0e-30_real32
+ rand_normal = sqrt(-2.0_real32 * log(u1)) * cos(6.28318530718_real32 * u2)
+ end subroutine box_muller
+
+ subroutine generate_random_bits(vec, n)
+ integer(int32), intent(out) :: vec(n)
+ integer(int32) :: n, i
+ do i = 1, n
+ vec(i) = merge(1, 0, thread_uniform() >= 0.5_real32)
+ end do
+ end subroutine generate_random_bits
+
+ function thread_uniform() result(u)
+ ! Fast per-thread xorshift32 generator returning a uniform value on
+ ! [0,1]. rng_state is !$omp threadprivate, so this advances each
+ ! thread's own independent stream with no shared mutable state and
+ ! no locking -- the replacement for RANDOM_NUMBER, which is not
+ ! safe to call from a parallel region.
+ real(real32) :: u
+ rng_state = ieor(rng_state, ishft(rng_state, 13))
+ rng_state = ieor(rng_state, ishft(rng_state, -17))
+ rng_state = ieor(rng_state, ishft(rng_state, 5))
+ u = real(iand(rng_state, huge(rng_state)), real32) / real(huge(rng_state), real32)
+ end function thread_uniform
+
+ subroutine select_generator_polynomials(nu, g0, g1)
+ ! Optimal (maximum free distance, noncatastrophic) rate-1/2
+ ! generator polynomials, indexed by memory order nu (constraint
+ ! length K = nu+1). K=12 (nu=11) keeps this file's original pair
+ ! (octal 7173,5261), unchanged, so results already gathered at
+ ! that setting stay reproducible. K=10, 11, 13 are the standard
+ ! maximum-dfree pairs from the Larsen/Odenwalder rate-1/2 tables
+ ! (as tabulated in e.g. Proakis "Digital Communications" and Lin &
+ ! Costello "Error Control Coding"):
+ ! K=10 (nu= 9): octal 1167,1545 dfree=12
+ ! K=11 (nu=10): octal 2335,3661 dfree=14
+ ! K=12 (nu=11): octal 7173,5261 (this file's existing pair)
+ ! K=13 (nu=12): octal 10533,17661 dfree=16
+ integer(int32), intent(in) :: nu
+ integer(int32), intent(out) :: g0, g1
+ select case (nu)
+ case (9) ! K = 10, dfree = 12
+ g0 = int(Z"277", int32); g1 = int(Z"365", int32)
+ case (10) ! K = 11, dfree = 14
+ g0 = int(Z"4DD", int32); g1 = int(Z"7B1", int32)
+ case (11) ! K = 12 -- this file's original constants
+ g0 = int(Z"E7B", int32); g1 = int(Z"AB1", int32)
+ case (12) ! K = 13, dfree = 16
+ g0 = int(Z"115B", int32); g1 = int(Z"1FB1", int32)
+ case default
+ print *, "No optimal generator polynomial pair defined for memory_nu =", nu
+ print *, "Supported values: 9, 10, 11, 12 (K = 10, 11, 12, 13)"
+ stop 1
+ end select
+ end subroutine select_generator_polynomials
+
+ pure integer(int32) function parity_bit(val)
+ integer(int32), intent(in) :: val
+ integer(int32) :: temp, p
+ temp = val; p = 0
+ do while (temp > 0)
+ if (iand(temp, 1) /= 0) p = ieor(p, 1)
+ temp = ishft(temp, -1)
+ end do
+ parity_bit = p
+ end function parity_bit
+
+ subroutine seed_random_generator()
+ ! Give every OpenMP thread its own distinct, deterministic, nonzero
+ ! xorshift32 seed -- rng_state is threadprivate, so this assignment
+ ! runs once per thread. Reproducible for a fixed thread count;
+ ! changing OMP_NUM_THREADS changes how frames are partitioned across
+ ! streams, so per-frame outcomes differ (though aggregate statistics
+ ! over num_frames should not, within Monte Carlo noise).
+ ! In a non-OpenMP build, !$ lines and !$omp directives are comments,
+ ! so use a deterministic single-thread seed without requiring libgomp.
+ rng_state = 9999_int32
+ !$omp parallel default(shared)
+ !$ rng_state = 9999_int32 + 104729_int32 * int(omp_get_thread_num(), int32)
+ if (rng_state == 0_int32) rng_state = 1_int32
+ !$omp end parallel
+ end subroutine seed_random_generator
+
+end module tbcc
diff --git a/lib/jtty/transmit.f90 b/lib/jtty/transmit.f90
new file mode 100644
index 00000000..98136ba0
--- /dev/null
+++ b/lib/jtty/transmit.f90
@@ -0,0 +1,55 @@
+subroutine transmit(nfunc)
+
+ use jttycom
+ parameter (MAX_TONES=85*7) !Max number of channel symbols
+ integer itone(MAX_TONES) !Channel symbols (tone frequencies)
+ character*17 cdatetime
+ real wave(NMAX)
+ complex cwave(NMAX)
+
+ if(ntransmitting.eq.1) return !Ignore if we're already transmitting
+
+! if(nfunc.eq.1) txmsg='CQ '//trim(mycall)//' '//mygrid
+! if(nfunc.eq.2) txmsg=trim(hiscall)//' '//trim(mycall)// &
+! ' 599 '//trim(exch)
+! if(nfunc.eq.3) txmsg=trim(hiscall)//' '//trim(mycall)// &
+! ' R 599 '//trim(exch)
+! if(nfunc.eq.4) txmsg=trim(hiscall)//' '//trim(mycall)//' RR73'
+! if(nfunc.eq.5) txmsg='TNX 73 GL'
+
+ if(nfunc.eq.1) txmsg='CQ '//trim(mycall)//' CQ'
+ if(nfunc.eq.2) txmsg=mycall
+ if(nfunc.eq.3) txmsg=trim(hiscall)//' 599 123'
+ if(nfunc.eq.4) txmsg='599 456'
+ if(nfunc.eq.5) txmsg=trim(hiscall)//' TU '//trim(mycall)//' CQ'
+
+ call genjtty(txmsg,itone,nsym)
+
+ nsps=384 !Samples per symbol at 12000 Hz
+ nwave=nsps*nsym !Length of i*2 data written to *.wav file
+ txt=nwave/12000.0
+
+ icmplx=0
+ bt=2.0
+ fsample=12000.0
+ f0=ftx
+ call gen_jttywave(itone,nsym,nsps,bt,fsample,f0,cwave,wave,icmplx,nwave)
+
+ iwave(1:nwave)=1000.0*wave(1:nwave)
+ iwave(nwave:)=0
+ call set_tx_length(nwave)
+ ntxok=1
+ n=len(trim(txmsg))
+
+ write(*,1010) trim(txmsg)
+1010 format('Tx: ',a)
+
+ write(12,1020) cdatetime(),0,0.0,nint(ftx),trim(txmsg)
+1020 format(a17,i4,f6.2,i5,' Tx ',a)
+ if(nfunc.ge.1 .and. nfunc.le.4) ntxed=nfunc
+ if(nfunc.ge.1 .and. nfunc.le.5) ltx(nfunc)=.true.
+ if(nfunc.eq.2 .or. nfunc.eq.3) QSO_in_progress=.true.
+ txmsg=""
+
+ return
+end subroutine transmit
diff --git a/lib/jtty/update.f90 b/lib/jtty/update.f90
new file mode 100644
index 00000000..a95b0519
--- /dev/null
+++ b/lib/jtty/update.f90
@@ -0,0 +1,144 @@
+subroutine update(ic1,ic2)
+
+ ! When the audio streams are active, this routine gets called
+ ! approximately every 100 ms -- determined by this statement
+ ! near the end of C function jttyaudio_():
+ ! Pa_Sleep(100);
+
+ ! It functions somewhat like the GUIupdate() loop in WSJT-X, calling
+ ! Rx or Tx routines as needed.
+
+ use jttycom
+ integer*2 id(30000)
+ logical level
+! character*50 line
+ character*80 umsg
+! character cdatetime*17
+ logical synced,eom
+ data iwrite00/9999999/
+ data level/.false./,idone/0/
+ data synced/.false./,eom/.false./
+ data umsg/' '/,m/0/,nt0/-1/
+ save level,iwrite00,iwrite0,synced,m,nt0,idone
+
+ if(ndebug.gt.0 .and. ntransmitting.eq.0 .and. &
+ (abs(iwrite-iwrite00).ge.12000 .or. iwrite.lt.iwrite00)) then
+ write(*,1000) iwrite,ntxok,ntransmitting,ndebug,ic1,ic2
+1000 format('Receiving iwrite:',i8,5i5)
+ iwrite00=iwrite
+ endif
+
+! Some keyboard Scan Codes: ic1=0, ic2 as follows
+! 13 27 59 60 61 62 63 64 65 66 67 68
+! = ESC F1 F2 F3 F4 F5 F6 F7 F8 F9 F10
+
+ if(ic1.ne.0 .or. ic2.ne.0) then
+ if(ic1.eq.27 .and. ic2.eq.0) ngo=0 !ESC ==> terminate program
+ if(nTxOK.eq.0 .and. ntransmitting.eq.0) then
+ nfunc=0
+ if(ic1.eq.0 .and. ic2.eq.59) nfunc=1 !F1 has Scan Code = 59
+ if(ic1.eq.0 .and. ic2.eq.60) nfunc=2 !F2
+ if(ic1.eq.0 .and. ic2.eq.61) nfunc=3 !F3
+ if(ic1.eq.0 .and. ic2.eq.62) nfunc=4 !F4
+ if(ic1.eq.0 .and. ic2.eq.63) nfunc=5 !F5
+ if(ic1.eq.0 .and. ic2.eq.64) hiscall=txmsg(1:6) !F6
+ if(nfunc.eq.1 .or. (nfunc.ge.2 .and. hiscall.ne.' ')) then
+ call transmit(nfunc)
+ endif
+ endif
+ if(ic1.eq.13 .and. ic2.eq.0) hiscall=hiscall_next !Enter key
+ if((ic1.eq.97 .or. ic1.eq.65) .and. ic2.eq.0) autoseq=.not.autoseq !a or A
+ if(ic1.eq.76 .and. ic2.eq.0) level=.not.level !l or L
+
+ if(ic2.eq.0) then
+ if(ic1.eq.13) then
+ call putchar(13) ! CR
+ call putchar(12) ! LF
+ call transmit(0)
+ m=0
+ elseif(ic1.eq.8) then
+ txmsg(m:m)=' '
+ if(m.ge.1) m=m-1
+ call putchar(ic1)
+ call putchar(32)
+ call putchar(ic1)
+ else
+ m=m+1
+ if(ic1.ge.97 .and. ic1.le.122) ic1=ic1-32
+ txmsg(m:m)=char(ic1)
+ call putchar(ic1)
+ endif
+ endif
+ endif
+
+ nready=iwrite-idone
+ if(nready.lt.0) nready=nready+NMAX
+ if(nready.lt.59*384) go to 100
+
+ ! Call the jtty decoder here, using code from rjtty.
+ ! ### Maybe call rjtty_sub(y1,iwrite,line1) ??? ###
+
+ iz=30240 !### TEMPORARY ###
+ k=iwrite-12000
+ if(k.lt.1) k=k+NMAX
+ do i=1,12000
+ k=k+1
+ if(k.gt.NMAX) k=k-NMAX
+ id(i)=y1(k)
+ enddo
+ nutc=0
+ nfqso=1500
+ nrx=-1
+ k0=0
+ k1=0
+ eom=.false.
+ f0=1500.0
+ ftol=100.0
+ smin=0
+ xdt=0.
+ f1=0.
+!### WORK NEEDED HERE ###
+ call jtty_decode(id,iz,f0,ftol,smin,synced,xdt,f1,snr,umsg)
+! fname=cdatetime()
+! fname(14:17)='.wav'
+! open(13,file=fname,status='unknown',access='stream')
+! h=default_header(12000,nwave)
+! write(13) h,id
+! close(13)
+ if(autoseq .and.nrx.eq.2) QSO_in_progress=.true.
+ if(autoseq .and. QSO_in_progress .and. nrx.ge.1 .and. nrx.le.4) then
+ lrx(nrx)=.true.
+ if(ntxed.eq.1) then
+ if(nrx.eq.2) then
+ call transmit(3)
+ else
+ call transmit(1)
+ endif
+ endif
+ if(ntxed.eq.2) then
+ if(nrx.eq.3) then
+ call transmit(4)
+ QSO_in_progress=.false.
+ write(*,1032)
+1032 format('QSO complete: S+P side')
+ else
+ call transmit(2)
+ endif
+ endif
+ if(ntxed.eq.3) then
+ if(nrx.eq.4) then
+ QSO_in_progress=.false.
+ write(*,1034)
+1034 format('QSO complete: CQ side')
+ else
+ call transmit(3)
+ endif
+ endif
+ endif
+ nt0=nt
+ idone=iwrite
+
+100 iwrite0=iwrite
+
+ return
+end subroutine update
diff --git a/lib/jtty/wava/plot_results.py b/lib/jtty/wava/plot_results.py
new file mode 100644
index 00000000..0ef97628
--- /dev/null
+++ b/lib/jtty/wava/plot_results.py
@@ -0,0 +1,57 @@
+
+import pandas as pd
+import matplotlib.pyplot as plt
+
+# Read data logged from the Fortran testbench suite
+try:
+ df = pd.read_csv('simulation_results.csv')
+except FileNotFoundError:
+ print("Error: 'simulation_results.csv' not found. Execute the Fortran simulation program first.")
+ exit()
+
+# Strip whitespace from columns to avoid parsing mismatches
+df['channel'] = df['channel'].str.strip()
+
+# Initialize Figure with high resolution DPI properties
+fig, ax1 = plt.subplots(figsize=(10, 6), dpi=120)
+
+# Set up Primary Axis: Frame Correct-Decode Probability P(Correct)
+ax1.set_xlabel('SNR in 2500 Hz Reference Bandwidth [dB]', fontsize=11, fontweight='bold')
+ax1.set_ylabel('P(Correct Decode)', color='navy', fontsize=11, fontweight='bold')
+ax1.set_xlim(0, -20) # Invert axis view to scan standard drop off descending to -20 dB
+ax1.set_ylim(-0.05, 1.05)
+ax1.grid(True, which='both', linestyle='--', alpha=0.5)
+
+# Set up Secondary Axis on the right side for 100 * UER (%)
+ax2 = ax1.twinx()
+ax2.set_ylabel('Undetected Error Rate: 100 * UER [%]', color='crimson', fontsize=11, fontweight='bold')
+ax2.set_ylim(-0.1, 5.0) # Standard percentage visualization window
+
+# Isolate channel tracking configurations
+awgn_data = df[df['channel'] == 'AWGN'].sort_values(by='snr_db', ascending=False)
+rayleigh_data = df[df['channel'] == 'RAYLEIGH'].sort_values(by='snr_db', ascending=False)
+
+# Plot Primary Curves - P(Correct)
+line1 = ax1.plot(awgn_data['snr_db'], awgn_data['p_correct'],
+ 'o-', color='navy', linewidth=2.0, label='AWGN: P(Correct)')
+line2 = ax1.plot(rayleigh_data['snr_db'], rayleigh_data['p_correct'],
+ 's-', color='royalblue', linewidth=1.8, label='Rayleigh: P(Correct)')
+
+# Plot Secondary Curves - 100 * UER (%)
+line3 = ax2.plot(awgn_data['snr_db'], awgn_data['uer_pct'],
+ '^--', color='crimson', linewidth=1.5, label='AWGN: 100*UER')
+line4 = ax2.plot(rayleigh_data['snr_db'], rayleigh_data['uer_pct'],
+ 'v--', color='orange', linewidth=1.5, label='Rayleigh: 100*UER')
+
+# Align Legend structures coherently across shared dual axis space
+lines = line1 + line2 + line3 + line4
+labels = [l.get_label() for l in lines]
+ax1.legend(lines, labels, loc='center left', frameon=True, shadow=True)
+
+plt.title('TBCC (92,46) Noncoherent 4-FSK Performance Profile\nConstraint Length K=11, List Size L=8, Rate=1/2',
+ fontsize=12, fontweight='bold', pad=15)
+
+plt.tight_layout()
+plt.savefig('tbcc_performance_curves.png', dpi=300)
+print("Plot successfully rendered and saved as 'tbcc_performance_curves.png'")
+plt.show()
diff --git a/lib/jtty/wava/rcu_bound_4fsk.f90 b/lib/jtty/wava/rcu_bound_4fsk.f90
new file mode 100644
index 00000000..ae58793f
--- /dev/null
+++ b/lib/jtty/wava/rcu_bound_4fsk.f90
@@ -0,0 +1,217 @@
+program rcu_bound_4fsk
+ ! Random Coding Union (RCU) achievability bound (Polyanskiy-Poor-Verdu
+ ! 2010, eq. 2) for noncoherent 4-FSK over AWGN and Rayleigh-fading
+ ! channels, matched to the exact channel model and SNR convention used
+ ! in tbcc_4fsk_simulation.f90. This bounds the frame-error probability
+ ! of the BEST POSSIBLE code at (n=46 symbols, M=2^k messages) -- a
+ ! benchmark for how close an actual code+decoder gets to optimal, not a
+ ! statement about any particular code.
+ !
+ ! Method: for a fixed received sequence r^n, each per-symbol term of the
+ ! competitor information density i(X_bar_t; r_t) is an exact discrete
+ ! 4-valued random variable (X_bar_t uniform over the 4 tones), so its
+ ! mean/variance are closed-form -- no inner Monte Carlo. Summing 46 such
+ ! terms and invoking the CLT gives the inner tail probability via erfc.
+ ! Only the outer expectation (over the true (x^n, r^n) pair) needs Monte
+ ! Carlo.
+ use, intrinsic :: iso_fortran_env, only: real32, real64, int32
+ use omp_lib
+ implicit none
+
+ integer(int32), save :: rng_state = 0
+ !$omp threadprivate(rng_state)
+
+ integer(int32), parameter :: N_SYM = 46 ! channel uses; matches TOTAL_K
+
+ character(len=8) :: channel_type
+ character(len=16) :: arg
+ integer(int32) :: nargs, num_trials, kbits, e, s
+ real(real64) :: Mminus1, rcu
+ real(real32) :: snr_2500_db, esno_linear
+ real(real64) :: t_wall_start, t_wall_end
+
+ nargs = iargc()
+ if (nargs /= 2) then
+ print *, 'Usage: rcu_bound_4fsk <num_trials> <k_bits>'
+ print *, ' k_bits: log2(number of equiprobable messages), e.g. 34'
+ stop
+ end if
+ call getarg(1, arg); read(arg,*) num_trials
+ call getarg(2, arg); read(arg,*) kbits
+ Mminus1 = 2.0_real64**kbits - 1.0_real64
+
+ call seed_random_generator()
+
+ print *, "=========================================================================="
+ print *, "RCU achievability bound: noncoherent 4-FSK, n =", N_SYM, " symbols"
+ print *, "M = 2^", kbits, "equiprobable messages | OpenMP threads:", omp_get_max_threads()
+ print *, "=========================================================================="
+
+ open(unit=25, file="rcu_bound_results.csv", status="unknown", action="write")
+ write(25,'(A)') "channel,snr_db,rcu_bound"
+
+ t_wall_start = omp_get_wtime()
+
+ do e = 1, 2
+ channel_type = merge("AWGN ", "RAYLEIGH", e == 1)
+ print *, ""
+ print *, "--- Channel: ", trim(channel_type), " ---"
+ write(*,'(A10,A16)') "SNR_2500", "RCU bound"
+ do s = -5, -20, -1
+ snr_2500_db = real(s, real32)
+ esno_linear = (10.0_real32**(snr_2500_db/10.0_real32)) * 80.0_real32
+ call compute_rcu(channel_type, esno_linear, Mminus1, num_trials, rcu)
+ write(*,'(F10.1,ES16.5)') snr_2500_db, rcu
+ write(25,'(A,A,F6.1,A,ES14.6)') trim(channel_type), ",", snr_2500_db, ",", rcu
+ end do
+ end do
+
+ close(25)
+ t_wall_end = omp_get_wtime()
+ print '(A,F8.2,A)', "Total wall-clock time: ", t_wall_end - t_wall_start, " s"
+
+contains
+
+ subroutine compute_rcu(channel_type, esno, Mm1, ntrials, rcu_out)
+ character(len=*), intent(in) :: channel_type
+ real(real32), intent(in) :: esno
+ real(real64), intent(in) :: Mm1
+ integer(int32), intent(in) :: ntrials
+ real(real64), intent(out) :: rcu_out
+
+ integer(int32) :: trial, t, x_true, j
+ real(real32) :: r(0:3), n_i, n_q, hfade
+ real(real64) :: logL(0:3), S, i_true, mu_t, var_t, term
+ real(real64) :: T_sum, MU_sum, VAR_sum, tail, bound_val, acc
+
+ acc = 0.0_real64
+
+ !$omp parallel do default(shared) &
+ !$omp private(trial, t, x_true, j, r, n_i, n_q, hfade, logL, S, &
+ !$omp i_true, mu_t, var_t, term, T_sum, MU_sum, VAR_sum, &
+ !$omp tail, bound_val) &
+ !$omp reduction(+:acc) schedule(static)
+ do trial = 1, ntrials
+ T_sum = 0.0_real64
+ MU_sum = 0.0_real64
+ VAR_sum = 0.0_real64
+
+ do t = 1, N_SYM
+ x_true = int(thread_uniform()*4.0_real32)
+ if (x_true > 3) x_true = 3
+
+ if (channel_type == "AWGN") then
+ hfade = 1.0_real32
+ else
+ call box_muller(n_i); call box_muller(n_q)
+ hfade = sqrt(0.5_real32*(n_i**2 + n_q**2))
+ end if
+
+ do j = 0, 3
+ call box_muller(n_i); call box_muller(n_q)
+ n_i = n_i*sqrt(0.5_real32); n_q = n_q*sqrt(0.5_real32)
+ if (j == x_true) then
+ r(j) = (hfade*sqrt(esno) + n_i)**2 + n_q**2
+ else
+ r(j) = n_i**2 + n_q**2
+ end if
+ end do
+
+ ! log-likelihood-ratio log L(r) = log f_sig(r) - log f_noise(r)
+ do j = 0, 3
+ if (channel_type == "AWGN") then
+ logL(j) = -real(esno,real64) &
+ + log_bessel_i0(2.0_real64*sqrt(real(esno,real64)*real(r(j),real64)))
+ else
+ logL(j) = -log(1.0_real64+real(esno,real64)) &
+ + real(r(j),real64)*real(esno,real64)/(1.0_real64+real(esno,real64))
+ end if
+ end do
+
+ S = logsumexp4(logL) ! log( sum_j L(r_j) )
+ i_true = log(4.0_real64) + logL(x_true) - S
+
+ mu_t = 0.0_real64
+ do j = 0, 3
+ mu_t = mu_t + (log(4.0_real64) + logL(j) - S)
+ end do
+ mu_t = mu_t/4.0_real64
+
+ var_t = 0.0_real64
+ do j = 0, 3
+ term = (log(4.0_real64) + logL(j) - S) - mu_t
+ var_t = var_t + term*term
+ end do
+ var_t = var_t/4.0_real64
+
+ T_sum = T_sum + i_true
+ MU_sum = MU_sum + mu_t
+ VAR_sum = VAR_sum + var_t
+ end do
+
+ ! CLT approximation to Pr[ sum_t i(X_bar_t;r_t) >= T_sum ]
+ tail = 0.5_real64*erfc( (T_sum-MU_sum) / sqrt(2.0_real64*VAR_sum) )
+ bound_val = min(1.0_real64, Mm1*tail)
+ acc = acc + bound_val
+ end do
+ !$omp end parallel do
+
+ rcu_out = acc/real(ntrials, real64)
+ end subroutine compute_rcu
+
+ pure function logsumexp4(v) result(s)
+ real(real64), intent(in) :: v(0:3)
+ real(real64) :: s, m
+ m = maxval(v)
+ s = m + log(sum(exp(v-m)))
+ end function logsumexp4
+
+ ! log(I0(x)), x>=0, via the standard Abramowitz & Stegun 9.8.1/9.8.2
+ ! rational approximations (~1.6e-7 relative accuracy), evaluated in log
+ ! space for large x to avoid overflowing exp(x).
+ pure function log_bessel_i0(x) result(logi0)
+ real(real64), intent(in) :: x
+ real(real64) :: logi0, ax, y, bessi0
+
+ ax = abs(x)
+ if (ax < 3.75_real64) then
+ y = (x/3.75_real64)**2
+ bessi0 = 1.0_real64 + y*(3.5156229_real64 + y*(3.0899424_real64 + &
+ y*(1.2067492_real64 + y*(0.2659732_real64 + &
+ y*(0.0360768_real64 + y*0.0045813_real64)))))
+ logi0 = log(bessi0)
+ else
+ y = 3.75_real64/ax
+ logi0 = ax - 0.5_real64*log(ax) + &
+ log(0.39894228_real64 + y*(0.01328592_real64 + &
+ y*(0.00225319_real64 + y*(-0.00157565_real64 + &
+ y*(0.00916281_real64 + y*(-0.02057706_real64 + &
+ y*(0.02635537_real64 + y*(-0.01647633_real64 + &
+ y*0.00392377_real64))))))))
+ end if
+ end function log_bessel_i0
+
+ subroutine box_muller(rand_normal)
+ real(real32), intent(out) :: rand_normal
+ real(real32) :: u1, u2
+ u1 = thread_uniform(); u2 = thread_uniform()
+ if (u1 < 1.0e-30_real32) u1 = 1.0e-30_real32
+ rand_normal = sqrt(-2.0_real32*log(u1)) * cos(6.28318530718_real32*u2)
+ end subroutine box_muller
+
+ function thread_uniform() result(u)
+ real(real32) :: u
+ rng_state = ieor(rng_state, ishft(rng_state, 13))
+ rng_state = ieor(rng_state, ishft(rng_state, -17))
+ rng_state = ieor(rng_state, ishft(rng_state, 5))
+ u = real(iand(rng_state, huge(rng_state)), real32) / real(huge(rng_state), real32)
+ end function thread_uniform
+
+ subroutine seed_random_generator()
+ !$omp parallel default(shared)
+ rng_state = 9999_int32 + 104729_int32*int(omp_get_thread_num(), int32)
+ if (rng_state == 0_int32) rng_state = 1_int32
+ !$omp end parallel
+ end subroutine seed_random_generator
+
+end program rcu_bound_4fsk
diff --git a/lib/jtty/wava/tbcc_4fsk_simulation.f90 b/lib/jtty/wava/tbcc_4fsk_simulation.f90
new file mode 100644
index 00000000..d6512f27
--- /dev/null
+++ b/lib/jtty/wava/tbcc_4fsk_simulation.f90
@@ -0,0 +1,167 @@
+program tbcc_4fsk_simulation
+
+ use, intrinsic :: iso_fortran_env, only: real32, int32, real64
+ use omp_lib
+ use tbcc
+ implicit none
+
+ real(real64) :: t_wall_start, t_wall_end
+
+ character(len=8) :: channel_type
+ character(len=8) :: arg
+ real(real32) :: snr_2500_db, esno_linear
+
+
+ integer(int32) :: tx_payload(PAYLOAD_BITS), tx_symbols(TOTAL_K)
+ real(real32) :: rx_tone_energies(0:3, TOTAL_K)
+ integer(int32) :: rx_decoded(PAYLOAD_BITS)
+
+ integer(int32) :: correct_frames, undetected_errors, total_detected_errors, total_frames
+ integer(int32) :: num_frames, L_size, wava_iters, isnr1, isnr2
+ real(real32) :: p_correct, uer
+ integer(int32) :: f, e, t, s, i, nargs
+ real(real32) :: n_i, n_q, h_fade, ch_i, ch_q, xsnr
+ logical :: decode_success, payload_match
+
+ nargs=iargc()
+ if(nargs.ne.5) then
+ print*,'Usage: tbcc_sim nu L iters Nmax SNR'
+ print*,'Example: tbcc_sim 9 4 2 10000 0'
+ stop
+ endif
+
+ call getarg(1,arg)
+ read(arg,*) memory_nu
+ call getarg(2,arg)
+ read(arg,*) L_size ! List size
+ call getarg(3,arg)
+ read(arg,*) wava_iters ! Trellis wraps for tail-biting convergence
+ call getarg(4,arg)
+ read(arg,*) num_frames
+ call getarg(5,arg)
+ read(arg,*) xsnr
+
+ call seed_random_generator()
+
+ print *, "=========================================================================="
+ print *, "Tail-Biting Convolutional Code (92,46) Noncoherent 4-FSK Simulation Suite"
+ print *, "Symbol Rate = 31.25 Baud | Reference Bandwidth = 2500 Hz"
+ print *, "OpenMP threads available: ", omp_get_max_threads()
+ print *, "Writing data logs directly to simulation_results.csv..."
+ print *, "=========================================================================="
+
+ ! Open CSV data output buffer file
+ open(unit=24, file="simulation_results.dat", status="unknown", action="write")
+ open(unit=25, file="simulation_results.csv", status="unknown", action="write")
+ write(24, '(A)') "snr,frames,good,uer"
+ write(25, '(A)') "channel,snr_db,p_correct,uer_pct"
+
+ t_wall_start = omp_get_wtime()
+ call tbcc_init(memory_nu)
+ total_frames = 0
+
+ do e = 1, 2
+ channel_type = merge("AWGN ", "RAYLEIGH", e == 1)
+ print *, ""
+ print *, "--- Channel Profile: ", trim(channel_type), " ---"
+ write(24,'(a,a,a)') "--- Channel Profile: ", trim(channel_type), " ---"
+
+ write(*,1000)
+ write(24,1000)
+1000 format(' SNR_2500 Frames Good UER '/39('-'))
+
+ isnr1 = -5
+ isnr2 = -20
+ do s = isnr1, isnr2, -1
+ snr_2500_db = s
+ if(xsnr.ne.0.0) snr_2500_db = xsnr
+ esno_linear = (10.0_real32 ** (snr_2500_db / 10.0_real32)) * 80.0_real32
+ correct_frames = 0
+ undetected_errors = 0
+ total_detected_errors = 0
+
+ ! Each frame (generate -> encode -> channel -> WAVA decode) is
+ ! completely independent of every other frame, so the frame loop
+ ! is embarrassingly parallel. Every array/scalar that a single
+ ! frame writes must be private -- otherwise threads clobber each
+ ! other's tx_payload/tx_encoded/etc. The three tallies are
+ ! combined across threads via REDUCTION.
+
+ !$omp parallel do default(shared) &
+ !$omp private(f, t, i, n_i, n_q, h_fade, ch_i, ch_q, decode_success, payload_match, &
+ !$omp tx_payload, tx_symbols, rx_tone_energies, rx_decoded) &
+ !$omp reduction(+:correct_frames, undetected_errors, total_detected_errors) &
+ !$omp schedule(static)
+ do f = 1, num_frames
+ call generate_random_bits(tx_payload, PAYLOAD_BITS)
+ call tbcc_encode(tx_payload, tx_symbols)
+
+ ! Channel Simulation
+ do t = 1, TOTAL_K
+ if (channel_type == "AWGN") then
+ h_fade = 1.0_real32
+ else
+ call box_muller(n_i)
+ call box_muller(n_q)
+ h_fade = sqrt(0.5_real32 * (n_i**2 + n_q**2))
+ end if
+
+ do i = 0, 3
+ call box_muller(n_i)
+ call box_muller(n_q)
+ n_i = n_i * sqrt(0.5_real32)
+ n_q = n_q * sqrt(0.5_real32)
+
+ if (i == tx_symbols(t)) then
+ ch_i = (h_fade * sqrt(esno_linear)) + n_i
+ ch_q = n_q
+ else
+ ch_i = n_i
+ ch_q = n_q
+ end if
+ rx_tone_energies(i, t) = ch_i**2 + ch_q**2
+ end do
+ end do
+
+ ! Decoding Execution
+ call tbcc_wava_fsk_decode(rx_tone_energies, L_size, wava_iters, &
+ rx_decoded, decode_success)
+
+ if (decode_success) then
+ payload_match = all(tx_payload == rx_decoded)
+ if (payload_match) then
+ correct_frames = correct_frames + 1
+ else
+ undetected_errors = undetected_errors + 1
+ end if
+ else
+ total_detected_errors = total_detected_errors + 1
+ end if
+ end do
+ !$omp end parallel do
+
+ p_correct = real(correct_frames, real32) / real(num_frames, real32)
+ uer = real(undetected_errors, real32) / real(num_frames, real32)
+ total_frames = total_frames + num_frames
+
+ write(*,1001) snr_2500_db, num_frames, p_correct, uer
+ write(24,1001) snr_2500_db, num_frames, p_correct, uer
+1001 format(f8.1,i10,2f10.6)
+
+ ! Write tracking vectors to the spreadsheet data table (Multiplying UER by
+ ! 100 for percentage scale)
+ write(25, '(A,A,F6.1,A,F7.5,A,F7.5)') trim(channel_type), ",", snr_2500_db, &
+ ",", p_correct, ",", uer * 100.0_real32
+ if(xsnr.ne.0.0) exit
+ end do !Loop over SNRs
+ end do !Loop over channel types (AWGN, then Rayleigh)
+
+ close(24)
+ close(25)
+
+ t_wall_end = omp_get_wtime()
+ print '(A,F8.2,A)', "Total wall-clock time: ", t_wall_end - t_wall_start, " s"
+ print '(a,f7.3,a)' ,"Average time per frame: ", &
+ 1000.0*(t_wall_end - t_wall_start)/total_frames, " ms"
+
+end program tbcc_4fsk_simulation
diff --git a/lib/jtty/wava/tbcc_performance_curves.png b/lib/jtty/wava/tbcc_performance_curves.png
new file mode 100644
index 00000000..88d63b07
--- /dev/null
+++ b/lib/jtty/wava/tbcc_performance_curves.png
Binary files differ
diff --git a/lib/lookup3.c b/lib/lookup3.c
new file mode 100644
index 00000000..d9951e81
--- /dev/null
+++ b/lib/lookup3.c
@@ -0,0 +1,305 @@
+/*
+ File name: lookup3.c
+
+ *------------------------------------------------------------------------------
+ *
+ * This file is part of the WSPR application, Weak Signal Propogation Reporter
+ *
+ * File Name: lookup3.c
+ * Description: Produce 32-bit hashes for hash table lookup
+ *
+ * Copyright (C) 2008-2014 Joseph Taylor, K1JT
+ * License: GNU GPL v3+
+ *
+ * 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 3 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., 51 Franklin
+ * Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * Files: lookup3.c
+ * Copyright: Copyright (C) 2006 Bob Jenkins <bob_jenkins@burtleburtle.net>
+ * License: public-domain
+ * You may use this code any way you wish, private, educational, or commercial.
+ * It's free.
+ *
+ *-------------------------------------------------------------------------------
+*/
+
+#include "lookup3.h"
+
+#define HASH_LITTLE_ENDIAN 1
+
+#define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
+
+/*
+-------------------------------------------------------------------------------
+mix -- mix 3 32-bit values reversibly.
+
+This is reversible, so any information in (a,b,c) before mix() is
+still in (a,b,c) after mix().
+
+If four pairs of (a,b,c) inputs are run through mix(), or through
+mix() in reverse, there are at least 32 bits of the output that
+are sometimes the same for one pair and different for another pair.
+This was tested for:
+* pairs that differed by one bit, by two bits, in any combination
+ of top bits of (a,b,c), or in any combination of bottom bits of
+ (a,b,c).
+* "differ" is defined as +, -, ^, or ~^. For + and -, I transformed
+ the output delta to a Gray code (a^(a>>1)) so a string of 1's (as
+ is commonly produced by subtraction) look like a single 1-bit
+ difference.
+* the base values were pseudorandom, all zero but one bit set, or
+ all zero plus a counter that starts at zero.
+
+Some k values for my "a-=c; a^=rot(c,k); c+=b;" arrangement that
+satisfy this are
+ 4 6 8 16 19 4
+ 9 15 3 18 27 15
+ 14 9 3 7 17 3
+Well, "9 15 3 18 27 15" didn't quite get 32 bits diffing
+for "differ" defined as + with a one-bit base and a two-bit delta. I
+used http://burtleburtle.net/bob/hash/avalanche.html to choose
+the operations, constants, and arrangements of the variables.
+
+This does not achieve avalanche. There are input bits of (a,b,c)
+that fail to affect some output bits of (a,b,c), especially of a. The
+most thoroughly mixed value is c, but it doesn't really even achieve
+avalanche in c.
+
+This allows some parallelism. Read-after-writes are good at doubling
+the number of bits affected, so the goal of mixing pulls in the opposite
+direction as the goal of parallelism. I did what I could. Rotates
+seem to cost as much as shifts on every machine I could lay my hands
+on, and rotates are much kinder to the top and bottom bits, so I used
+rotates.
+-------------------------------------------------------------------------------
+*/
+#define mix(a,b,c) \
+{ \
+ a -= c; a ^= rot(c, 4); c += b; \
+ b -= a; b ^= rot(a, 6); a += c; \
+ c -= b; c ^= rot(b, 8); b += a; \
+ a -= c; a ^= rot(c,16); c += b; \
+ b -= a; b ^= rot(a,19); a += c; \
+ c -= b; c ^= rot(b, 4); b += a; \
+}
+
+/*
+-------------------------------------------------------------------------------
+final -- final mixing of 3 32-bit values (a,b,c) into c
+
+Pairs of (a,b,c) values differing in only a few bits will usually
+produce values of c that look totally different. This was tested for
+* pairs that differed by one bit, by two bits, in any combination
+ of top bits of (a,b,c), or in any combination of bottom bits of
+ (a,b,c).
+* "differ" is defined as +, -, ^, or ~^. For + and -, I transformed
+ the output delta to a Gray code (a^(a>>1)) so a string of 1's (as
+ is commonly produced by subtraction) look like a single 1-bit
+ difference.
+* the base values were pseudorandom, all zero but one bit set, or
+ all zero plus a counter that starts at zero.
+
+These constants passed:
+ 14 11 25 16 4 14 24
+ 12 14 25 16 4 14 24
+and these came close:
+ 4 8 15 26 3 22 24
+ 10 8 15 26 3 22 24
+ 11 8 15 26 3 22 24
+-------------------------------------------------------------------------------
+*/
+#define final(a,b,c) \
+{ \
+ c ^= b; c -= rot(b,14); \
+ a ^= c; a -= rot(c,11); \
+ b ^= a; b -= rot(a,25); \
+ c ^= b; c -= rot(b,16); \
+ a ^= c; a -= rot(c,4); \
+ b ^= a; b -= rot(a,14); \
+ c ^= b; c -= rot(b,24); \
+}
+
+/*
+-------------------------------------------------------------------------------
+hashlittle() -- hash a variable-length key into a 32-bit value
+ k : the key (the unaligned variable-length array of bytes)
+ length : the length of the key, counting by bytes
+ initval : can be any 4-byte value
+Returns a 32-bit value. Every bit of the key affects every bit of
+the return value. Two keys differing by one or two bits will have
+totally different hash values.
+
+The best hash table sizes are powers of 2. There is no need to do
+mod a prime (mod is sooo slow!). If you need less than 32 bits,
+use a bitmask. For example, if you need only 10 bits, do
+ h = (h & hashmask(10));
+In which case, the hash table should have hashsize(10) elements.
+
+If you are hashing n strings (uint8_t **)k, do it like this:
+ for (i=0, h=0; i<n; ++i) h = hashlittle( k[i], len[i], h);
+
+By Bob Jenkins, 2006. bob_jenkins@burtleburtle.net. You may use this
+code any way you wish, private, educational, or commercial. It's free.
+
+Use for hash table lookup, or anything where one collision in 2^^32 is
+acceptable. Do NOT use for cryptographic purposes.
+-------------------------------------------------------------------------------
+*/
+
+uint32_t wsjt_hashlittle(const void *key, size_t length, uint32_t initval)
+{
+ uint32_t a,b,c; /* internal state */
+ union { const void *ptr; size_t i; } u; /* needed for Mac Powerbook G4 */
+
+ /* Set up the internal state */
+ a = b = c = 0xdeadbeef + ((uint32_t)length) + initval;
+
+ u.ptr = key;
+ if (HASH_LITTLE_ENDIAN && ((u.i & 0x3) == 0)) {
+ const uint32_t *k = (const uint32_t *)key; /* read 32-bit chunks */
+
+ /*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */
+ while (length > 12)
+ {
+ a += k[0];
+ b += k[1];
+ c += k[2];
+ mix(a,b,c);
+ length -= 12;
+ k += 3;
+ }
+
+ /*----------------------------- handle the last (probably partial) block */
+ const uint8_t *k8 = (const uint8_t *)k;
+ switch(length)
+ {
+ case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
+ case 11: c+=((uint32_t)k8[10])<<16; /* fall through */
+ case 10: c+=((uint32_t)k8[9])<<8; /* fall through */
+ case 9 : c+=k8[8]; /* fall through */
+ case 8 : b+=k[1]; a+=k[0]; break;
+ case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */
+ case 6 : b+=((uint32_t)k8[5])<<8; /* fall through */
+ case 5 : b+=k8[4]; /* fall through */
+ case 4 : a+=k[0]; break;
+ case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */
+ case 2 : a+=((uint32_t)k8[1])<<8; /* fall through */
+ case 1 : a+=k8[0]; break;
+ case 0 : return c;
+ }
+
+ } else if (HASH_LITTLE_ENDIAN && ((u.i & 0x1) == 0)) {
+ const uint16_t *k = (const uint16_t *)key; /* read 16-bit chunks */
+ const uint8_t *k8;
+
+ /*--------------- all but last block: aligned reads and different mixing */
+ while (length > 12)
+ {
+ a += k[0] + (((uint32_t)k[1])<<16);
+ b += k[2] + (((uint32_t)k[3])<<16);
+ c += k[4] + (((uint32_t)k[5])<<16);
+ mix(a,b,c);
+ length -= 12;
+ k += 6;
+ }
+
+ /*----------------------------- handle the last (probably partial) block */
+ k8 = (const uint8_t *)k;
+ switch(length)
+ {
+ case 12: c+=k[4]+(((uint32_t)k[5])<<16);
+ b+=k[2]+(((uint32_t)k[3])<<16);
+ a+=k[0]+(((uint32_t)k[1])<<16);
+ break;
+ case 11: c+=((uint32_t)k8[10])<<16; /* fall through */
+ case 10: c+=k[4];
+ b+=k[2]+(((uint32_t)k[3])<<16);
+ a+=k[0]+(((uint32_t)k[1])<<16);
+ break;
+ case 9 : c+=k8[8]; /* fall through */
+ case 8 : b+=k[2]+(((uint32_t)k[3])<<16);
+ a+=k[0]+(((uint32_t)k[1])<<16);
+ break;
+ case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */
+ case 6 : b+=k[2];
+ a+=k[0]+(((uint32_t)k[1])<<16);
+ break;
+ case 5 : b+=k8[4]; /* fall through */
+ case 4 : a+=k[0]+(((uint32_t)k[1])<<16);
+ break;
+ case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */
+ case 2 : a+=k[0];
+ break;
+ case 1 : a+=k8[0];
+ break;
+ case 0 : return c; /* zero length requires no mixing */
+ }
+
+ } else { /* need to read the key one byte at a time */
+ const uint8_t *k = (const uint8_t *)key;
+
+ /*--------------- all but the last block: affect some 32 bits of (a,b,c) */
+ while (length > 12)
+ {
+ a += k[0];
+ a += ((uint32_t)k[1])<<8;
+ a += ((uint32_t)k[2])<<16;
+ a += ((uint32_t)k[3])<<24;
+ b += k[4];
+ b += ((uint32_t)k[5])<<8;
+ b += ((uint32_t)k[6])<<16;
+ b += ((uint32_t)k[7])<<24;
+ c += k[8];
+ c += ((uint32_t)k[9])<<8;
+ c += ((uint32_t)k[10])<<16;
+ c += ((uint32_t)k[11])<<24;
+ mix(a,b,c);
+ length -= 12;
+ k += 12;
+ }
+
+ /*-------------------------------- last block: affect all 32 bits of (c) */
+ switch(length) /* all the case statements fall through */
+ {
+ case 12: c+=((uint32_t)k[11])<<24;
+ /* fall through */
+ case 11: c+=((uint32_t)k[10])<<16;
+ /* fall through */
+ case 10: c+=((uint32_t)k[9])<<8;
+ /* fall through */
+ case 9 : c+=k[8];
+ /* fall through */
+ case 8 : b+=((uint32_t)k[7])<<24;
+ /* fall through */
+ case 7 : b+=((uint32_t)k[6])<<16;
+ /* fall through */
+ case 6 : b+=((uint32_t)k[5])<<8;
+ /* fall through */
+ case 5 : b+=k[4];
+ /* fall through */
+ case 4 : a+=((uint32_t)k[3])<<24;
+ /* fall through */
+ case 3 : a+=((uint32_t)k[2])<<16;
+ /* fall through */
+ case 2 : a+=((uint32_t)k[1])<<8;
+ /* fall through */
+ case 1 : a+=k[0];
+ break;
+ case 0 : return c;
+ }
+ }
+
+ final(a,b,c);
+ return c;
+}
diff --git a/lib/lookup3.h b/lib/lookup3.h
new file mode 100644
index 00000000..ad45d2d0
--- /dev/null
+++ b/lib/lookup3.h
@@ -0,0 +1,18 @@
+#ifndef WSJT_LOOKUP3_H_
+#define WSJT_LOOKUP3_H_
+
+#include <stddef.h>
+#include <stdint.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Return the full 32-bit Jenkins lookup3 hash for a byte sequence. */
+uint32_t wsjt_hashlittle(const void *key, size_t length, uint32_t initval);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/lib/map65_mmdec.f90 b/lib/map65_mmdec.f90
index 14871857..797e6ab5 100644
--- a/lib/map65_mmdec.f90
+++ b/lib/map65_mmdec.f90
@@ -1,20 +1,30 @@
+module map65_mmdec_mod
+ use q65_decode
+ implicit none
+
+ type, extends(q65_decoder) :: counting_q65_decoder
+ integer :: decoded
+ end type counting_q65_decoder
+
+contains
+
subroutine map65_mmdec(nutc,id2,nqd,ntrperiod, nsubmode,nfa,nfb,nfqso, &
ntol,newdat,nagain,max_drift,ndepth,mycall,hiscall,hisgrid)
use prog_args
use timer_module, only: timer
use q65_decode
+ use iso_fortran_env, only: int16
include 'jt9com.f90'
- include 'timer_common.inc'
-
- type, extends(q65_decoder) :: counting_q65_decoder
- integer :: decoded
- end type counting_q65_decoder
logical single_decode,bVHF,lnewdat,lagain,lclearave,lapcqonly
- integer*2 id2(300*12000)
+ integer(int16) id2(300*12000)
integer nqf(20)
+ integer nutc,nqd,ntrperiod,nsubmode,nfa,nfb,nfqso,ntol
+ integer newdat,nagain,max_drift,ndepth,navg0,ncontest
+ integer nqsoprogress,ntr0
+ real emedelay
! type(params_block) :: params
character(len=12) :: mycall, hiscall
character(len=6) :: hisgrid
@@ -44,47 +54,49 @@ subroutine map65_mmdec(nutc,id2,nqd,ntrperiod, nsubmode,nfa,nfb,nfqso, &
call timer('dec_q65 ',0)
call my_q65%decode(q65_decoded,id2,nqd,nutc,ntrperiod,nsubmode,nfqso, &
ntol,ndepth,nfa,nfb,lclearave,single_decode,lagain,max_drift,lnewdat, &
- emedelay,mycall,hiscall,hisgrid,nQSOProgress,ncontest,lapcqonly,navg0,nqf)
+ emedelay,mycall,hiscall,hisgrid,nQSOProgress,ncontest,.false., &
+ lapcqonly,navg0,nqf)
call timer('dec_q65 ',1)
return
-contains
-
- subroutine q65_decoded (this,nutc,snr1,nsnr,dt,freq,decoded,idec, &
- nused,ntrperiod)
-
- use q65_decode
- implicit none
-
- class(q65_decoder), intent(inout) :: this
- integer, intent(in) :: nutc
- real, intent(in) :: snr1
- integer, intent(in) :: nsnr
- real, intent(in) :: dt
- real, intent(in) :: freq
- character(len=37), intent(in) :: decoded
- integer, intent(in) :: idec
- integer, intent(in) :: nused
- integer, intent(in) :: ntrperiod
-
- if(nutc+snr1+nsnr+dt+freq+idec+nused+ntrperiod.eq.-999) stop
- if(decoded.eq.'-999') stop
-
- cq0='q '
- write(cq0(2:2),'(i1)') idec
- if(nused.ge.2) write(cq0(3:3),'(i1)') nused
- nsnr0=nsnr
- xdt0=dt
- nfreq0=nint(freq)
- msg0=decoded
-
- select type(this)
- type is (counting_q65_decoder)
- if(idec.ge.0) this%decoded = this%decoded + 1
- end select
-
- return
- end subroutine q65_decoded
end subroutine map65_mmdec
+
+subroutine q65_decoded (this,nutc,snr1,nsnr,dt,freq,decoded,idec, &
+ nused,ntrperiod,iflagdec)
+
+ implicit none
+
+ class(q65_decoder), intent(inout) :: this
+ integer, intent(in) :: nutc
+ real, intent(in) :: snr1
+ integer, intent(in) :: nsnr
+ real, intent(in) :: dt
+ real, intent(in) :: freq
+ character(len=37), intent(in) :: decoded
+ integer, intent(in) :: idec
+ integer, intent(in) :: nused
+ integer, intent(in) :: ntrperiod
+ integer, intent(in) :: iflagdec !Not used by MAP65's q65b path; see WSJT-X's q65_decoded
+
+ if(nutc+snr1+nsnr+dt+freq+idec+nused+ntrperiod+iflagdec.eq.-999) stop
+ if(decoded.eq.'-999') stop
+
+ cq0='q '
+ write(cq0(2:2),'(i1)') idec
+ if(nused.ge.2) write(cq0(3:3),'(i1)') nused
+ nsnr0=nsnr
+ xdt0=dt
+ nfreq0=nint(freq)
+ msg0=decoded
+
+ select type(this)
+ type is (counting_q65_decoder)
+ if(idec.ge.0) this%decoded = this%decoded + 1
+ end select
+
+ return
+end subroutine q65_decoded
+
+end module map65_mmdec_mod
diff --git a/lib/moondopjpl.f90 b/lib/moondopjpl.f90
index 20fbb5e8..f05de384 100644
--- a/lib/moondopjpl.f90
+++ b/lib/moondopjpl.f90
@@ -1,6 +1,9 @@
subroutine MoonDopJPL(nyear,month,nday,uth4,lon4,lat4,RAMoon4, &
- DecMoon4,LST4,HA4,AzMoon4,ElMoon4,vr4,dist4)
+ DecMoon4,LST4,HA4,AzMoon4,ElMoon4,vr4,dist4,ephemeris_result)
+ use ieee_arithmetic, only: ieee_is_finite
+ use jpl_ephemeris_status, only: EPHEMERIS_INVALID_INPUT, &
+ EPHEMERIS_UNAVAILABLE
implicit real*8 (a-h,o-z)
real*4 uth4 !UT in hours
real*4 lon4 !East longitude, degrees
@@ -13,12 +16,28 @@ subroutine MoonDopJPL(nyear,month,nday,uth4,lon4,lat4,RAMoon4, &
real*4 ElMoon4 !Topocentric Elevation of moon, degrees
real*4 vr4 !Radial velocity of moon wrt obs, km/s
real*4 dist4 !Echo time, seconds
+ integer ephemeris_result
+
+ RAMoon4=0.
+ DecMoon4=0.
+ LST4=0.
+ HA4=0.
+ AzMoon4=0.
+ ElMoon4=0.
+ vr4=0.
+ dist4=0.
+ ephemeris_result=EPHEMERIS_INVALID_INPUT
+
+ if(.not.ieee_is_finite(uth4) .or. uth4.lt.0. .or. uth4.ge.24.) return
+ if(.not.ieee_is_finite(lon4) .or. .not.ieee_is_finite(lat4)) return
+ if(lat4.lt.-90. .or. lat4.gt.90.) return
twopi=8.d0*atan(1.d0) !Define some constants
rad=360.d0/twopi
clight=2.99792458d5
call sla_CLDJ(nyear,month,nday,djutc,j)
+ if(j.ne.0) return
djutc=djutc + uth4/24.d0
dut=-0.460d0
@@ -28,7 +47,8 @@ subroutine MoonDopJPL(nyear,month,nday,uth4,lon4,lat4,RAMoon4, &
nspecial=0
call ephem(djutc,dut,east_long,geodetic_lat,height,nspecial, &
- RA,Dec,Az,El,techo,dop,fspread_1GHz,vr)
+ RA,Dec,Az,El,techo,dop,fspread_1GHz,vr,ephemeris_result)
+ if(ephemeris_result.eq.EPHEMERIS_UNAVAILABLE) return
RAMoon4=RA
DecMoon4=Dec
diff --git a/lib/morse.f90 b/lib/morse.f90
index 7b428958..ecc6b2be 100644
--- a/lib/morse.f90
+++ b/lib/morse.f90
@@ -1,4 +1,12 @@
-subroutine morse(msg,idat,n)
+module morse_encoder
+
+ implicit none
+ private
+ public encode_morse
+
+contains
+
+subroutine encode_morse(msg,idat,n)
! Convert ascii message to a Morse code bit string.
! Dash = 3 dots
@@ -6,9 +14,12 @@ subroutine morse(msg,idat,n)
! Space between letters = 3 dots
! Space between words = 7 dots
- character*(*) msg
- integer idat(250)
+ implicit none
+
+ character(len=*), intent(in) :: msg
+ integer, intent(out) :: idat(:),n
integer*1 ic(21,38)
+ integer i,j,jj,k,msglen,nmax
data ic/ &
1,1,1,0,1,1,1,0,1,1,1,0,1,1,1,0,1,1,1,0,20, &
1,0,1,1,1,0,1,1,1,0,1,1,1,0,1,1,1,0,0,0,18, &
@@ -48,7 +59,6 @@ subroutine morse(msg,idat,n)
1,1,1,0,1,1,1,0,1,0,1,0,0,0,0,0,0,0,0,0,12, &
1,1,1,0,1,0,1,0,1,1,1,0,1,0,0,0,0,0,0,0,14, &
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2/ !Incremental word space
- save
msglen=len(msg)
idat=0
@@ -56,15 +66,24 @@ subroutine morse(msg,idat,n)
do k=1,msglen
jj=ichar(msg(k:k))
if(jj.ge.97 .and. jj.le.122) jj=jj-32 !Convert lower to upper case
- if(jj.ge.48 .and. jj.le.57) j=jj-48 !Numbers
- if(jj.ge.65 .and. jj.le.90) j=jj-55 !Letters
- if(jj.eq.47) j=36 !Slash (/)
- if(jj.eq.32) j=37 !Word space
+ if(jj.ge.48 .and. jj.le.57) then
+ j=jj-48 !Numbers
+ else if(jj.ge.65 .and. jj.le.90) then
+ j=jj-55 !Letters
+ else if(jj.eq.47) then
+ j=36 !Slash (/)
+ else if(jj.eq.32) then
+ j=37 !Word space
+ else
+ idat=0
+ n=0
+ return
+ endif
j=j+1
! Insert this character
nmax=ic(21,j)
- if (n + nmax + 4 .gt. size (idat)) exit
+ if (n + nmax + 6 .gt. size (idat)) exit
do i=1,nmax
n=n+1
idat(n)=ic(i,j)
@@ -84,4 +103,17 @@ subroutine morse(msg,idat,n)
enddo
return
+end subroutine encode_morse
+
+end module morse_encoder
+
+subroutine morse(msg,idat,n)
+
+ use morse_encoder, only: encode_morse
+ implicit none
+
+ character(len=*), intent(in) :: msg
+ integer, intent(out) :: idat(250),n
+ call encode_morse(msg,idat,n)
+
end subroutine morse
diff --git a/lib/msk144_freq_search.f90 b/lib/msk144_freq_search.f90
index 5029816a..5268851b 100644
--- a/lib/msk144_freq_search.f90
+++ b/lib/msk144_freq_search.f90
@@ -1,9 +1,11 @@
subroutine msk144_freq_search(cdat,fc,if1,if2,delf,nframes,navmask,cb, &
cdat2,xmax,bestf,cs,xccs)
- parameter (NSPM=864,NZ=7*NSPM)
- complex cdat(NZ)
- complex cdat2(NZ)
+ use, intrinsic :: ieee_arithmetic, only: ieee_is_finite
+
+ parameter (NSPM=864)
+ complex cdat(NSPM*nframes)
+ complex cdat2(NSPM*nframes)
complex c(NSPM) !Coherently averaged complex data
complex ct2(2*NSPM)
complex cs(NSPM)
@@ -13,7 +15,13 @@ subroutine msk144_freq_search(cdat,fc,if1,if2,delf,nframes,navmask,cb, &
real xccs(0:NSPM-1)
integer navmask(nframes) !Tells which frames to average
- navg=sum(navmask)
+ xmax=0.0
+ bestf=0.0
+ cs=0.0
+ xccs=0.0
+
+ navg=sum(navmask)
+ if(navg.le.0 .or. if1.gt.if2) return
n=nframes*NSPM
fac=1.0/(48.0*sqrt(float(navg)))
@@ -37,8 +45,10 @@ subroutine msk144_freq_search(cdat,fc,if1,if2,delf,nframes,navmask,cb, &
enddo
xcc=abs(cc)
+ if(.not.all(ieee_is_finite(xcc))) cycle
xb=maxval(xcc)*fac
- if(xb.gt.xmax) then
+ if(.not.ieee_is_finite(xb)) cycle
+ if(ifr.eq.if1 .or. xb.gt.xmax) then
xmax=xb
bestf=ferr
cs=c
diff --git a/lib/msk144code.f90 b/lib/msk144code.f90
index 2cb4d6a4..ffbc9acc 100644
--- a/lib/msk144code.f90
+++ b/lib/msk144code.f90
@@ -6,6 +6,7 @@ program msk144code
use packjt77
character*77 c77
character msg*37,msgsent*37,bad*1,msgtype*18
+ integer pack_status
integer*4 i4tone(144)
include 'msk144_testmsg.f90'
@@ -36,7 +37,17 @@ program msk144code
call genmsk_128_90(msg,ichk,msgsent,i4tone,itype)
i3=-1
n3=-1
- call pack77(msg,i3,n3,c77)
+ if(msg(1:1).ne.'@' .and. itype.ne.7) then
+ if(trim(msgsent).eq.'*** bad message ***') then
+ print*,'Cannot encode message: ',trim(msg)
+ stop 1
+ endif
+ call pack77(msgsent,i3,n3,c77,status=pack_status)
+ if(pack_status.ne.PACK77_STATUS_ENCODED) then
+ print*,'Cannot encode message: ',trim(msg)
+ stop 1
+ endif
+ endif
msgtype=""
if(i3.eq.0) then
if(n3.eq.0) msgtype="Free text"
diff --git a/lib/msk144sim.f90 b/lib/msk144sim.f90
index 5a4f3cb5..b0ed8873 100644
--- a/lib/msk144sim.f90
+++ b/lib/msk144sim.f90
@@ -86,7 +86,7 @@ program msk144sim
do ifile=1,nfiles !Loop over requested number of files
write(fname,1002) ifile !Output filename
1002 format('000000_',i6.6)
- open(10,file=fname(1:13)//'.wav',access='stream',status='unknown')
+ open(10,file=fname(1:13)//'.wav',access='stream',status='replace')
wave=0.0
iwave=0
diff --git a/lib/msk144spd.f90 b/lib/msk144spd.f90
index 2bc6dcfe..3ff5e12c 100644
--- a/lib/msk144spd.f90
+++ b/lib/msk144spd.f90
@@ -4,7 +4,9 @@ subroutine msk144spd(cbig,n,ntol,nsuccess,msgreceived,fc,fret,tret,navg,ct, &
! MSK144 short-ping-decoder
use packjt77
+ use msk_spectrum, only: msk_clip_spectrum_window,msk_peak_offset
use timer_module, only: timer
+ use, intrinsic :: ieee_arithmetic, only: ieee_is_finite
parameter (NSPM=864, MAXSTEPS=100, NFFT=NSPM, MAXCAND=5, NPATTERNS=6)
character*37 msgreceived
@@ -20,6 +22,7 @@ subroutine msk144spd(cbig,n,ntol,nsuccess,msgreceived,fc,fret,tret,navg,ct, &
integer navmask(3)
integer nstart(MAXCAND)
logical ismask(NFFT)
+ logical high_window_usable,low_window_usable
real detmet(-2:MAXSTEPS+3)
real detmet2(-2:MAXSTEPS+3)
real detfer(MAXSTEPS)
@@ -29,7 +32,8 @@ subroutine msk144spd(cbig,n,ntol,nsuccess,msgreceived,fc,fret,tret,navg,ct, &
real softbits(144)
real tonespec(NFFT)
real tpat(NPATTERNS)
- real*8 dt, df, fs, pi, twopi
+ real*8 dt,df,fs,pi,twopi,nfhi,nflo
+ real*8 ihlo_requested,ihhi_requested,illo_requested,ilhi_requested
logical first
data first/.true./
data navpatterns/ &
@@ -43,6 +47,10 @@ subroutine msk144spd(cbig,n,ntol,nsuccess,msgreceived,fc,fret,tret,navg,ct, &
save df,first,fs,pi,twopi,dt,tframe,rcw
+ nsuccess=0
+ msgreceived=' '
+ if(n.lt.3*NSPM .or. ntol.lt.0 .or. .not.ieee_is_finite(fc)) return
+
if(first) then
nmatchedfilter=1
! define half-sine pulse and raised-cosine edge window
@@ -62,16 +70,21 @@ subroutine msk144spd(cbig,n,ntol,nsuccess,msgreceived,fc,fret,tret,navg,ct, &
endif
! fill the detmet, detferr arrays
- nstep=(n-NSPM)/216 ! 72ms/4=18ms steps
+ nstep=min(MAXSTEPS,(n-NSPM)/216) ! 72ms/4=18ms steps
detmet=0
detmet2=0
detfer=-999.99
- nfhi=2*(fc+500)
- nflo=2*(fc-500)
- ihlo=nint((nfhi-2*ntol)/df) + 1
- ihhi=nint((nfhi+2*ntol)/df) + 1
- illo=nint((nflo-2*ntol)/df) + 1
- ilhi=nint((nflo+2*ntol)/df) + 1
+ nfhi=2d0*(dble(fc)+500d0)
+ nflo=2d0*(dble(fc)-500d0)
+ ihlo_requested=(nfhi-2d0*dble(ntol))/df + 1d0
+ ihhi_requested=(nfhi+2d0*dble(ntol))/df + 1d0
+ illo_requested=(nflo-2d0*dble(ntol))/df + 1d0
+ ilhi_requested=(nflo+2d0*dble(ntol))/df + 1d0
+ call msk_clip_spectrum_window(NFFT,ihlo_requested,ihhi_requested,ihlo,ihhi, &
+ high_window_usable)
+ call msk_clip_spectrum_window(NFFT,illo_requested,ilhi_requested,illo,ilhi, &
+ low_window_usable)
+ if(.not.high_window_usable .or. .not.low_window_usable) return
i2000=nint(nflo/df) + 1
i4000=nint(nfhi/df) + 1
do istp=1,nstep
@@ -94,7 +107,7 @@ subroutine msk144spd(cbig,n,ntol,nsuccess,msgreceived,fc,fret,tret,navg,ct, &
ismask(ihlo:ihhi)=.true. ! high tone search window
iloc=maxloc(tonespec,ismask)
ihpk=iloc(1)
- deltah=-real( (ctmp(ihpk-1)-ctmp(ihpk+1)) / (2*ctmp(ihpk)-ctmp(ihpk-1)-ctmp(ihpk+1)) )
+ deltah=msk_peak_offset(ctmp,ihpk)
ah=tonespec(ihpk)
ahavp=(sum(tonespec,ismask)-ah)/count(ismask)
trath=ah/(ahavp+0.01)
@@ -102,7 +115,7 @@ subroutine msk144spd(cbig,n,ntol,nsuccess,msgreceived,fc,fret,tret,navg,ct, &
ismask(illo:ilhi)=.true. ! window for low tone
iloc=maxloc(tonespec,ismask)
ilpk=iloc(1)
- deltal=-real( (ctmp(ilpk-1)-ctmp(ilpk+1)) / (2*ctmp(ilpk)-ctmp(ilpk-1)-ctmp(ilpk+1)) )
+ deltal=msk_peak_offset(ctmp,ilpk)
al=tonespec(ilpk)
alavp=(sum(tonespec,ismask)-al)/count(ismask)
tratl=al/(alavp+0.01)
@@ -121,6 +134,7 @@ subroutine msk144spd(cbig,n,ntol,nsuccess,msgreceived,fc,fret,tret,navg,ct, &
call indexx(detmet(1:nstep),nstep,indices) !find median of detection metric vector
xmed=detmet(indices(nstep/4))
+ if(xmed.le.0.0 .or. .not.ieee_is_finite(xmed)) return
detmet=detmet/xmed ! noise floor of detection metric is 1.0
ndet=0
@@ -152,8 +166,6 @@ subroutine msk144spd(cbig,n,ntol,nsuccess,msgreceived,fc,fret,tret,navg,ct, &
enddo
endif
- nsuccess=0
- msgreceived=' '
npeaks=2
ntol0=8
deltaf=2.0
diff --git a/lib/msk144sync.f90 b/lib/msk144sync.f90
index cfcd8c92..ccbb1c2d 100644
--- a/lib/msk144sync.f90
+++ b/lib/msk144sync.f90
@@ -67,7 +67,7 @@ subroutine msk144sync(cdat,nframes,ntol,delf,navmask,npeaks,fc,fest, &
if2=if1+nstep-1
if(id.eq.nthreads) if2=nint(ntol/delf)
call msk144_freq_search(cdat,fc,if1,if2,delf,nframes,navmask,cb, &
- cdat2(1,id),xm(id),bf(id),cs(1,id),xccs(1,id))
+ cdat2(1,id),xm(id),bf(id),cs(1,id),xccs(:,id))
!$OMP END PARALLEL
xmax=xm(1)
diff --git a/lib/msk40_freq_search.f90 b/lib/msk40_freq_search.f90
index 97f74f5e..6645c97b 100644
--- a/lib/msk40_freq_search.f90
+++ b/lib/msk40_freq_search.f90
@@ -1,9 +1,11 @@
subroutine msk40_freq_search(cdat,fc,if1,if2,delf,nframes,navmask,cb, &
cdat2,xmax,bestf,cs,xccs)
- parameter (NSPM=240,NZ=7*NSPM)
- complex cdat(NZ)
- complex cdat2(NZ)
+ use, intrinsic :: ieee_arithmetic, only: ieee_is_finite
+
+ parameter (NSPM=240)
+ complex cdat(NSPM*nframes)
+ complex cdat2(NSPM*nframes)
complex c(NSPM) !Coherently averaged complex data
complex ct2(2*NSPM)
complex cs(NSPM)
@@ -13,7 +15,13 @@ subroutine msk40_freq_search(cdat,fc,if1,if2,delf,nframes,navmask,cb, &
real xccs(0:NSPM-1)
integer navmask(nframes) !Tells which frames to average
- navg=sum(navmask)
+ xmax=0.0
+ bestf=0.0
+ cs=0.0
+ xccs=0.0
+
+ navg=sum(navmask)
+ if(navg.le.0 .or. if1.gt.if2) return
n=nframes*NSPM
! fac=1.0/(48.0*sqrt(float(navg)))
fac=1.0/(24.0*sqrt(float(navg)))
@@ -37,8 +45,10 @@ subroutine msk40_freq_search(cdat,fc,if1,if2,delf,nframes,navmask,cb, &
enddo
xcc=abs(cc)
+ if(.not.all(ieee_is_finite(xcc))) cycle
xb=maxval(xcc)*fac
- if(xb.gt.xmax) then
+ if(.not.ieee_is_finite(xb)) cycle
+ if(ifr.eq.if1 .or. xb.gt.xmax) then
xmax=xb
bestf=ferr
cs=c
diff --git a/lib/msk40spd.f90 b/lib/msk40spd.f90
index 63532ae9..65321849 100644
--- a/lib/msk40spd.f90
+++ b/lib/msk40spd.f90
@@ -3,7 +3,9 @@ subroutine msk40spd(cbig,n,ntol,mycall,hiscall,bswl,nhasharray, &
! msk40 short-ping-decoder
use packjt77
+ use msk_spectrum, only: msk_clip_spectrum_window,msk_peak_offset
use timer_module, only: timer
+ use, intrinsic :: ieee_arithmetic, only: ieee_is_finite
parameter (NSPM=240, MAXSTEPS=150, NFFT=NSPM, MAXCAND=5, NPATTERNS=6)
character*12 mycall,hiscall
@@ -20,6 +22,7 @@ subroutine msk40spd(cbig,n,ntol,mycall,hiscall,bswl,nhasharray, &
integer navmask(3)
integer nstart(MAXCAND)
logical ismask(NFFT)
+ logical high_window_usable,low_window_usable
logical*1 bswl
real detmet(-2:MAXSTEPS+3)
real detmet2(-2:MAXSTEPS+3)
@@ -29,7 +32,8 @@ subroutine msk40spd(cbig,n,ntol,mycall,hiscall,bswl,nhasharray, &
real snrs(MAXCAND)
real tonespec(NFFT)
real tpat(NPATTERNS)
- real*8 dt, df, fs, pi, twopi
+ real*8 dt,df,fs,pi,twopi,nfhi,nflo
+ real*8 ihlo_requested,ihhi_requested,illo_requested,ilhi_requested
logical first
data first/.true./
data navpatterns/ &
@@ -42,6 +46,10 @@ subroutine msk40spd(cbig,n,ntol,mycall,hiscall,bswl,nhasharray, &
data tpat/1.5,0.5,2.5,1.0,2.0,1.5/
save df,first,fs,pi,twopi,dt,tframe,rcw
+ nsuccess=0
+ msgreceived=' '
+ if(n.lt.3*NSPM .or. ntol.lt.0 .or. .not.ieee_is_finite(fc)) return
+
if(first) then
nmatchedfilter=1
! define half-sine pulse and raised-cosine edge window
@@ -62,16 +70,21 @@ subroutine msk40spd(cbig,n,ntol,mycall,hiscall,bswl,nhasharray, &
! fill the detmet, detferr arrays
- nstep=(n-NSPM)/60 ! 20ms/4=5ms steps
+ nstep=min(MAXSTEPS,(n-NSPM)/60) ! 20ms/4=5ms steps
detmet=0
detmet2=0
detfer=-999.99
- nfhi=2*(fc+500)
- nflo=2*(fc-500)
- ihlo=nint((nfhi-2*ntol)/df)+1
- ihhi=nint((nfhi+2*ntol)/df)+1
- illo=nint((nflo-2*ntol)/df)+1
- ilhi=nint((nflo+2*ntol)/df)+1
+ nfhi=2d0*(dble(fc)+500d0)
+ nflo=2d0*(dble(fc)-500d0)
+ ihlo_requested=(nfhi-2d0*dble(ntol))/df + 1d0
+ ihhi_requested=(nfhi+2d0*dble(ntol))/df + 1d0
+ illo_requested=(nflo-2d0*dble(ntol))/df + 1d0
+ ilhi_requested=(nflo+2d0*dble(ntol))/df + 1d0
+ call msk_clip_spectrum_window(NFFT,ihlo_requested,ihhi_requested,ihlo,ihhi, &
+ high_window_usable)
+ call msk_clip_spectrum_window(NFFT,illo_requested,ilhi_requested,illo,ilhi, &
+ low_window_usable)
+ if(.not.high_window_usable .or. .not.low_window_usable) return
i2000=nint(nflo/df)+1
i4000=nint(nfhi/df)+1
do istp=1,nstep
@@ -94,7 +107,7 @@ subroutine msk40spd(cbig,n,ntol,mycall,hiscall,bswl,nhasharray, &
ismask(ihlo:ihhi)=.true. ! high tone search window
iloc=maxloc(tonespec,ismask)
ihpk=iloc(1)
- deltah=-real( (ctmp(ihpk-1)-ctmp(ihpk+1)) / (2*ctmp(ihpk)-ctmp(ihpk-1)-ctmp(ihpk+1)) )
+ deltah=msk_peak_offset(ctmp,ihpk)
ah=tonespec(ihpk)
ahavp=(sum(tonespec,ismask)-ah)/count(ismask)
trath=ah/(ahavp+0.01)
@@ -102,7 +115,7 @@ subroutine msk40spd(cbig,n,ntol,mycall,hiscall,bswl,nhasharray, &
ismask(illo:ilhi)=.true. ! window for low tone
iloc=maxloc(tonespec,ismask)
ilpk=iloc(1)
- deltal=-real( (ctmp(ilpk-1)-ctmp(ilpk+1)) / (2*ctmp(ilpk)-ctmp(ilpk-1)-ctmp(ilpk+1)) )
+ deltal=msk_peak_offset(ctmp,ilpk)
al=tonespec(ilpk)
alavp=(sum(tonespec,ismask)-al)/count(ismask)
tratl=al/(alavp+0.01)
@@ -121,6 +134,7 @@ subroutine msk40spd(cbig,n,ntol,mycall,hiscall,bswl,nhasharray, &
call indexx(detmet(1:nstep),nstep,indices) !find median of detection metric vector
xmed=detmet(indices(nstep/4))
+ if(xmed.le.0.0 .or. .not.ieee_is_finite(xmed)) return
detmet=detmet/xmed ! noise floor of detection metric is 1.0
ndet=0
@@ -152,8 +166,6 @@ subroutine msk40spd(cbig,n,ntol,mycall,hiscall,bswl,nhasharray, &
enddo
endif
- nsuccess=0
- msgreceived=' '
npeaks=2
ntol0=29
deltaf=7.2
diff --git a/lib/msk40sync.f90 b/lib/msk40sync.f90
index 5a2ca1e7..888673f7 100644
--- a/lib/msk40sync.f90
+++ b/lib/msk40sync.f90
@@ -27,6 +27,13 @@ subroutine msk40sync(cdat,nframes,ntol,delf,navmask,npeaks,fc,fest, &
data s8r/1,0,1,1,0,0,0,1/
save first,cb,fs,pi,twopi,dt,s8r,pp
+ interface
+ subroutine wsjt_tsan_acquire_msk40_sync() bind(C)
+ end subroutine wsjt_tsan_acquire_msk40_sync
+ subroutine wsjt_tsan_release_msk40_sync() bind(C)
+ end subroutine wsjt_tsan_release_msk40_sync
+ end interface
+
if(first) then
pi=4.0*atan(1.0)
twopi=8.0*atan(1.0)
@@ -67,10 +74,13 @@ subroutine msk40sync(cdat,nframes,ntol,delf,navmask,npeaks,fc,fest, &
if2=if1+nstep-1
if(id.eq.nthreads) if2=nint(ntol/delf)
call msk40_freq_search(cdat,fc,if1,if2,delf,nframes,navmask,cb, &
- cdat2(1,id),xm(id),bf(id),cs(1,id),xccs(1,id))
+ cdat2(1,id),xm(id),bf(id),cs(1,id),xccs(:,id))
+ ! GCC TSan does not observe libgomp's implicit barrier.
+ call wsjt_tsan_release_msk40_sync()
! write(73,3002) id,if1,if2,nfreqs,nthreads,bf(id),xm(id)
!3002 format(5i5,2f10.3)
!$OMP END PARALLEL
+ call wsjt_tsan_acquire_msk40_sync()
xmax=xm(1)
fest=fc+bf(1)
diff --git a/lib/msk_spectrum.f90 b/lib/msk_spectrum.f90
new file mode 100644
index 00000000..2339105c
--- /dev/null
+++ b/lib/msk_spectrum.f90
@@ -0,0 +1,59 @@
+module msk_spectrum
+ use, intrinsic :: iso_fortran_env, only: real64
+ use, intrinsic :: ieee_arithmetic, only: ieee_is_finite
+ implicit none
+ private
+
+ public :: msk_clip_spectrum_window
+ public :: msk_peak_offset
+
+contains
+
+ pure subroutine msk_clip_spectrum_window(nfft,requested_lo,requested_hi, &
+ lo,hi,usable)
+ integer, intent(in) :: nfft
+ real(real64), intent(in) :: requested_lo,requested_hi
+ integer, intent(out) :: lo,hi
+ logical, intent(out) :: usable
+
+ lo=1
+ hi=0
+ usable=.false.
+ if(nfft.lt.1) return
+ if(.not.ieee_is_finite(requested_lo) .or. &
+ .not.ieee_is_finite(requested_hi)) return
+ if(requested_lo.gt.requested_hi) return
+ if(requested_hi.lt.0.5_real64 .or. &
+ requested_lo.ge.real(nfft,real64)+0.5_real64) return
+
+ lo=nint(max(1.0_real64,min(real(nfft,real64),requested_lo)))
+ hi=nint(max(1.0_real64,min(real(nfft,real64),requested_hi)))
+ usable=lo.le.hi
+ if(.not.usable) then
+ lo=1
+ hi=0
+ endif
+ end subroutine msk_clip_spectrum_window
+
+ pure real function msk_peak_offset(spectrum,peak_bin) result(offset)
+ complex, intent(in) :: spectrum(:)
+ integer, intent(in) :: peak_bin
+ complex :: curvature
+ real :: candidate,scale
+
+ offset=0.0
+ if(peak_bin.le.lbound(spectrum,1) .or. &
+ peak_bin.ge.ubound(spectrum,1)) return
+
+ curvature=2.0*spectrum(peak_bin)-spectrum(peak_bin-1)- &
+ spectrum(peak_bin+1)
+ scale=max(abs(spectrum(peak_bin-1)),abs(spectrum(peak_bin)), &
+ abs(spectrum(peak_bin+1)))
+ if(scale.le.0.0) return
+ if(abs(curvature).le.epsilon(scale)*scale) return
+
+ candidate=-real((spectrum(peak_bin-1)-spectrum(peak_bin+1))/curvature)
+ if(ieee_is_finite(candidate)) offset=candidate
+ end function msk_peak_offset
+
+end module msk_spectrum
diff --git a/lib/options.f90 b/lib/options.f90
index f12311ed..bc2cdf97 100644
--- a/lib/options.f90
+++ b/lib/options.f90
@@ -106,6 +106,7 @@ contains
integer :: chrpos, length, st, id = 0
character :: chr
+ character(len=100) :: longopt_name
logical :: long
if (cnt == 0) cnt = command_argument_count()
@@ -152,6 +153,7 @@ contains
end if
chr = longopts(id)%chr
+ longopt_name = longopts(id)%name
! check if option requires an argument
if (.not. longopts(id)%has_arg) then
@@ -248,7 +250,7 @@ contains
// " requires an argument"
else
write (error_unit, *) "error: option --" &
- // trim(longopts(id)%name) // " requires an argument"
+ // trim(longopt_name) // " requires an argument"
end if
end select
diff --git a/lib/osd128_90.f90 b/lib/osd128_90.f90
index 75082bf5..bb7a52ba 100644
--- a/lib/osd128_90.f90
+++ b/lib/osd128_90.f90
@@ -110,7 +110,8 @@ subroutine osd128_90(llr,apmask,ndeep,message77,cw,nhardmin,dmin)
ntotal=0
nrejected=0
- if(ndeep.eq.0) goto 998 ! norder=0
+ nord=0
+ if(ndeep.le.0) goto 998 ! norder=0
if(ndeep.gt.5) ndeep=5
if( ndeep.eq. 1) then
nord=1
diff --git a/lib/packjt.f90 b/lib/packjt.f90
index 2e51d78a..4bcead11 100644
--- a/lib/packjt.f90
+++ b/lib/packjt.f90
@@ -470,10 +470,10 @@ subroutine packbits(dbits,nsymd,m0,sym)
if(c3.eq.'OOO ') c3=' ' !Strip out the OOO flag
call getpfx1(c1,k1,nv2a)
if(nv2a.ge.4) go to 10
- call packcall(c1,nc1,text1)
+ call packcall(c1(1:6),nc1,text1)
if(text1) go to 10
call getpfx1(c2,k2,nv2b)
- call packcall(c2,nc2,text2)
+ call packcall(c2(1:6),nc2,text2)
if(text2) go to 10
if(nv2a.eq.2 .or. nv2a.eq.3 .or. nv2b.eq.2 .or. nv2b.eq.3) then
if(k1.lt.0 .or. k2.lt.0 .or. k1*k2.ne.0) go to 10
@@ -801,6 +801,12 @@ subroutine packbits(dbits,nsymd,m0,sym)
lrof=len_trim(rof)
ispfx=(llof.gt.0 .and. llof.le.4)
issfx=(lrof.gt.0 .and. lrof.le.3)
+ do i=1,llof
+ if(lof(i:i).lt.' ') ispfx=.false.
+ enddo
+ do i=1,lrof
+ if(rof(i:i).lt.' ') issfx=.false.
+ enddo
invalid=.not.(ispfx.or.issfx)
if(ispfx.and.issfx) then
if(llof.lt.3) issfx=.false.
@@ -817,6 +823,7 @@ subroutine packbits(dbits,nsymd,m0,sym)
if(invalid) then
k=-1
+ callsign=callsign0
else
if(ispfx) then
tpfx=lof(1:4)
@@ -936,8 +943,7 @@ subroutine packbits(dbits,nsymd,m0,sym)
else if(c.ge.' ') then
n=36
else
- Print*,'Invalid character in callsign ',c,' ',ichar(c)
- stop
+ n=-1
endif
nchar=n
@@ -980,7 +986,7 @@ subroutine packpfx(call1,n1,ng,nadd)
if(call1(i1+2:i1+2).eq.' ') then
! Single-character add-on suffix (maybe also fourth suffix letter?)
call0=call1(:i1-1)
- call packcall(call0,n1,text)
+ call packcall(call0(1:6),n1,text)
nadd=1
nc=ichar(call1(i1+1:i1+1))
if(nc.ge.48 .and. nc.le.57) then
@@ -995,7 +1001,7 @@ subroutine packpfx(call1,n1,ng,nadd)
else if(call1(i1+3:i1+3).eq.' ') then
! Two-character numerical suffix, /10 to /99
call0=call1(:i1-1)
- call packcall(call0,n1,text)
+ call packcall(call0(1:6),n1,text)
nadd=1
n=10*(ichar(call1(i1+1:i1+1))-48) + ichar(call1(i1+2:i1+2)) - 48
nadd=1
@@ -1006,7 +1012,7 @@ subroutine packpfx(call1,n1,ng,nadd)
if(pfx(3:3).eq.' ') pfx=' '//pfx(1:2)
if(pfx(3:3).eq.' ') pfx=' '//pfx(1:2)
call0=call1(i1+1:)
- call packcall(call0,n1,text)
+ call packcall(call0(1:6),n1,text)
ng=0
do i=1,3
diff --git a/lib/plotsave.f90 b/lib/plotsave.f90
index ee1a41cf..4e144264 100644
--- a/lib/plotsave.f90
+++ b/lib/plotsave.f90
@@ -1,7 +1,8 @@
subroutine plotsave(swide,nw,nh,irow)
- real, dimension(:,:), allocatable :: sw
+ real, dimension(:,:), allocatable :: sw,sw_old
real swide(0:nw-1)
+ integer mw,mh
data nw0/-1/,nh0/-1/
save nw0,nh0,sw
@@ -11,10 +12,19 @@ subroutine plotsave(swide,nw,nh,irow)
endif
if(nw.ne.nw0 .or. nh.ne.nh0 .or. (.not.allocated(sw))) then
- if(allocated(sw)) deallocate(sw)
-! if(nw0.ne.-1) deallocate(sw)
- allocate(sw(0:nw-1,0:nh-1))
- sw=0.
+ if(allocated(sw)) then
+! Resize: keep the overlapping history instead of blanking the waterfall.
+ call move_alloc(sw,sw_old)
+ allocate(sw(0:nw-1,0:nh-1))
+ sw=0.
+ mw=min(nw,nw0)
+ mh=min(nh,nh0)
+ sw(0:mw-1,0:mh-1)=sw_old(0:mw-1,0:mh-1)
+ deallocate(sw_old)
+ else
+ allocate(sw(0:nw-1,0:nh-1))
+ sw=0.
+ endif
nw0=nw
nh0=nh
endif
diff --git a/lib/print_version.c b/lib/print_version.c
new file mode 100644
index 00000000..1cf1215f
--- /dev/null
+++ b/lib/print_version.c
@@ -0,0 +1,16 @@
+#include <stdio.h>
+
+#include "scs_version.h"
+#include "wsjtx_config.h"
+
+void print_version(const char *prog_name)
+{
+ printf(" Program: %s %d.%d.%d%s", prog_name,
+ PROJECT_VERSION_MAJOR, PROJECT_VERSION_MINOR, PROJECT_VERSION_PATCH,
+ BUILD_TYPE_REVISION);
+ if (SCS_VERSION_STR[0] != '\0') {
+ printf(" (revision %s)\n", SCS_VERSION_STR);
+ } else {
+ puts(" (revision unavailable)");
+ }
+}
diff --git a/lib/ptt.c b/lib/ptt.c
index 902193fd..42854cc5 100644
--- a/lib/ptt.c
+++ b/lib/ptt.c
@@ -5,8 +5,8 @@ int ptt_(int *nport, int *ntx, int *iptt)
{
static HANDLE hFile;
static int open=0;
- char s[10];
- int i3=1,i4=1,i5=1,i6=1,i9=1,i00=1;
+ char s[32];
+ int i3=1,i4=1,i5=1,i6=1,i9=1,i00=1,n;
if(*nport==0) {
*iptt=*ntx;
@@ -14,7 +14,8 @@ int ptt_(int *nport, int *ntx, int *iptt)
}
if(*ntx && (!open)) {
- sprintf(s,"\\\\.\\COM%d",*nport);
+ n=snprintf(s,sizeof s,"\\\\.\\COM%d",*nport);
+ if(n < 0 || n >= (int) sizeof s) return 1;
hFile=CreateFile(TEXT(s),GENERIC_WRITE,0,NULL,OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,NULL);
if(hFile==INVALID_HANDLE_VALUE) {
diff --git a/lib/q65_decode.f90 b/lib/q65_decode.f90
index 5c9b0237..e06d9972 100644
--- a/lib/q65_decode.f90
+++ b/lib/q65_decode.f90
@@ -1,10 +1,13 @@
module q65_decode
+ use q65_workspace, only: q65_workspace_type
+
integer nsnr0,nfreq0
real xdt0
character msg0*37,cq0*3
type :: q65_decoder
+ type(q65_workspace_type) :: workspace
procedure(q65_decode_callback), pointer :: callback
contains
procedure :: decode
@@ -12,7 +15,7 @@ module q65_decode
abstract interface
subroutine q65_decode_callback (this,nutc,snr1,nsnr,dt,freq, &
- decoded,idec,nused,ntrperiod)
+ decoded,idec,nused,ntrperiod,iflagdec)
import q65_decoder
implicit none
class(q65_decoder), intent(inout) :: this
@@ -25,6 +28,7 @@ module q65_decode
integer, intent(in) :: idec
integer, intent(in) :: nused
integer, intent(in) :: ntrperiod
+ integer, intent(in) :: iflagdec !Recovered spare 78th bit (see genq65/q65_ap)
end subroutine q65_decode_callback
end interface
@@ -33,7 +37,7 @@ contains
subroutine decode(this,callback,iwave,nqd0,nutc,ntrperiod,nsubmode,nfqso, &
ntol,ndepth,nfa0,nfb0,lclearave,single_decode,lagain,max_drift0, &
lnewdat0,emedelay,mycall,hiscall,hisgrid,nQSOprogress,ncontest, &
- lapcqonly,navg0,nqf)
+ lq65pileup,lapcqonly,navg0,nqf)
! Top-level routine that organizes the decoding of Q65 signals
! Input: iwave Raw data, i*2
@@ -47,6 +51,7 @@ contains
! emedelay Sync search extended to cover EME delays
! nQSOprogress Auto-sequencing state for the present QSO
! ncontest Supported contest type
+! lq65pileup Q65 Pileup AP flag policy
! lapcqonly Flag to use AP only for CQ calls
! Output: sent to the callback routine for display to user
@@ -58,7 +63,7 @@ contains
use types
parameter (NMAX=300*12000) !Max TRperiod is 300 s
- parameter (MAX_CALLERS=40) !For multiple q3 decodes in NA VHf Contest mode
+ parameter (MAX_CALLERS=50) !For multiple q3 decodes in NA VHF Contest mode
class(q65_decoder), intent(inout) :: this
@@ -81,7 +86,8 @@ contains
integer nqf(20)
integer stageno !Added by W3SZ
integer time
- logical lclearave,lnewdat0,lapcqonly,unpk77_success
+ integer iflagdec !Recovered spare 78th bit
+ logical lclearave,lnewdat0,lq65pileup,lapcqonly,unpk77_success
logical single_decode,lagain
complex c00(0:3600000) !Analytic signal, 6000 Sa/s
type(q3list) callers(MAX_CALLERS)
@@ -233,7 +239,7 @@ contains
apsymbols=0
if(ipass.ge.1) then
! Subsequent passes use AP information appropiate for nQSOprogress
- call q65_ap(nQSOprogress,ipass,ncontest,lapcqonly,iaptype, &
+ call q65_ap(nQSOprogress,ipass,ncontest,lq65pileup,lapcqonly,iaptype, &
apsym0,apmask1,apsymbols1)
write(c78,1050) apmask1
1050 format(78i1)
@@ -244,7 +250,7 @@ contains
endif
call timer('q65loop1',0)
- call q65_loops(c00,npts/2,nsps/2,nsubmode,ndepth,jpk0, &
+ call q65_loops(this%workspace,c00,npts/2,nsps/2,nsubmode,ndepth,jpk0, &
xdt,f0,iaptype,xdt1,f1,snr2,dat4,idec)
call timer('q65loop1',1)
if(idec.ge.0) then
@@ -312,6 +318,7 @@ contains
! 3: Decode with AP for "MyCall DxCall ?"
! Unpack decoded message for display to user
+ iflagdec=iand(dat4(13),1) !Recover the spare 78th bit before it's shifted away
write(c77,1000) dat4(1:12),dat4(13)/2
1000 format(12b6.6,b5.5)
call unpack77(c77,1,decoded,unpk77_success) !Unpack to get decoded
@@ -319,7 +326,7 @@ contains
do i=1,ndecodes
if(decodes(i).eq.decoded) idupe=1
enddo
- if(idupe.eq.0) then
+ if(idupe.eq.0 .and. unpk77_success) then
ndecodes=min(ndecodes+1,100)
decodes(ndecodes)=decoded
f0decodes(ndecodes)=f0dec
@@ -327,7 +334,7 @@ contains
call q65_snr(dat4,dtdec,f0dec,mode_q65,snr2)
nsnr=nint(snr2)
call this%callback(nutc,snr1,nsnr,dtdec,f0dec,decoded, &
- idec,nused,ntrperiod)
+ idec,nused,ntrperiod,iflagdec)
if(ncontest.eq.1) then
call q65_hist2(nint(f0dec),decoded,callers,nhist2)
else
@@ -403,7 +410,7 @@ contains
apsymbols=0
if(ipass.ge.1) then
! Subsequent passes use AP information appropiate for nQSOprogress
- call q65_ap(nQSOprogress,ipass,ncontest,lapcqonly,iaptype, &
+ call q65_ap(nQSOprogress,ipass,ncontest,lq65pileup,lapcqonly,iaptype, &
apsym0,apmask1,apsymbols1)
write(c78,1050) apmask1
read(c78,1060) apmask
@@ -412,7 +419,7 @@ contains
endif
call timer('q65loop2',0)
- call q65_loops(c00,npts/2,nsps/2,nsubmode,ndepth,jpk0, &
+ call q65_loops(this%workspace,c00,npts/2,nsps/2,nsubmode,ndepth,jpk0, &
xdt,f0,iaptype,xdt1,f1,snr2,dat4,idec)
call timer('q65loop2',1)
! write(*,3001) '=e',nfqso,ntol,ndepth,xdt,f0,idec
@@ -426,20 +433,21 @@ contains
200 decoded=' '
if(idec.ge.0) then
! Unpack decoded message for display to user
+ iflagdec=iand(dat4(13),1) !Recover the spare 78th bit before it's shifted away
write(c77,1000) dat4(1:12),dat4(13)/2
call unpack77(c77,1,decoded,unpk77_success) !Unpack to get decoded
idupe=0
do i=1,ndecodes
if(decodes(i).eq.decoded) idupe=1
enddo
- if(idupe.eq.0) then
+ if(idupe.eq.0 .and. unpk77_success) then
ndecodes=min(ndecodes+1,100)
decodes(ndecodes)=decoded
f0decodes(ndecodes)=f0dec
call q65_snr(dat4,dtdec,f0dec,mode_q65,snr2)
nsnr=nint(snr2)
call this%callback(nutc,snr1,nsnr,dtdec,f0dec,decoded, &
- idec,nused,ntrperiod)
+ idec,nused,ntrperiod,iflagdec)
if(ncontest.eq.1) then
call q65_hist2(nint(f0dec),decoded,callers,nhist2)
else
diff --git a/lib/qra/q65/genq65.f90 b/lib/qra/q65/genq65.f90
index 4c555748..1705ce82 100644
--- a/lib/qra/q65/genq65.f90
+++ b/lib/qra/q65/genq65.f90
@@ -1,4 +1,4 @@
-subroutine genq65(msg0,ichk,msgsent,itone,i3,n3)
+subroutine genq65(msg0,ichk,msgsent,itone,i3,n3,iflag)
! Encodes a Q65 message to yield itone(1:85)
@@ -25,13 +25,16 @@ subroutine genq65(msg0,ichk,msgsent,itone,i3,n3)
endif
i3=-1
n3=-1
- call pack77(msg0,i3,n3,c77)
- read(c77(60:74),'(b15)') ng15
+ c77=' '
+ unpk77_success=.false.
+ call pack77_legacy_truncating_fallback(msg0,i3,n3,c77)
+ if(i3.lt.0 .or. n3.lt.0) go to 998
+ read(c77(60:74),'(b15)',err=998) ng15
if(ng15.eq.32373) c77(60:74)='111111010010011' !Message is RR73
call unpack77(c77,0,msgsent,unpk77_success) !Unpack to get msgsent
- read(c77,1001) dgen
+ read(c77,1001,err=998) dgen
1001 format(12b6.6,b5.5)
- dgen(13)=2*dgen(13) !Convert 77-bit to 78-bit payload
+ dgen(13)=2*dgen(13)+iflag !Convert 77-bit to 78-bit payload; iflag is the spare 78th bit
if(ichk.eq.1) go to 999 !Return if checking only
call q65_enc(dgen,sent) !Encode message, dgen(1:13) ==> sent(1:63)
@@ -47,5 +50,12 @@ subroutine genq65(msg0,ichk,msgsent,itone,i3,n3)
endif
enddo
+ go to 999
+998 dgen=0
+ sent=0
+ itone=0
+ i3=-1
+ n3=-1
+ msgsent='*** bad message *** '
999 return
end subroutine genq65
diff --git a/lib/qra/q65/normrnd.c b/lib/qra/q65/normrnd.c
index 90abfa42..29d7e243 100644
--- a/lib/qra/q65/normrnd.c
+++ b/lib/qra/q65/normrnd.c
@@ -33,7 +33,7 @@
#elif _SVID_SOURCE || _XOPEN_SOURCE || __unix__ || (defined (__APPLE__) && defined(__MACH__)) /* POSIX or Unix or Apple */
#include <stdlib.h>
#define rand_s(x) (*x)=(unsigned int)lrand48() // returns unsigned integers in the range 0..0x7FFFFFFF
- #define K_RAND_MAX 0x7FFFFFFF // that's the max number
+ #define K_RAND_MAX 2147483647.0f // that's the max number
// generated by lrand48
#else
#error "No good quality PRNG found"
diff --git a/lib/qra/q65/q65.c b/lib/qra/q65/q65.c
index fb08dd13..a88c1e4e 100644
--- a/lib/qra/q65/q65.c
+++ b/lib/qra/q65/q65.c
@@ -30,11 +30,12 @@
#define Q65_LLH_THRESHOLD -260.0f
// This value produce the same WER performance in decode_fullaplist
-// #define Q65_LLH_THRESHOLD -262.0f
+// #define Q65_LLH_THRESHOLD -262.0f
static int _q65_crc6(int *x, int sz);
static void _q65_crc12(int *y, int *x, int sz);
+static void _q65_mask(const qracode *pcode, float *ix, const int *mask, const int *x);
float q65_llh;
@@ -665,7 +666,12 @@ int q65_check_llh(float *llh, const int* ydec, const int nN, const int nM, const
int k;
float t = 0;
+ if (llh != NULL)
+ *llh = -INFINITY;
+
for (k=0;k<nN;k++) {
+ if (ydec[k] < 0 || ydec[k] >= nM)
+ return 0;
float x=pIntrin[ydec[k]];
if(x < 1.0e-36) x = 1.0e-36;
t+=logf(x);
@@ -805,7 +811,7 @@ int _q65_get_bits_per_symbol(const qracode *pCode)
{
return pCode->m;
}
-static void _q65_mask(const qracode *pcode, float *ix, const int *mask, const int *x)
+void _q65_mask(const qracode *pcode, float *ix, const int *mask, const int *x)
{
// mask intrinsic information ix with available a priori knowledge
diff --git a/lib/qra/q65/q65.f90 b/lib/qra/q65/q65.f90
index d73ded61..5718243c 100644
--- a/lib/qra/q65/q65.f90
+++ b/lib/qra/q65/q65.f90
@@ -9,7 +9,7 @@ module q65
integer apmask(13),apsymbols(13)
integer,dimension(22) :: isync = (/1,9,12,13,15,22,23,26,27,33,35, &
38,46,50,55,60,62,66,69,74,76,85/)
- integer codewords(63,206)
+ integer codewords(63,411) !See MAX_NCW in q65_set_list2.f90
integer ibwa,ibwb,ncw,nsps,mode_q65,nfa,nfb,nqd
integer idfbest,idtbest,ibw,ndistbest,maxiters,max_drift
integer istep,nsmo,lag1,lag2,npasses,iseq,ncand,nrc
@@ -367,7 +367,7 @@ subroutine q65_dec_q012(s3,LL,snr2,dat4,idec,decoded)
apsymbols=0
if(ipass.ge.1) then
! Subsequent passes use AP information appropiate for nQSOprogress
- call q65_ap(nQSOprogress,ipass,ncontest,lapcqonly,iaptype, &
+ call q65_ap(nQSOprogress,ipass,ncontest,.false.,lapcqonly,iaptype, &
apsym0,apmask1,apsymbols1)
write(c78,1050) apmask1
1050 format(78i1)
@@ -527,7 +527,7 @@ subroutine q65_ccf_22(s1,iz,jz,nfqso,ntol,ipk,jpk,f0,xdt,ccf2)
if(ccfmax.gt.ccfbest .and. abs(i*df-nfqso).le.ftol) then
ccfbest=ccfmax
- snrbest=snr
+! snrbest=snr ! snrbest not used. snr may be uninitialized.
ibest=i
lagbest=lagpk
idrift_best=idrift_max
@@ -848,7 +848,7 @@ subroutine q65_hist2(nfreq,msg0,callers,nhist2)
use types
use prog_args
- parameter (MAX_CALLERS=40) !For multiple q3 decodes in NA VHf Contest mode
+ parameter (MAX_CALLERS=50) !For multiple q3 decodes in NA VHF Contest mode
character*37 msg0,msg
type(q3list) callers(MAX_CALLERS)
character*6 c6
diff --git a/lib/qra/q65/q65.h b/lib/qra/q65/q65.h
index d0a04d4e..ab1b389d 100644
--- a/lib/qra/q65/q65.h
+++ b/lib/qra/q65/q65.h
@@ -34,7 +34,9 @@
// Verify loglikelihood after successful decoding
#define Q65_CHECKLLH
// Max codeword list size in q65_decode_fullaplist
-#define Q65_FULLAPLIST_SIZE 256
+// See MAX_NCW in q65_set_list2.f90 (not required to be a power of 2 --
+// this value is only ever used in a plain bounds check).
+#define Q65_FULLAPLIST_SIZE 411
// maximum number of weights for the fast-fading metric evaluation
#define Q65_FASTFADING_MAXWEIGTHS 65
@@ -113,7 +115,6 @@ int q65_esnodb_fastfading(
int _q65_get_message_length(const qracode *pCode);
int _q65_get_codeword_length(const qracode *pCode);
float _q65_get_code_rate(const qracode *pCode);
-static void _q65_mask(const qracode *pcode, float *ix, const int *mask, const int *x);
int _q65_get_alphabet_size(const qracode *pCode);
int _q65_get_bits_per_symbol(const qracode *pCode);
diff --git a/lib/qra/q65/q65_ap.f90 b/lib/qra/q65/q65_ap.f90
index 32e26a4e..e6568676 100644
--- a/lib/qra/q65/q65_ap.f90
+++ b/lib/qra/q65/q65_ap.f90
@@ -1,4 +1,4 @@
-subroutine q65_ap(nQSOprogress,ipass,ncontest,lapcqonly,iaptype, &
+subroutine q65_ap(nQSOprogress,ipass,ncontest,lq65pileup,lapcqonly,iaptype, &
apsym0,apmask,apsymbols)
integer apsym0(58),aph10(10)
@@ -6,7 +6,7 @@ subroutine q65_ap(nQSOprogress,ipass,ncontest,lapcqonly,iaptype, &
integer naptypes(0:5,4) ! (nQSOProgress, ipass) maximum of 4 passes for now
integer mcqru(29),mcqfd(29),mcqtest(29),mcqww(29)
integer mcq(29),mrrr(19),m73(19),mrr73(19)
- logical lapcqonly,first
+ logical lq65pileup,lapcqonly,first
data mcq/0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0/
data mcqru/0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,0,0,1,1,0,0/
data mcqfd/0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,1,0,0,0,1,0/
@@ -120,25 +120,31 @@ subroutine q65_ap(nQSOprogress,ipass,ncontest,lapcqonly,iaptype, &
endif
endif
- if(iaptype.eq.3) then ! MyCall,DxCall,???
+ if(iaptype.eq.3) then ! MyCall,DxCall,???
apmask=0
+! Q65 Pileup uses bit 78 for the copied-last-transmission indication.
+! Other Q65 AP decodes retain the normal known-zero bit.
if(ncontest.eq.0.or.ncontest.eq.1.or.ncontest.eq.2.or.ncontest.eq.5.or.ncontest.eq.7) then
- apmask(1:58)=1
+ apmask(1:58)=1
apsymbols(1:58)=apsym0
- apmask(75:78)=1
- apsymbols(75:78)=(/0,0,1,0/)
+ apmask(75:77)=1
+ apsymbols(75:77)=(/0,0,1/)
+ if(.not.lq65pileup) then
+ apmask(78)=1
+ apsymbols(78)=0
+ endif
else if(ncontest.eq.3) then ! Field Day
- apmask(1:56)=1
+ apmask(1:56)=1
apsymbols(1:28)=apsym0(1:28)
apsymbols(29:56)=apsym0(30:57)
- apmask(72:78)=1
- apsymbols(75:78)=0
- else if(ncontest.eq.4) then
- apmask(2:57)=1
+ apmask(72:77)=1
+ apsymbols(75:77)=0
+ else if(ncontest.eq.4) then
+ apmask(2:57)=1
apsymbols(2:29)=apsym0(1:28)
apsymbols(30:57)=apsym0(30:57)
- apmask(75:78)=1
- apsymbols(75:78)=(/0,0,1,0/)
+ apmask(75:77)=1
+ apsymbols(75:77)=(/0,0,1/)
endif
endif
diff --git a/lib/qra/q65/q65_encoding_modules.f90 b/lib/qra/q65/q65_encoding_modules.f90
index 4988dd4d..3f749d5b 100644
--- a/lib/qra/q65/q65_encoding_modules.f90
+++ b/lib/qra/q65/q65_encoding_modules.f90
@@ -164,10 +164,10 @@ subroutine get_q65crc12(mc2,ncrc1,ncrc2)
end subroutine get_q65crc12
-subroutine get_q65_tones(msg37,codeword,itone)
+subroutine get_q65_tones(msg37,codeword,itone,msgsent,success)
use packjt77
implicit none
- character*37 msg37
+ character*37 msg37,msgsent
character*77 c77
character*6 c6
integer codeword(65)
@@ -175,16 +175,36 @@ subroutine get_q65_tones(msg37,codeword,itone)
integer message(15)
integer shortcodeword(63)
integer itone(85)
- integer i,j,k
+ integer i,j,k,ios,pack_status,ng15
integer*1 mbits(90)
integer i3,n3,ncrc1,ncrc2
+ logical success,unpk77_success
data sync/1,9,12,13,15,22,23,26,27,33,35,38,46,50,55,60,62,66,69,74,76,85/
i3=-1
n3=-1
- call pack77(msg37,i3,n3,c77)
+ c77=' '
+ codeword=0
+ itone=0
+ msgsent='*** bad message *** '
+ success=.false.
+ call pack77_legacy_truncating_fallback(msg37,i3,n3,c77, &
+ status=pack_status)
+ if(pack_status.ne.PACK77_STATUS_ENCODED) return
+ read(c77(60:74),'(b15)',iostat=ios) ng15
+ if(ios.ne.0) return
+ if(ng15.eq.32373) c77(60:74)='111111010010011' !Message is RR73
+ call unpack77(c77,0,msgsent,unpk77_success)
+ if(.not.unpk77_success) then
+ msgsent='*** bad message *** '
+ return
+ endif
mbits=0
- read(c77,'(77i1)') mbits(1:77)
+ read(c77,'(77i1)',iostat=ios) mbits(1:77)
+ if(ios.ne.0) then
+ msgsent='*** bad message *** '
+ return
+ endif
! Message is 77 bits long. Add a 0 bit to create a 78-bit message and pad with
! 12 zeros to create 90-bit mbit array for CRC calculation.
@@ -216,6 +236,7 @@ subroutine get_q65_tones(msg37,codeword,itone)
itone(i)=shortcodeword(k)+1
endif
enddo
+ success=.true.
end subroutine get_q65_tones
end module q65_encoding
diff --git a/lib/qra/q65/q65_ftn_test.f90 b/lib/qra/q65/q65_ftn_test.f90
index 607d0f5b..3f5c47c0 100644
--- a/lib/qra/q65/q65_ftn_test.f90
+++ b/lib/qra/q65/q65_ftn_test.f90
@@ -21,8 +21,12 @@ program q65_ftn_test
endif
call getarg(1,msg0)
call pack77(msg0,i3,n3,c77)
+ if(i3.lt.0) then
+ print*,'Cannot pack message: ',trim(msg0)
+ go to 999
+ endif
call unpack77(c77,0,msgsent,unpk77_success) !Unpack to get msgsent
- read(c77,1000) x
+ read(c77,1000,err=990) x
1000 format(12b6.6,b5.5)
call q65_enc(x,y) !Encode message, x(1:13) ==> y(1:63)
@@ -48,4 +52,7 @@ program q65_ftn_test
write(*,1100) xdec,trim(msg)
1100 format(/'Decoded message:'/13i3,2x,a)
+ go to 999
+
+990 print*,'Cannot read packed message bits: ',trim(msg0)
999 end program q65_ftn_test
diff --git a/lib/qra/q65/q65_loops.f90 b/lib/qra/q65/q65_loops.f90
index 3220648e..4a5bc34f 100644
--- a/lib/qra/q65/q65_loops.f90
+++ b/lib/qra/q65/q65_loops.f90
@@ -1,24 +1,23 @@
-subroutine q65_loops(c00,npts2,nsps2,nsubmode,ndepth,jpk0, &
+subroutine q65_loops(workspace,c00,npts2,nsps2,nsubmode,ndepth,jpk0, &
xdt0,f0,iaptype,xdt1,f1,snr2,dat4,idec)
use packjt77
use timer_module, only: timer
use q65
+ use q65_workspace, only: q65_workspace_type
parameter (NN=63)
parameter (LN=2176*63) !LN=LL*NN; LL=64*(mode_q65+2), NN=63
+ type(q65_workspace_type), intent(inout) :: workspace
complex c00(0:npts2-1) !Analytic representation of dd(), 6000 Hz
- complex ,allocatable :: c0(:) !Ditto, with freq shift
character decoded*37
real a(3) !twkfreq params f,f1,f2
- real,allocatable :: s3(:) !Symbol spectra
integer dat4(13) !Decoded message (as 13 six-bit integers)
integer nap(0:11) !AP return codes
data nap/0,2,3,2,3,4,2,3,6,4,6,6/
LL=64*(mode_q65+2)
- allocate(s3(LL*NN))
- allocate(c0(0:npts2-1))
+ call workspace%ensure(npts2,LL)
idec=-1
ircbest=9999
irc=-99
@@ -54,18 +53,19 @@ subroutine q65_loops(c00,npts2,nsps2,nsubmode,ndepth,jpk0, &
a(1)=-(f0+0.5*baud*ndf)
! Variable 'drift' is frequency increase over full TxT. Therefore we want:
a(2)=-0.5*drift
- call twkfreq(c00,c0,npts2,6000.0,a)
+ call twkfreq(c00,workspace%c0(0:npts2-1),npts2,6000.0,a)
do idt=1,idtmax
ndt=idt/2
if(mod(idt,2).eq.0) ndt=-ndt
jpk=jpk0 + nsps2*ndt/16 !tsym/16
jpk=max(0,jpk)
jpk=min(29000,jpk)
- call spec64(c0,npts2,nsps2,mode_q65,jpk,s3,LL,NN)
- call pctile(s3,LL*NN,40,base)
- s3=s3/base
- where(s3(1:LL*NN)>s3lim) s3(1:LL*NN)=s3lim
- call q65_bzap(s3,LL) !Zap birdies
+ call spec64(workspace%c0(0:npts2-1),workspace%cs,npts2,nsps2, &
+ mode_q65,jpk,workspace%s3(1:LL*NN),LL,NN)
+ call pctile(workspace%s3(1:LL*NN),LL*NN,40,base)
+ workspace%s3(1:LL*NN)=workspace%s3(1:LL*NN)/base
+ where(workspace%s3(1:LL*NN)>s3lim) workspace%s3(1:LL*NN)=s3lim
+ call q65_bzap(workspace%s3(1:LL*NN),LL) !Zap birdies
do ibw=ibwa,ibwb
ndist=ndf**2 + ndt**2 + (ibw-ibw0)**2
if(ndist.gt.maxdist) cycle
@@ -73,7 +73,7 @@ subroutine q65_loops(c00,npts2,nsps2,nsubmode,ndepth,jpk0, &
if(b90.gt.345.0) cycle
b90ts = b90/baud
call timer('dec2 ',0)
- call q65_dec2(s3,nsubmode,b90ts,esnodb,irc,dat4,decoded)
+ call q65_dec2(workspace%s3(1:LL*NN),nsubmode,b90ts,esnodb,irc,dat4,decoded)
call timer('dec2 ',1)
! irc > 0 ==> number of iterations required to decode
! -1 = invalid params
diff --git a/lib/qra/q65/q65_set_list.f90 b/lib/qra/q65/q65_set_list.f90
index 0b836bde..2bb9c1f3 100644
--- a/lib/qra/q65/q65_set_list.f90
+++ b/lib/qra/q65/q65_set_list.f90
@@ -45,7 +45,7 @@ subroutine q65_set_list(mycall,hiscall,hisgrid,codewords,ncw)
endif
endif
- call genq65(msg,0,msgsent,itone,i3,n3)
+ call genq65(msg,0,msgsent,itone,i3,n3,0)
i0=1
j=0
do k=1,85
diff --git a/lib/qra/q65/q65_set_list2.f90 b/lib/qra/q65/q65_set_list2.f90
index 39147e61..433802fb 100644
--- a/lib/qra/q65/q65_set_list2.f90
+++ b/lib/qra/q65/q65_set_list2.f90
@@ -1,8 +1,8 @@
subroutine q65_set_list2(mycall,hiscall,hisgrid,callers,nhist2,codewords,ncw)
use types
- parameter (MAX_NCW=206)
- parameter (MAX_CALLERS=40) !For multiple q3 decodes in NA VHf Contest mode
+ parameter (MAX_NCW=411) !1 + 40 stored callers plus the current call, 5 kinds, 2 flags
+ parameter (MAX_CALLERS=50) !For multiple q3 decodes in NA VHF Contest mode
character*12 mycall,hiscall
character*6 hisgrid,c6
character*4 g4
@@ -41,7 +41,6 @@ subroutine q65_set_list2(mycall,hiscall,hisgrid,callers,nhist2,codewords,ncw)
g4=hisgrid(1:4)
endif
do k=1,5
- i=i+1
msg=trim(mycall)//' '//trim(c6)
j0=len(trim(msg))+1
if(k.eq.1) msg=msg(1:j0)//g4
@@ -49,19 +48,26 @@ subroutine q65_set_list2(mycall,hiscall,hisgrid,callers,nhist2,codewords,ncw)
if(k.eq.3) msg(j0:j0+3)=' RRR'
if(k.eq.4) msg(j0:j0+4)=' RR73'
if(k.eq.5) msg(j0:j0+2)=' 73'
- call genq65(msg,0,msgsent,itone,i3,n3)
- i0=1
- jj=0
- do kk=1,85
- if(kk.eq.isync(i0)) then
- i0=i0+1
- cycle
- endif
- jj=jj+1
- codewords(jj,i)=itone(kk) - 1
+ ! Generate both flag values: a caller may or may not have set
+ ! bit78 (copied our last transmission), and both must be
+ ! present as exact candidates for the full-AP list match to
+ ! recognize either with full sensitivity.
+ do iflag=0,1
+ i=i+1
+ call genq65(msg,0,msgsent,itone,i3,n3,iflag)
+ i0=1
+ jj=0
+ do kk=1,85
+ if(kk.eq.isync(i0)) then
+ i0=i0+1
+ cycle
+ endif
+ jj=jj+1
+ codewords(jj,i)=itone(kk) - 1
+ enddo
+! write(71,3001) i,j,k,iflag,codewords(1:13,i),trim(msg)
+!3001 format(4i3,2x,13i3,2x,a)
enddo
-! write(71,3001) i,j,k,codewords(1:13,i),trim(msg)
-!3001 format(3i3,2x,13i3,2x,a)
enddo
enddo
ncw=i
diff --git a/lib/qra/q65/q65_workspace.f90 b/lib/qra/q65/q65_workspace.f90
new file mode 100644
index 00000000..321bdfd4
--- /dev/null
+++ b/lib/qra/q65/q65_workspace.f90
@@ -0,0 +1,43 @@
+module q65_workspace
+
+ implicit none
+
+ integer, parameter :: Q65_NN=63
+ integer, parameter :: Q65_MAXFFT=20736
+
+ type :: q65_workspace_type
+ complex, allocatable :: c0(:)
+ real, allocatable :: s3(:)
+ complex, allocatable :: cs(:)
+ contains
+ procedure :: ensure => ensure_q65_workspace
+ end type q65_workspace_type
+
+contains
+
+ subroutine ensure_q65_workspace(this,npts2,ll)
+ class(q65_workspace_type), intent(inout) :: this
+ integer, intent(in) :: npts2,ll
+ integer n3
+
+ ! Keep the largest capacity so repeated searches do not churn the allocator.
+ n3=ll*Q65_NN
+
+ if(.not.allocated(this%c0)) then
+ allocate(this%c0(0:npts2-1))
+ else if(size(this%c0).lt.npts2) then
+ deallocate(this%c0)
+ allocate(this%c0(0:npts2-1))
+ endif
+
+ if(.not.allocated(this%s3)) then
+ allocate(this%s3(1:n3))
+ else if(size(this%s3).lt.n3) then
+ deallocate(this%s3)
+ allocate(this%s3(1:n3))
+ endif
+
+ if(.not.allocated(this%cs)) allocate(this%cs(0:Q65_MAXFFT-1))
+ end subroutine ensure_q65_workspace
+
+end module q65_workspace
diff --git a/lib/qra/q65/q65code.f90 b/lib/qra/q65/q65code.f90
index d61cba91..f4a94d00 100644
--- a/lib/qra/q65/q65code.f90
+++ b/lib/qra/q65/q65code.f90
@@ -2,9 +2,11 @@ program q65code
use q65_encoding
implicit none
- character*37 msg37
+ character*37 msg37,msgsent
integer nargs
integer codeword(65),tones(85)
+ integer iargc
+ logical success
nargs=iargc()
if(nargs .ne. 1) then
@@ -13,8 +15,13 @@ program q65code
endif
call getarg(1,msg37)
- call get_q65_tones(msg37,codeword,tones)
+ call get_q65_tones(msg37,codeword,tones,msgsent,success)
+ if(.not.success) then
+ print*,'Cannot encode message: ',trim(msg37)
+ stop 1
+ endif
+ write(*,*) 'Message sent: ',trim(msgsent)
write(*,*) 'Generated message plus CRC (90 bits)'
write(*,'(a8,15i4)') '6 bit : ',codeword(1:15)
write(*,'(a8,15b6.6)') 'binary: ',codeword(1:15)
diff --git a/lib/qra/q65/q65sim.f90 b/lib/qra/q65/q65sim.f90
index 827cf55c..53d6ca84 100644
--- a/lib/qra/q65/q65sim.f90
+++ b/lib/qra/q65/q65sim.f90
@@ -23,8 +23,8 @@ program q65sim
character*37 msg,msgsent,imsg(10)
nargs=iargc()
- if(nargs.ne.11) then
- print*,'Usage: q65sim "msg" A-F freq fDop DT f1 Stp TRp Nsig Nfile SNR'
+ if(nargs.ne.11 .and. nargs.ne.12) then
+ print*,'Usage: q65sim "msg" A-F freq fDop DT f1 Stp TRp Nsig Nfile SNR [Flag]'
print*,'Example: q65sim "K1ABC W9XYZ EN37" A 1500 0.0 0.0 0.0 1 60 1 1 -26'
print*,'Example: q65sim "ST" A 1500 0.0 0.0 0.0 1 60 1 -26'
print*,' fDop = Doppler spread'
@@ -32,6 +32,7 @@ program q65sim
print*,' Stp = Step size (Hz)'
print*,' Stp = 0 implies no Doppler tracking'
print*,' Nsig = number of generated signals, 1 - 10'
+ print*,' Flag = optional, sets the spare 78th bit (0 or 1); default 0'
print*,' Creates filenames which increment to permit averaging in first period'
print*,' If msg = ST program produces a single tone at freq'
go to 999
@@ -57,6 +58,11 @@ program q65sim
read(arg,*) nfiles
call getarg(11,arg)
read(arg,*) snrdb
+ iflag=0
+ if(nargs.eq.12) then
+ call getarg(12,arg)
+ read(arg,*) iflag
+ endif
if(ntrperiod.eq.15) then
nsps=1800
@@ -97,7 +103,7 @@ program q65sim
ichk=0
do i=1,nsig
msg=imsg(i)
- call genq65(msg,ichk,msgsent,itone,i3,n3)
+ call genq65(msg,ichk,msgsent,itone,i3,n3,iflag)
ntone(:,i)=itone
enddo
@@ -135,7 +141,7 @@ program q65sim
1106 format('000000_',i4.4,'.wav')
endif
- open(10,file=trim(fname),access='stream',status='unknown')
+ open(10,file=trim(fname),access='stream',status='replace')
xnoise=0.
if(snrdb.lt.90) then
do i=1,npts
diff --git a/lib/qso50/g0 b/lib/qso50/g0
index a19d872a..50fff694 100644
--- a/lib/qso50/g0
+++ b/lib/qso50/g0
@@ -4,5 +4,5 @@ gfortran -o twq -Wall -Wno-conversion -fbounds-check twq.f90 \
unpacktext2.f90 unpackpfx.f90 pack50.f90 unpack50.f90 \
../hash.f90 ../deg2grid.f90 ../grid2deg.f90 \
../fix_contest_msg.f90 ../to_contest_msg.f90 \
- ../fmtmsg.f90 ../azdist.f90 ../geodist.f90 ../wsprd/nhash.c
- \ No newline at end of file
+ ../fmtmsg.f90 ../azdist.f90 ../geodist.f90 ../wsprd/nhash.c \
+ ../lookup3.c
diff --git a/lib/readwav.f90 b/lib/readwav.f90
index 25369049..506bf3a9 100644
--- a/lib/readwav.f90
+++ b/lib/readwav.f90
@@ -17,6 +17,7 @@
! end do
!
module readwav
+ use, intrinsic :: iso_fortran_env, only: int64
implicit none
type format_chunk
@@ -32,13 +33,15 @@ module readwav
integer :: lun
type(format_chunk) :: audio_format
integer :: data_size
+ integer :: data_bytes_remaining
contains
procedure :: read
+ procedure :: read_samples
end type wav_header
private
contains
- subroutine read (this, filename)
+ subroutine read (this, filename, status, message)
implicit none
type riff_descriptor
@@ -48,26 +51,147 @@ contains
class(wav_header), intent(inout) :: this
character(len=*), intent(in) :: filename
+ integer, intent(out), optional :: status
+ character(len=*), intent(out), optional :: message
- integer :: filepos
+ integer :: ios
+ integer(int64) :: filepos, filesize, data_end, nextpos, padded_size
type(riff_descriptor) :: desc
character(len=4) :: riff_type
+ logical :: format_found
this%lun=26
- open (unit=this%lun, file=filename, access='stream',status='old')
- read (unit=this%lun) desc,riff_type
+ this%data_size = 0
+ this%data_bytes_remaining = 0
+ this%audio_format = format_chunk(0, 0, 0, 0, 0, 0)
+ format_found = .false.
+ call set_result(0, '')
+
+ open (unit=this%lun, file=filename, access='stream', form='unformatted', &
+ status='old', action='read', iostat=ios)
+ if (ios /= 0) then
+ call fail('cannot open file')
+ return
+ end if
+ inquire (unit=this%lun, size=filesize)
+ if (filesize < 12) then
+ call fail('file is too short for a RIFF/WAVE header')
+ return
+ end if
+
+ read (unit=this%lun, iostat=ios) desc, riff_type
+ if (ios /= 0) then
+ call fail('cannot read RIFF/WAVE header')
+ return
+ end if
+ if (desc%id /= 'RIFF' .or. riff_type /= 'WAVE') then
+ call fail('not a RIFF/WAVE file')
+ return
+ end if
inquire (unit=this%lun, pos=filepos)
do
- read (unit=this%lun, pos=filepos) desc
+ if (filepos + 8_int64 > filesize + 1_int64) then
+ call fail('missing data chunk')
+ return
+ end if
+ read (unit=this%lun, pos=filepos, iostat=ios) desc
+ if (ios /= 0) then
+ call fail('cannot read WAV chunk header')
+ return
+ end if
inquire (unit=this%lun, pos=filepos)
+ if (desc%size < 0) then
+ call fail('WAV chunk has an invalid size')
+ return
+ end if
+ data_end = filepos + int(desc%size, int64)
+ if (data_end > filesize + 1_int64) then
+ call fail('WAV chunk extends beyond end of file')
+ return
+ end if
+ padded_size = int(desc%size, int64)
+ if (mod(padded_size, 2_int64) /= 0) padded_size = padded_size + 1_int64
+ nextpos = filepos + padded_size
if (desc%id .eq. 'fmt ') then
- read (unit=this%lun) this%audio_format
+ if (desc%size < 16) then
+ call fail('fmt chunk is too short')
+ return
+ end if
+ read (unit=this%lun, iostat=ios) this%audio_format
+ if (ios /= 0) then
+ call fail('cannot read fmt chunk')
+ return
+ end if
+ if (this%audio_format%audio_format /= 1 .or. &
+ this%audio_format%num_channels /= 1 .or. &
+ this%audio_format%bits_per_sample /= 16) then
+ call fail('unsupported WAV format; expected mono 16-bit PCM')
+ return
+ end if
+ if (this%audio_format%sample_rate /= 11025 .and. &
+ this%audio_format%sample_rate /= 12000) then
+ call fail('unsupported WAV sample rate')
+ return
+ end if
+ format_found = .true.
else if (desc%id .eq. 'data') then
+ if (.not. format_found) then
+ call fail('data chunk appears before fmt chunk')
+ return
+ end if
this%data_size = desc%size
- exit
+ this%data_bytes_remaining = desc%size
+ call set_result(0, '')
+ return
+ end if
+ if (nextpos > filesize + 1_int64) then
+ call fail('WAV chunk extends beyond end of file')
+ return
end if
- filepos = filepos + (desc%size + 1) / 2 * 2 ! pad to even alignment
+ filepos = nextpos
end do
- return
+
+ contains
+
+ subroutine fail(text)
+ character(len=*), intent(in) :: text
+
+ close(unit=this%lun, iostat=ios)
+ this%lun = -1
+ call set_result(1, text)
+ end subroutine fail
+
+ subroutine set_result(code, text)
+ integer, intent(in) :: code
+ character(len=*), intent(in) :: text
+
+ if (present(status)) status = code
+ if (present(message)) message = text
+ end subroutine set_result
end subroutine read
+
+ subroutine read_samples(this, samples, samples_read, status, message)
+ class(wav_header), intent(inout) :: this
+ integer*2, intent(out) :: samples(:)
+ integer, intent(out) :: samples_read
+ integer, intent(out), optional :: status
+ character(len=*), intent(out), optional :: message
+
+ integer :: ios
+
+ samples = 0
+ samples_read = min(size(samples), this%data_bytes_remaining / 2)
+ if (present(status)) status = 0
+ if (present(message)) message = ''
+ if (samples_read == 0) return
+
+ read(unit=this%lun, iostat=ios) samples(:samples_read)
+ if (ios /= 0) then
+ samples_read = 0
+ if (present(status)) status = 1
+ if (present(message)) message = 'cannot read WAV sample data'
+ return
+ end if
+ this%data_bytes_remaining = this%data_bytes_remaining - 2 * samples_read
+ end subroutine read_samples
end module readwav
diff --git a/lib/refspectrum.f90 b/lib/refspectrum.f90
index 68b514f9..01a79ab0 100644
--- a/lib/refspectrum.f90
+++ b/lib/refspectrum.f90
@@ -1,11 +1,14 @@
-subroutine refspectrum(id2,bclear,brefspec,buseref,fname)
+subroutine refspectrum(id2,ninput,bclear,brefspec,buseref,fname)
! Input:
! id2 i*2 Raw 16-bit integer data, 12000 Hz sample rate
+! ninput Valid input count, 1..3456; zero resets stream history
! brefspec logical True when accumulating a reference spectrum
parameter (NFFT=6912,NH=NFFT/2,NPOLYLOW=400,NPOLYHIGH=2600)
integer*2 id2(NFFT)
+ integer*2 measurement(NH)
+ integer ninput,nmeasurement,offset,ncopy
logical*1 bclear,brefspec,buseref,blastuse
real xs(0:NH-1) !Saved upper half of input chunk convolved with h(t)
@@ -30,15 +33,41 @@ subroutine refspectrum(id2,bclear,brefspec,buseref,fname)
w(i)=ww*ww/NFFT
enddo
nsave=0
+ nmeasurement=0
s=0.0
filter=1.0
xs=0.
first=.false.
endif
- if(bclear) s=0.
+ if(bclear) then
+ s=0.
+ fil=1.0
+ ref=0.0
+ filter=0.0
+ cfil=0.0
+ xs=0.0
+ nsave=0
+ nmeasurement=0
+ blastuse=.false.
+ endif
+ if(ninput.lt.0.or.ninput.gt.NH) return
+ if(ninput.eq.0) then
+ xs=0.0
+ nmeasurement=0
+ if(.not.buseref) blastuse=.false.
+ return
+ endif
if(brefspec) then
- x(0:NH-1)=0.001*id2(1:NH)
+ offset=0
+ do while(offset.lt.ninput)
+ ncopy=min(NH-nmeasurement,ninput-offset)
+ measurement(nmeasurement+1:nmeasurement+ncopy)=id2(offset+1:offset+ncopy)
+ offset=offset+ncopy
+ nmeasurement=nmeasurement+ncopy
+ if(nmeasurement.lt.NH) cycle
+ nmeasurement=0
+ x(0:NH-1)=0.001*measurement
x(NH:NFFT-1)=0.0
call four2a(cx,NFFT,1,-1,0) !r2c FFT
@@ -118,6 +147,7 @@ subroutine refspectrum(id2,bclear,brefspec,buseref,fname)
enddo
close(16)
endif
+ enddo
return
endif
@@ -136,21 +166,23 @@ subroutine refspectrum(id2,bclear,brefspec,buseref,fname)
cx(1:NH)=fil(1:NH)/NFFT
call four2a(cx,NFFT,1,1,-1)
x=cshift(x,-400)
- x(800:NH)=0.0
+! Retain only the causal 800-tap response. Leaving the negative-time tail
+! near NFFT produces circular wraparound that depends on input chunk size.
+ x(800:NFFT-1)=0.0
call four2a(cx,NFFT,1,-1,0)
cfil=cx
close(16)
endif
! Use overlap and add method to apply causal reference filter.
- x(0:NH-1)=id2(1:NH)
- x(NH:NFFT-1)=0.0
+ x(0:ninput-1)=id2(1:ninput)
+ x(ninput:NFFT-1)=0.0
x=x/NFFT
call four2a(cx,NFFT,1,-1,0)
cx=cfil*cx
call four2a(cx,NFFT,1,1,-1)
x(0:NH-1)=x(0:NH-1)+xs
- xs=x(NH:NFFT-1)
- id2(1:NH)=nint(x(0:NH-1))
+ xs=x(ninput:ninput+NH-1)
+ id2(1:ninput)=nint(x(0:ninput-1))
endif
blastuse=buseref
diff --git a/lib/rig_control.c b/lib/rig_control.c
index 7c8b2f62..96cd49ca 100644
--- a/lib/rig_control.c
+++ b/lib/rig_control.c
@@ -3,6 +3,9 @@
#include <stdlib.h>
#include <string.h>
#include "tstrig.h"
+#ifndef HAMLIB_RIGPORT
+#include <hamlib/port.h>
+#endif
RIG *my_rig; // handle to rig
@@ -60,10 +63,10 @@ int rigOpen(int verbose, rig_model_t my_model, const char* rig_file,
}
if (rig_file)
- strncpy(my_rig->state.rigport.pathname, rig_file, FILPATHLEN - 1);
+ strncpy(HAMLIB_RIGPORT(my_rig)->pathname, rig_file, HAMLIB_FILPATHLEN - 1);
if (serial_rate!=0)
- my_rig->state.rigport.parm.serial.rate = serial_rate;
+ HAMLIB_RIGPORT(my_rig)->parm.serial.rate = serial_rate;
if (civaddr)
rig_set_conf(my_rig, rig_token_lookup(my_rig, "civaddr"), civaddr);
diff --git a/lib/rtty_spec.f90 b/lib/rtty_spec.f90
index 2ddc802f..6b109665 100644
--- a/lib/rtty_spec.f90
+++ b/lib/rtty_spec.f90
@@ -95,7 +95,7 @@ program rtty_spec
h=default_header(12000,NMAX)
datmax=maxval(abs(dat))
iwave=nint(32767.0*dat/datmax)
- open(10,file='000000_000001.wav',access='stream',status='unknown')
+ open(10,file='000000_000001.wav',access='stream',status='replace')
write(10) h,iwave
close(10)
diff --git a/lib/save_dxbase.f90 b/lib/save_dxbase.f90
deleted file mode 100644
index 206dfd5e..00000000
--- a/lib/save_dxbase.f90
+++ /dev/null
@@ -1,9 +0,0 @@
-subroutine save_dxbase(dxbase0)
-
- use packjt77
- character*6 dxbase0
-
- dxbase=dxbase0
-
- return
-end subroutine save_dxbase
diff --git a/lib/savec2.f90 b/lib/savec2.f90
index 6435a215..b3862186 100644
--- a/lib/savec2.f90
+++ b/lib/savec2.f90
@@ -2,27 +2,27 @@ integer function savec2(c2name,ntrseconds,f0m1500)
! Array c0() has complex samples at 1500 Hz sample rate.
! WSPR-2: downsample by 1/4 to produce c2, centered at 1500 Hz
-! WSPR-15: downsample by 1/32 to produce c2, centered at 1612.5 Hz
parameter (NDMAX=120*1500) !Sample intervals at 1500 Hz rate
- parameter (MAXFFT=256*1024)
character*(*) c2name
character*14 outfile
real*8 f0m1500
complex c0
- complex c1(0:MAXFFT-1)
- complex c2(0:65535)
+ ! Keep FFT buffers at a stable address so four2a can reuse its plans.
+ complex, allocatable, save :: c1(:),c2(:)
common/c0com/c0(0:NDMAX-1)
- ntrminutes=ntrseconds/60
+ if(ntrseconds.ne.120) then
+ savec2=-1
+ return
+ endif
+
+ ntrminutes=2
npts=114*1500
nfft1=262144
- if(ntrminutes.eq.15) then
- npts=890*1500
- nfft1=MAXFFT
- endif
- df1=1500.0/nfft1
+ nfft2=65536
+ if(.not.allocated(c1)) allocate(c1(0:nfft1-1),c2(0:nfft2-1))
fac=1.0/nfft1
c1(0:npts-1)=fac*c0(0:npts-1)
c1(npts:nfft1-1)=0.
@@ -30,23 +30,16 @@ integer function savec2(c2name,ntrseconds,f0m1500)
call four2a(c1,nfft1,1,1,1) !Complex FFT to frequency domain
! Select the desired frequency range
- nfft2=65536
nh2=nfft2/2
- if(ntrminutes.eq.2) then
- c2(0:nh2)=c1(0:nh2)
- c2(nh2+1:nfft2-1)=c1(nfft1-nh2+1:nfft1-1)
- else
- i0=nint(112.5/df1)
- c2(0:nh2)=c1(i0:i0+nh2)
- c2(nh2+1:nfft2-1)=c1(i0-nh2+1:i0-1)
- endif
+ c2(0:nh2)=c1(0:nh2)
+ c2(nh2+1:nfft2-1)=c1(nfft1-nh2+1:nfft1-1)
call four2a(c2,nfft2,1,-1,1) !Shorter complex FFT, back to time domain
! Write complex time-domain data to disk.
i1=index(c2name,'.c2')
outfile=c2name(i1-11:i1+2)
- open(18,file=c2name,status='unknown',access='stream', iostat=ioerr)
+ open(18,file=c2name,status='replace',access='stream', iostat=ioerr)
if (ioerr.eq.0) then
write(18) outfile,ntrminutes,f0m1500,c2(0:45000-1)
close(18)
diff --git a/lib/sec_midn.f90 b/lib/sec_midn.f90
index 0bbe62c2..03d175d5 100644
--- a/lib/sec_midn.f90
+++ b/lib/sec_midn.f90
@@ -4,8 +4,7 @@ real function sec_midn()
end function sec_midn
subroutine sleep_msec(n)
-
- call usleep(1000*n)
-
+ use, intrinsic :: iso_fortran_env, only: INT64
+ call usleep(int(1000*n, kind=INT64))
return
end subroutine sleep_msec
diff --git a/lib/sh65.f90 b/lib/sh65.f90
index 09bef9c2..7d1efc3d 100644
--- a/lib/sh65.f90
+++ b/lib/sh65.f90
@@ -6,6 +6,7 @@ subroutine sh65(cx,n5,mode65,ntol,xdf,nspecial,snrdb)
real ss(-NH+1:NH,16)
real sigmax(16)
integer ipk(16)
+ save ss
ss=0.
@@ -47,6 +48,7 @@ subroutine sh65(cx,n5,mode65,ntol,xdf,nspecial,snrdb)
ib2=min(NH,nint(fb/df + 4.1*nfac))
! Find strongest line in each of the 16 phases
+ snr1=0.
sbest=0.
snrbest=0.
nbest=1
diff --git a/lib/shmem.cpp b/lib/shmem.cpp
index 95a86614..7d1783d6 100644
--- a/lib/shmem.cpp
+++ b/lib/shmem.cpp
@@ -14,7 +14,5 @@ extern "C"
bool shmem_attach () {return shmem.attach();}
int shmem_size () {return static_cast<int> (shmem.size());}
struct jt9com * shmem_address () {return reinterpret_cast<struct jt9com *>(shmem.data());}
- bool shmem_lock () {return shmem.lock();}
- bool shmem_unlock () {return shmem.unlock();}
bool shmem_detach () {return shmem.detach();}
}
diff --git a/lib/shmem.f90 b/lib/shmem.f90
index 8d9db7d6..853f67e9 100644
--- a/lib/shmem.f90
+++ b/lib/shmem.f90
@@ -27,16 +27,6 @@ module shmem
integer(c_int) :: shmem_size
end function shmem_size
- function shmem_lock () bind(C, name="shmem_lock")
- use iso_c_binding, only: c_bool
- logical(c_bool) :: shmem_lock
- end function shmem_lock
-
- function shmem_unlock () bind(C, name="shmem_unlock")
- use iso_c_binding, only: c_bool
- logical(c_bool) :: shmem_unlock
- end function shmem_unlock
-
function shmem_detach () bind(C, name="shmem_detach")
use iso_c_binding, only: c_bool
logical(c_bool) :: shmem_detach
diff --git a/lib/sleep_msec.f90 b/lib/sleep_msec.f90
index 1a8dbe4f..1c15053e 100644
--- a/lib/sleep_msec.f90
+++ b/lib/sleep_msec.f90
@@ -1,4 +1,5 @@
subroutine sleep_msec(n)
- call usleep(n*1000)
+ use, intrinsic :: iso_fortran_env, only: INT64
+ call usleep(INT(n*1000, kind=INT64))
return
end subroutine sleep_msec
diff --git a/lib/spec64.f90 b/lib/spec64.f90
index 9e0d708d..1fd732bb 100644
--- a/lib/spec64.f90
+++ b/lib/spec64.f90
@@ -1,10 +1,12 @@
-subroutine spec64(c0,npts,nsps,mode_q65,jpk,s3,LL,NN)
+subroutine spec64(c0,cs,npts,nsps,mode_q65,jpk,s3,LL,NN)
+
+ use q65_workspace, only: Q65_MAXFFT
- parameter (MAXFFT=20736)
complex c0(0:npts-1) !Complex spectrum of dd()
- complex cs(0:MAXFFT-1) !Complex symbol spectrum
+ complex cs(0:Q65_MAXFFT-1) !Complex symbol spectrum
real s3(LL,NN) !Synchronized symbol spectra
real xbase0(LL),xbase(LL)
+ real s3_row(NN)
! integer ipk1(1)
integer isync(22) !Indices of sync symbols
data isync/1,9,12,13,15,22,23,26,27,33,35,38,46,50,55,60,62,66,69,74,76,85/
@@ -36,7 +38,8 @@ subroutine spec64(c0,npts,nsps,mode_q65,jpk,s3,LL,NN)
df=6000.0/nfft
do i=1,LL
- call pctile(s3(i,1:NN),NN,45,xbase0(i)) !Get baseline for passband shape
+ s3_row=s3(i,1:NN)
+ call pctile(s3_row,NN,45,xbase0(i)) !Get baseline for passband shape
enddo
nh=25
diff --git a/lib/spec_qra65.f90 b/lib/spec_qra65.f90
index 15e8fd09..575d5050 100644
--- a/lib/spec_qra65.f90
+++ b/lib/spec_qra65.f90
@@ -6,6 +6,7 @@ subroutine spec_qra65(c0,nsps,s3,LL,NN)
complex, allocatable :: cs(:) !Complex symbol spectrum
real s3(LL,NN) !Synchronized symbol spectra
real xbase0(LL),xbase(LL) !Work arrays
+ real s3_row(NN)
integer isync(22) !Indices of sync symbols
data isync/1,9,12,13,15,22,23,26,27,33,35,38,46,50,55,60,62,66,69,74,76,85/
@@ -32,7 +33,8 @@ subroutine spec_qra65(c0,nsps,s3,LL,NN)
df=6000.0/nsps
do i=1,LL
- call pctile(s3(i,1:NN),NN,45,xbase0(i)) !Get baseline for passband shape
+ s3_row=s3(i,1:NN)
+ call pctile(s3_row,NN,45,xbase0(i)) !Get baseline for passband shape
enddo
nh=9
diff --git a/lib/stdmsg.f90 b/lib/stdmsg.f90
index b4f41040..323b3c47 100644
--- a/lib/stdmsg.f90
+++ b/lib/stdmsg.f90
@@ -41,3 +41,37 @@ function stdmsg(msg0)
return
end function stdmsg
+
+function stdmsg72(msg0,is_jt65)
+
+ use iso_c_binding, only: c_bool
+ use packjt, only: packmsg, unpackmsg
+
+ implicit none
+
+ character(len=37), intent(in) :: msg0
+ logical(c_bool), intent(in) :: is_jt65
+ logical(c_bool) :: stdmsg72
+ character(len=22) :: msg72,decoded72
+ integer :: dat(12),itype,n
+
+ stdmsg72=.false.
+ msg72=msg0(1:22)
+
+ if(msg0(23:24).eq.' d' .and. msg72(22:22).eq.'?') msg72(22:22)=' '
+
+ if(is_jt65) then
+ n=len_trim(msg72)
+ if(n.ge.4) then
+ if(msg72(n-3:n).eq.' OOO') msg72(n-3:)=' '
+ endif
+ endif
+
+ call packmsg(msg72,dat,itype)
+ if(itype.lt.1 .or. itype.gt.5) return
+
+ call unpackmsg(dat,decoded72)
+ stdmsg72=(decoded72.eq.msg72)
+
+ return
+end function stdmsg72
diff --git a/lib/stream_setmode.c b/lib/stream_setmode.c
new file mode 100644
index 00000000..f70b29e7
--- /dev/null
+++ b/lib/stream_setmode.c
@@ -0,0 +1,24 @@
+/* stream_setmode.c — put stdin into binary mode on Windows.
+ *
+ * jt9 --stream / jt9stream read a framed binary byte stream (PCM audio +
+ * control frames) from stdin. On Windows, stdin defaults to text mode, which
+ * translates CR/LF and stops at a 0x1A (^Z) byte — both corrupt binary data.
+ * This helper forces binary mode once, before the stream is opened.
+ *
+ * On POSIX (Linux, macOS) there is no text/binary distinction for stdin, so
+ * this compiles to a no-op. Called via a bind(C) interface from
+ * lib/streaming_io.f90. C linkage gives the exact symbol name (no Fortran
+ * trailing-underscore mangling), matched by bind(C, name="...").
+ */
+#ifdef _WIN32
+#include <io.h>
+#include <fcntl.h>
+#include <stdio.h>
+#endif
+
+void stream_set_stdin_binary(void)
+{
+#ifdef _WIN32
+ _setmode(_fileno(stdin), _O_BINARY);
+#endif
+}
diff --git a/lib/stream_stdin.c b/lib/stream_stdin.c
new file mode 100644
index 00000000..b3f09025
--- /dev/null
+++ b/lib/stream_stdin.c
@@ -0,0 +1,49 @@
+/* stream_stdin.c — portable read-fully helper for the framed stdin
+ * protocol (lib/streaming_io.f90).
+ *
+ * Fortran unit I/O cannot read a redirected stdin portably: native
+ * Windows has no /dev/stdin, and re-OPENing the preconnected unit 5 with
+ * ACCESS='STREAM' is non-conforming (F2018 12.5.6.1 — ACCESS is not a
+ * changeable mode of a connected unit), so libgfortran rejects it on
+ * every platform. This helper reads file descriptor 0 directly instead,
+ * and is used on ALL platforms — one code path, exercised by the POSIX
+ * fixtures suites, no #ifdef branch that CI never runs.
+ *
+ * The loop retries until the full request is delivered or the stream
+ * truly ends (read() == 0, or a hard error). A pipe short-read — which
+ * a small fast producer can trigger, and which Fortran stream input
+ * surfaces as an I/O error — therefore can never be mistaken for EOF:
+ * a short return here means the producer closed the pipe.
+ *
+ * Windows: binary mode must be forced on fd 0 before the first read
+ * (stream_set_stdin_binary in lib/stream_setmode.c, called from
+ * jt9_stream's setup) or the CRT stops at 0x1A and rewrites CRLF;
+ * _read() honors that mode. Called via bind(C) from Fortran.
+ */
+#include <stdint.h>
+
+#ifdef _WIN32
+#include <io.h>
+#else
+#include <errno.h>
+#include <unistd.h>
+#endif
+
+int64_t stream_stdin_read_fully(void *buf, int64_t n)
+{
+ char *p = (char *) buf;
+ int64_t total = 0;
+ while (total < n) {
+ int64_t want = n - total;
+ if (want > ((int64_t) 1 << 20)) want = (int64_t) 1 << 20;
+#ifdef _WIN32
+ int r = _read(0, p + total, (unsigned int) want);
+#else
+ ssize_t r = read(0, p + total, (size_t) want);
+ if (r < 0 && errno == EINTR) continue;
+#endif
+ if (r <= 0) break;
+ total += (int64_t) r;
+ }
+ return total;
+}
diff --git a/lib/streaming_apply.f90 b/lib/streaming_apply.f90
new file mode 100644
index 00000000..72feda74
--- /dev/null
+++ b/lib/streaming_apply.f90
@@ -0,0 +1,328 @@
+! Streaming apply — configure_fields -> params_block mapping.
+!
+! Extracted from streaming_io.f90's former nested-internal apply_configure_
+! so the cfg->params apply ROUTING is unit-testable. The
+! routing was previously unreachable (a nested internal sub of jt9_stream) and
+! inert on the FT8/JT9 fixtures, so a mis-route (e.g. his_call -> hisgrid)
+! passed every fixture gate byte-identical. This module makes the
+! mapping a module-public procedure that a standalone driver can call against a
+! bare params_block — see test/apply_routing_test.f90.
+!
+! This is a behavior-preserving relocation: the body below is the verbatim
+! apply_configure_ body (sd%params -> params, the two host-associated baselines
+! now explicit dummy args). The order-sensitive logic (rxfreq decouple,
+! apply_per_mode_policy call + emedelay-before-policy, nfa/nfb baseline restore,
+! ntol per-mode cap) keeps its original position, so behavior is identical.
+!
+! Dependencies (all acyclic — neither dependee uses this module):
+! streaming_control -> configure_fields (the source struct)
+! jt9_params_init -> apply_per_mode_policy
+! include jt9com.f90 -> params_block (+ iso_c_binding / constants.f90)
+
+module streaming_apply
+ use streaming_control, only: configure_fields, NPTS_C0_ARRAY_MIN, &
+ NPTS_C0_ARRAY_MAX
+ use jt9_params_init, only: apply_per_mode_policy
+
+ include 'jt9com.f90'
+
+ private
+ public :: apply_configure_fields
+ ! Re-export the include'd struct so a standalone unit driver can declare a
+ ! params_block to assert apply routing against (test/apply_routing_test.f90)
+ ! without itself including jt9com.f90. Same bind(C) type as everywhere else
+ ! (F2018 §7.5.2.4 same-type rule), so it argument-associates with the
+ ! jt9_params_init init routines exactly as streaming_io's include'd one does.
+ public :: params_block
+
+contains
+
+ ! Apply a configure frame's set fields to a params_block + the caller's
+ ! mode/TRperiod state. baseline_nfa/baseline_nfb are the session-baseline
+ ! nfa/nfb (stashed by the caller at stream start) restored on mode change
+ ! when the consumer didn't explicit-set them this frame.
+ subroutine apply_configure_fields(in_cfg, io_mode, io_TRperiod, params, &
+ baseline_nfa, baseline_nfb)
+ type(configure_fields), intent(in) :: in_cfg
+ integer, intent(inout) :: io_mode
+ real(8), intent(inout) :: io_TRperiod
+ type(params_block), intent(inout) :: params
+ integer, intent(in) :: baseline_nfa, baseline_nfb
+ if (in_cfg%mode_set) then
+ io_mode = in_cfg%mode
+ params%nmode = in_cfg%mode
+ ! Default TRperiod for the new mode if no explicit trperiod follows.
+ if (.not. in_cfg%trperiod_set) then
+ select case (in_cfg%mode)
+ case (8); io_TRperiod = 15.d0
+ case (5); io_TRperiod = 7.5d0
+ case (144); io_TRperiod = 30.d0
+ case default; io_TRperiod = 60.d0
+ end select
+ params%ntr = int(io_TRperiod)
+ end if
+ end if
+ if (in_cfg%trperiod_set) then
+ io_TRperiod = in_cfg%trperiod
+ params%ntr = int(io_TRperiod)
+ end if
+ if (in_cfg%depth_set) params%ndepth = in_cfg%depth
+ if (in_cfg%submode_set) params%nsubmode = in_cfg%submode
+ if (in_cfg%rxfreq_set) then
+ params%nfqso = in_cfg%rxfreq
+ params%nftx = in_cfg%rxfreq
+ end if
+ if (in_cfg%mycall_set) params%mycall = transfer(in_cfg%mycall, params%mycall)
+ if (in_cfg%mygrid_set) params%mygrid = transfer(in_cfg%mygrid, params%mygrid)
+
+ ! ===== Phase 4: operator identity fields (RFC v1 §2) ====================
+ ! char12/char6 via transfer() like mycall/mygrid (§4 — a width mismatch
+ ! silently truncates/pads at the bind(C) boundary, so the configure_fields
+ ! widths match the struct). Bools assign directly (logical -> logical(c_bool)).
+ if (in_cfg%his_call_set) params%hiscall = transfer(in_cfg%his_call, params%hiscall)
+ if (in_cfg%his_grid_set) params%hisgrid = transfer(in_cfg%his_grid, params%hisgrid)
+ if (in_cfg%my_b_call_set) params%mybcall = transfer(in_cfg%my_b_call, params%mybcall)
+ if (in_cfg%his_b_call_set) params%hisbcall = transfer(in_cfg%his_b_call, params%hisbcall)
+ if (in_cfg%my_call_standard_set) params%lmycallstd = in_cfg%my_call_standard
+ if (in_cfg%his_call_standard_set) params%lhiscallstd = in_cfg%his_call_standard
+
+ ! Phase 4: frequency-window ints. tx_audio_offset_hz -> nftx applies AFTER
+ ! the rxfreq block above so it DECOUPLES the tx side: rxfreq set both
+ ! nfqso+nftx, and a co-present tx_audio_offset_hz then overrides nftx only.
+ ! jt65_jt9_split_hz -> nfsplit (honored as written; a bare
+ ! mid-stream mode switch does not auto-replay init-time fsplit). max_drift_hz
+ ! -> max_drift (Q65 drift search; inert for FT8/JT9, so no decode-output
+ ! fixture — verified at parse-unit + no-regression, like the other §4 fields).
+ if (in_cfg%tx_audio_offset_hz_set) params%nftx = in_cfg%tx_audio_offset_hz
+ if (in_cfg%jt65_jt9_split_hz_set) params%nfsplit = in_cfg%jt65_jt9_split_hz
+ if (in_cfg%max_drift_hz_set) params%max_drift = in_cfg%max_drift_hz
+
+ ! ===== Phase 5: decoder-tuning basic fields (RFC v1 §2) =================
+ ! Flat 1:1. dt_tolerance_seconds/eme_delay_seconds narrow real(8) ->
+ ! real(c_float) via the target's kind() (§4 — document the narrowing).
+ ! eme_delay_seconds is applied HERE, before the apply_per_mode_policy
+ ! call below: a frame that ALSO sets mode/trperiod re-runs that policy, which
+ ! OVERWRITES emedelay (0.0 non-Q65-60s, 2.5 Q65-60s) — so a producer
+ ! eme_delay_seconds survives only on a frame with NO mode/trperiod change
+ ! (matches RFC §2.4). kin_samples/nzhsym_per_period are honored at apply, but
+ ! the streaming period-prep block (~:331/:339) RECOMPUTES kin/nzhsym from the
+ ! accumulated sample count before each decode, so they are inert on this path
+ ! (documented; verified byte-identical). robust_mode/nagain_flag/
+ ! clear_average -> logical(c_bool). tx_mode (enum) -> ntxmode (read only in
+ ! the 65+9 dual-decode dispatch; inert for FT8/pure-JT9 fixtures).
+ if (in_cfg%dt_tolerance_seconds_set) &
+ params%dttol = real(in_cfg%dt_tolerance_seconds, kind(params%dttol))
+ if (in_cfg%eme_delay_seconds_set) &
+ params%emedelay = real(in_cfg%eme_delay_seconds, kind(params%emedelay))
+ if (in_cfg%kin_samples_set) params%kin = in_cfg%kin_samples
+ if (in_cfg%nzhsym_per_period_set) params%nzhsym = in_cfg%nzhsym_per_period
+ if (in_cfg%npts_c0_array_set .and. &
+ in_cfg%npts_c0_array .ge. NPTS_C0_ARRAY_MIN .and. &
+ in_cfg%npts_c0_array .le. NPTS_C0_ARRAY_MAX) &
+ params%npts8 = in_cfg%npts_c0_array
+ if (in_cfg%min_width_set) params%minw = in_cfg%min_width
+ if (in_cfg%min_sync_set) params%minsync = in_cfg%min_sync
+ if (in_cfg%n_2pass_set) params%n2pass = in_cfg%n_2pass
+ if (in_cfg%robust_mode_set) params%nrobust = in_cfg%robust_mode
+ if (in_cfg%nagain_flag_set) params%nagain = in_cfg%nagain_flag
+ if (in_cfg%tx_mode_set) params%ntxmode = in_cfg%tx_mode
+ if (in_cfg%clear_average_set) params%nclearave = in_cfg%clear_average
+
+ ! ===== Phase 6: FT8/FT4 specifics cluster (RFC v1 §2) ===================
+ ! Flat 1:1, no per-mode-policy interaction (none of these 24 are touched by
+ ! apply_per_mode_policy / the nfa-nfb-restore / ntol blocks below). 21 of 24
+ ! are INERT on the jt9 --stream FT8/JT9 fixtures (read only inside the
+ ! multithreaded-FT8 block decoder.f90:192, which streaming forces off via
+ ! lmultift8=.false.; jt65_ap_on is JT65-only; superfox_mode/even_sequence are
+ ! superfox-path-only (ncontest==7 / sfrx_sub); ft8_decoder_start is non-stream
+ ! (WAV/shmem) path; hint_mode unread anywhere) —
+ ! parse-unit + apply-routing-unit + no-regression guard them. Only ft8_ap_on
+ ! -> lft8apon, ap_cq_only -> lapcqonly, ap_width_hz -> napwid reach the
+ ! single-pass FT8 decoder (decoder.f90:1141-1146), but they are EMPIRICALLY
+ ! inert on the FT8 fixture in the FLIP direction too (ft8_ap_on=false / AP off,
+ ! ap_cq_only=true, ap_width_hz=5000 each yield byte-identical 21 decodes vs
+ ! baseline across 6 clean paired trials — the fixture has no AP-only
+ ! decodes), so no decode-effect gate is possible. ap_width_hz stores the RAW
+ ! wire int (the decoder halves it at lib/ft8var/ft8bvar.f90:1040 for the lapmyc
+ ! AP path, §3 napwid note) — do NOT pre-scale here. nagain_filter/stop_hint/hint_mode
+ ! assign logical -> logical(c_bool) nagainfil/nstophint/nhint (n-prefix, but
+ ! bool-typed in the struct).
+ ! multithreaded_ft8: the receiver IGNORES a non-false value.
+ ! Streaming has NO multithreaded-FT8 support — lmultift8=.true. takes the
+ ! decoder.f90:192 multithread branch, which yields 0 FT8 decodes on the stream
+ ! path (deterministic: 0 vs a 21-decode baseline, every trial).
+ ! So apply ONLY a false value (a no-op given the init-forced false), keeping the
+ ! forced-false invariant; a true is dropped so a producer can never enable the
+ ! broken path. Re-enable a straight pass-through if/when multithread streaming
+ ! lands. (The other 23 keys are flat pass-throughs — inert on the FT8/JT9
+ ! fixtures; verified byte-identical at probe values.)
+ if (in_cfg%multithreaded_ft8_set .and. .not. in_cfg%multithreaded_ft8) &
+ params%lmultift8 = .false.
+ if (in_cfg%ft8_cycles_set) params%nft8cycles = in_cfg%ft8_cycles
+ if (in_cfg%ft8_rxf_sensitivity_set) params%nft8rxfsens = in_cfg%ft8_rxf_sensitivity
+ if (in_cfg%ft8_threads_set) params%nmt = in_cfg%ft8_threads
+ if (in_cfg%ft8_decoder_start_set) params%ndecoderstart = in_cfg%ft8_decoder_start
+ if (in_cfg%ft8_low_threshold_set) params%lft8lowth = in_cfg%ft8_low_threshold
+ if (in_cfg%ft8_subpass_set) params%lft8subpass = in_cfg%ft8_subpass
+ if (in_cfg%ft8_ap_on_set) params%lft8apon = in_cfg%ft8_ap_on
+ if (in_cfg%ap_cq_only_set) params%lapcqonly = in_cfg%ap_cq_only
+ if (in_cfg%ap_my_call_set) params%lapmyc = in_cfg%ap_my_call
+ if (in_cfg%jt65_ap_on_set) params%ljt65apon = in_cfg%jt65_ap_on
+ if (in_cfg%ap_width_hz_set) params%napwid = in_cfg%ap_width_hz
+ if (in_cfg%hide_ft8_duplicates_set) params%lhideft8dupes = in_cfg%hide_ft8_duplicates
+ if (in_cfg%common_ft8b_set) params%lcommonft8b = in_cfg%common_ft8b
+ if (in_cfg%enable_dxc_search_set) params%lenabledxcsearch = in_cfg%enable_dxc_search
+ if (in_cfg%wide_dxc_search_set) params%lwidedxcsearch = in_cfg%wide_dxc_search
+ if (in_cfg%superfox_mode_set) params%b_superfox = in_cfg%superfox_mode
+ if (in_cfg%even_sequence_set) params%b_even_seq = in_cfg%even_sequence
+ if (in_cfg%hound_mode_set) params%lhound = in_cfg%hound_mode
+ if (in_cfg%multi_instance_set) params%lmultinst = in_cfg%multi_instance
+ if (in_cfg%skip_tx1_set) params%lskiptx1 = in_cfg%skip_tx1
+ if (in_cfg%nagain_filter_set) params%nagainfil = in_cfg%nagain_filter
+ if (in_cfg%stop_hint_set) params%nstophint = in_cfg%stop_hint
+ if (in_cfg%hint_mode_set) params%nhint = in_cfg%hint_mode
+
+ ! ===== Phase 7: diagnostic / sequencing fields (RFC v1 §2) ==============
+ ! No per-mode-policy interaction (none of these 6 are touched by
+ ! apply_per_mode_policy / the nfa-nfb-restore / ntol blocks below). 5 of the 6
+ ! are flat pass-throughs and INERT on the jt9 --stream FT8/JT9 fixtures:
+ ! currently_txing/mode_changed/sec_band_changed/delay_units/
+ ! last_tx_seconds_ago are read ONLY inside the multithreaded-FT8 block
+ ! (decoder.f90:192..1148, which streaming forces off via lmultift8=.false.), so
+ ! no decode-output gate is possible -> the parse-unit (run-phase7-parse-unit.sh)
+ ! + the apply-routing unit (run-apply-routing-unit.sh, sentinel-opposite slot
+ ! asserts) + no-regression are their coverage (like Phase 4).
+ ! currently_txing/mode_changed assign logical -> logical(c_bool)
+ ! ltxing/lmodechanged. OMITTED wire keys (utc_list*/nlist_count/datetime/
+ ! from_wav_file/new_data_flag) are documented in streaming_control.f90.
+ !
+ ! qso_progress_state -> nQSOProgress is the EXCEPTION: it reaches the
+ ! single-pass FT8 decoder (decoder.f90:1141), where ft8b.f90:274/299 use it as a
+ ! RAW index into nappasses(0:5) / naptypes(0:5,4) on the default
+ ! lft8apon=.true. / lapcqonly=.false. path. An out-of-range producer value
+ ! (<0 or >5) faults the decoder (an -fbounds-check abort -> a one-frame DoS;
+ ! silent memory corruption without the flag) -- a qso_progress_state=99
+ ! crashes jt9 --stream. The valid range is [0,5] universally (every decoder
+ ! dimensions naptypes(0:5,4)/nappasses(0:5); QsoProgress.hpp defines the
+ ! C++ producer values as 0..5). So, exactly like the Phase 6
+ ! multithreaded_ft8 guard
+ ! (the receiver IGNORES a value that would break the decode path), the apply
+ ! IGNORES an out-of-range value, keeping the safe default. Valid [0,5] pass
+ ! through UNCHANGED -> wire-parity preserved for every value the CLI -Q path
+ ! accepts (the CLI's identical out-of-range crash, jt9.f90:191, is a pre-existing
+ ! latent bug the streaming wire contract declines to inherit). On the FT8/JT9
+ ! fixtures an in-range qso_progress_state is empirically INERT (it only steers AP
+ ! passes and the fixture has no AP-only decodes -> qso=5 gives a
+ ! byte-identical 21-decode set), so the in-range routing is guarded by the
+ ! apply-routing unit; a survival fixture guards the out-of-range case (negative-controlled).
+ if (in_cfg%last_tx_seconds_ago_set) params%nlasttx = in_cfg%last_tx_seconds_ago
+ if (in_cfg%currently_txing_set) params%ltxing = in_cfg%currently_txing
+ if (in_cfg%mode_changed_set) params%lmodechanged = in_cfg%mode_changed
+ if (in_cfg%qso_progress_state_set .and. in_cfg%qso_progress_state >= 0 &
+ .and. in_cfg%qso_progress_state <= 5) &
+ params%nQSOProgress = in_cfg%qso_progress_state
+ if (in_cfg%sec_band_changed_set) params%nsecbandchanged = in_cfg%sec_band_changed
+ if (in_cfg%delay_units_set) params%ndelay = in_cfg%delay_units
+
+ ! ===== Phase 8: string & scaled / derived fields (RFC v1 §2/§6) =========
+ ! No per-mode-policy interaction. The cfg members already hold the DERIVED
+ ! legacy ints (utc_nutc / date_yymmdd / n_trials_nranera — computed at parse,
+ ! streaming_control.f90), so date/n_trials are flat pass-throughs here; only
+ ! candthin_threshold/dt_center_seconds scale at apply (real(8) wire -> int /100,
+ ! §6.5). INERT on the FT8/JT9 stream fixtures except utc (read-site map+probe):
+ ! ncandthin/ndtcenter are read ONLY by the multithread FT8-variant decoder
+ ! my_ft8var%decodevar (every such call — first at decoder.f90:348 — scales /100
+ ! into the variant sync thresholds sync8var.f90:17-18), and every such call lives
+ ! inside the if(lmultift8 .and. nmode==8) block (opens decoder.f90:192, else at
+ ! :1140) that streaming forces off — the single-pass FT8 decoder
+ ! (my_ft8%decode, :1141) is NOT passed them (probed inert: 5.0 / 2.0 s gave the
+ ! byte-identical 21-decode set). n_trials->nranera->ntrials is JT65-deep-search-only
+ ! (ntrials computed decoder.f90:143-145, consumed :1338/:1365, unused on FT8/JT9);
+ ! date->yymmdd is superfox-only (sfrx_sub.f90). So those four are guarded by
+ ! parse-unit + apply-routing-unit + no-regression; utc is decode-observable
+ ! (round-trip fixtures). NONE is an array index, so unlike qso_progress_state no
+ ! out-of-range apply guard is needed (read-site check: nranera<=18
+ ! keeps 10**(nranera/2) within int32; ncandthin/ndtcenter become real thresholds).
+ if (in_cfg%date_set) params%yymmdd = in_cfg%date_yymmdd
+ if (in_cfg%n_trials_set) params%nranera = in_cfg%n_trials_nranera
+ if (in_cfg%candthin_threshold_set) &
+ params%ncandthin = nint(in_cfg%candthin_threshold * 100.d0)
+ if (in_cfg%dt_center_seconds_set) &
+ params%ndtcenter = nint(in_cfg%dt_center_seconds * 100.d0)
+
+ ! ===== Phase 9: bit-packed fields (RFC v1 §2.4/§2.5/§6.1/§6.2) ===========
+ ! ndepth_packed / nexp_decode_packed were computed at parse (pack_phase9_ in
+ ! streaming_control.f90) from the 9 unpacked keys, so apply is flat. The legacy
+ ! `depth` full-int routes to ndepth verbatim above (the depth_set line near the
+ ! top); a frame carrying BOTH depth and any unpacked ndepth key was declined at
+ ! parse (conflict configure_type_error), so the depth and ndepth_packed
+ ! assignments never both fire on an accepted frame. Only depth_level is
+ ! decode-observable on FT8/JT9 (the fixtures run at depth=3 -> ndepth=3;
+ ! depth_level=1 -> ndepth=1 changes the FT8 pass structure ft8_decode.f90:178/182
+ ! and the JT9 iand(ndepth,7) tests jt9_decode.f90:88,92). The other 8
+ ! unpacked keys reach Q65/JT65/FST4/JT4 or the contest branch only
+ ! (single_decode/vhf_features/noise_blanker never reach the single-pass FT8
+ ! my_ft8%decode), so they are guarded by the parse-unit (the bit-pack) + this
+ ! routing (apply-routing-unit) + no-regression. No out-of-range apply guard is
+ ! needed: the pack already masks depth_level/q65_maxiters to their
+ ! bit widths and clamps the NB byte, and none reaches a raw array index.
+ if (in_cfg%ndepth_packed_set) params%ndepth = in_cfg%ndepth_packed
+ if (in_cfg%nexp_decode_packed_set) params%nexp_decode = in_cfg%nexp_decode_packed
+
+ ! Decode-bandwidth fields. Apply BEFORE the per-mode
+ ! policy block so consumer values flow through the cap: FT8/FST4 use
+ ! min(ntol, cap) so a smaller consumer value wins; Q65 + JT65+JT9 hard-
+ ! override the consumer value (those modes have decoder-side invariants
+ ! tied to the per-mode ntol). nfa/nfb pass through unchanged.
+ if (in_cfg%ntol_set) params%ntol = in_cfg%ntol
+ if (in_cfg%nfa_set) params%nfa = in_cfg%nfa
+ if (in_cfg%nfb_set) params%nfb = in_cfg%nfb
+
+ ! Per-period UTC. Producer sends a fresh nutc in each
+ ! period's configure frame so streaming_emit_decode can format the time
+ ! field correctly (instead of "000000").
+ if (in_cfg%nutc_set) params%nutc = in_cfg%nutc
+ ! Phase 8 (RFC v1 §6.3/§4.1): utc (ISO "HH:MM:SS") is a SECOND route to nutc,
+ ! kept alongside the legacy int nutc above. Applied AFTER nutc so utc WINS when
+ ! a frame carries both (the richer ISO form). The apply order encodes the
+ ! precedence — it does NOT depend on the parse order. utc_nutc was derived from
+ ! the ISO string at parse (streaming_control.f90 parse_iso_time_).
+ if (in_cfg%utc_set) params%nutc = in_cfg%utc_nutc
+
+ ! Re-apply per-mode policy whenever mode or trperiod changes.
+ if (in_cfg%mode_set .or. in_cfg%trperiod_set) then
+ ! Q65 60s emedelay (apply_per_mode_policy is emedelay-only).
+ call apply_per_mode_policy(params, io_mode, io_TRperiod)
+
+ ! Restore session-baseline nfa/nfb on mode change
+ ! when consumer didn't explicit-set this frame. Mirrors WAV semantics
+ ! (each invocation starts from CLI defaults).
+ if (.not. in_cfg%nfa_set) params%nfa = baseline_nfa
+ if (.not. in_cfg%nfb_set) params%nfb = baseline_nfb
+
+ ! ntol mode-change policy. The cap-vs-restore logic
+ ! differs from init-time (which always starts from CLI args), so the
+ ! ntol block lives here at config-time rather than in
+ ! apply_per_mode_policy.
+ if (.not. in_cfg%ntol_set) then
+ ! Restore per-mode default — NOT min()-clamping the carry-over.
+ select case (io_mode)
+ case (241, 242); params%ntol = 100 ! FST4/FST4W
+ case (65 + 9); params%ntol = 20 ! JT65+JT9 hard
+ case (66); params%ntol = 10 ! Q65 hard
+ case default; params%ntol = 1000 ! FT8/FT4/etc
+ end select
+ else
+ ! Consumer set explicit ntol — apply per-mode cap on the consumer
+ ! value. Q65 + JT65+JT9 always hard-override (decoder invariants).
+ select case (io_mode)
+ case (241, 242); params%ntol = min(params%ntol, 100)
+ case (66); params%ntol = 10
+ case (65 + 9); params%ntol = 20
+ case default; params%ntol = min(params%ntol, 1000)
+ end select
+ end if
+ end if
+ end subroutine apply_configure_fields
+
+end module streaming_apply
diff --git a/lib/streaming_control.f90 b/lib/streaming_control.f90
new file mode 100644
index 00000000..a65915bd
--- /dev/null
+++ b/lib/streaming_control.f90
@@ -0,0 +1,1779 @@
+! Streaming control-frame parser.
+!
+! Parses control JSON frames received on stdin via the streaming
+! framing. Two frame types are recognized today:
+!
+! {"t":"configure","mode":"FT8","depth":3,"rxfreq":1500,
+! "mycall":"KJ5HST","mygrid":"EM18","trperiod":15}
+! {"t":"halt"}
+!
+! Hand-rolled flat-JSON parser. Callers should treat unknown "t" values
+! as forward-compat extensions (mirrors the consumer-ignores-unknown
+! discipline from the ready handshake).
+!
+! Restrictions (deliberate scope):
+! - Flat objects only; no nested objects, no arrays.
+! - Numeric values must be plain decimal (no scientific notation).
+! - String values must NOT contain escape sequences. Callsigns, grids,
+! and mode names are alphanumeric ASCII per WSJT-X conventions, so
+! this is a safe simplification today; it can be extended if needed.
+
+module streaming_control
+ use, intrinsic :: iso_fortran_env, only: error_unit
+ implicit none
+ private
+
+ ! Action returned by parse_control_frame.
+ integer, parameter, public :: CTRL_UNKNOWN = 0
+ integer, parameter, public :: CTRL_CONFIGURE = 1
+ integer, parameter, public :: CTRL_HALT = 2
+ integer, parameter, public :: CTRL_PARSE_ERR = 3
+ ! downsam9 expands npts8 by 8 before filling its NFFT1 input buffer.
+ integer, parameter, public :: NPTS_C0_ARRAY_MIN = 1
+ integer, parameter, public :: NPTS_C0_ARRAY_MAX = 81648
+
+ type, public :: configure_fields
+ ! Each "*_set" flag indicates whether the JSON contained that key.
+ ! Callers apply only the fields that were set so partial updates work.
+ logical :: mode_set = .false.
+ integer :: mode = 0
+ logical :: mode_invalid = .false.
+ logical :: depth_set = .false.
+ integer :: depth = 0
+ logical :: rxfreq_set = .false.
+ integer :: rxfreq = 0
+ logical :: trperiod_set = .false.
+ real(8) :: trperiod = 0.d0
+ logical :: submode_set = .false.
+ integer :: submode = 0
+ logical :: mycall_set = .false.
+ character(len=12) :: mycall = ' '
+ logical :: mygrid_set = .false.
+ character(len=6) :: mygrid = ' '
+ ! Decode-bandwidth fields. Without these, the streaming
+ ! default ntol=20 confines decoding to ±20 Hz around audio offset 0,
+ ! missing the entire FT8 200-3000 Hz passband. Apply BEFORE the per-mode
+ ! policy block in apply_configure_fields so explicit values aren't capped by
+ ! min(ntol, 1000).
+ logical :: ntol_set = .false.
+ integer :: ntol = 0
+ logical :: nfa_set = .false.
+ integer :: nfa = 0
+ logical :: nfb_set = .false.
+ integer :: nfb = 0
+ ! Per-period UTC as HHMMSS integer. Threaded into
+ ! params%nutc so streaming_emit_decode can format the time field
+ ! correctly. Producer should send a fresh nutc in each period's
+ ! configure frame (mirrors WAV-path filename-derived per-invocation
+ ! UTC).
+ logical :: nutc_set = .false.
+ integer :: nutc = 0
+ ! Body schema version (RFC v1 §3). Absent => default 1 (forward-compat
+ ! with un-versioned producers). The receiver declines a frame whose
+ ! version it does not recognize (streaming_io.f90 CTRL_CONFIGURE arm).
+ logical :: version_set = .false.
+ integer :: version = 1
+ ! Phase 4 (RFC v1 §2): operator identity + frequency-window fields, flat
+ ! 1:1 onto params_block. Char widths match the bind(C) struct exactly
+ ! (his_call/my_b_call/his_b_call=12, his_grid=6) — applied via transfer()
+ ! in apply_configure_fields. Over-length callsign/grid keeps the current silent
+ ! truncation (consistent with mycall/mygrid; stricter validation is
+ ! out of scope). my_call_standard/his_call_standard are the
+ ! schema's first BOOLEAN keys (-> logical(c_bool) lmycallstd/lhiscallstd).
+ logical :: his_call_set = .false.
+ character(len=12) :: his_call = ' '
+ logical :: his_grid_set = .false.
+ character(len=6) :: his_grid = ' '
+ logical :: my_b_call_set = .false.
+ character(len=12) :: my_b_call = ' '
+ logical :: his_b_call_set = .false.
+ character(len=12) :: his_b_call = ' '
+ logical :: my_call_standard_set = .false.
+ logical :: my_call_standard = .false.
+ logical :: his_call_standard_set = .false.
+ logical :: his_call_standard = .false.
+ ! Frequency-window ints. tx_audio_offset_hz -> nftx DECOUPLES the tx side
+ ! from rxfreq (which sets both nfqso AND nftx), so it must apply AFTER the
+ ! rxfreq block. jt65_jt9_split_hz -> nfsplit (a mid-stream mode switch
+ ! does not auto-replay init-time fsplit).
+ ! max_drift_hz -> max_drift (Q65 drift search; default 0).
+ logical :: tx_audio_offset_hz_set = .false.
+ integer :: tx_audio_offset_hz = 0
+ logical :: jt65_jt9_split_hz_set = .false.
+ integer :: jt65_jt9_split_hz = 0
+ logical :: max_drift_hz_set = .false.
+ integer :: max_drift_hz = 0
+ ! Phase 5 (RFC v1 §2): decoder-tuning basic fields, flat 1:1 onto
+ ! params_block. dt_tolerance_seconds/eme_delay_seconds are the schema's
+ ! first real(8) members; they narrow to real(c_float) dttol/emedelay at
+ ! apply (§4 — narrowing documented in streaming_apply.f90 apply_configure_fields).
+ ! robust_mode/nagain_flag/clear_average are BOOLEANS -> logical(c_bool)
+ ! nrobust/nagain/nclearave (reuse the Phase 4 get_bool_/accept_bool path).
+ ! tx_mode is an enum (JT9->9 / JT65->65, or a raw int) -> ntxmode, mirroring
+ ! the "mode" parse. OBSERVABILITY (read-site map): on the
+ ! jt9 --stream FT8/JT9 fixtures kin_samples(kin)+nzhsym_per_period(nzhsym)
+ ! are OVERWRITTEN every period by the streaming period-prep block
+ ! (streaming_io.f90 ~:331/:339); dttol/minw/minsync/n2pass/nrobust/nclearave
+ ! are JT4/JT65/Q65-only; emedelay is forced to 0 by apply_per_mode_policy on
+ ! a mode-setting frame; ntxmode is read only in mode 65+9 — so 10 of 12 are
+ ! inert here (parse-unit + no-regression guard them). Only npts_c0_array(npts8)
+ ! and nagain_flag(nagain) reach the FT8/JT9 decoders.
+ logical :: dt_tolerance_seconds_set = .false.
+ real(8) :: dt_tolerance_seconds = 0.d0
+ logical :: eme_delay_seconds_set = .false.
+ real(8) :: eme_delay_seconds = 0.d0
+ logical :: kin_samples_set = .false.
+ integer :: kin_samples = 0
+ logical :: nzhsym_per_period_set = .false.
+ integer :: nzhsym_per_period = 0
+ logical :: npts_c0_array_set = .false.
+ integer :: npts_c0_array = 0
+ logical :: min_width_set = .false.
+ integer :: min_width = 0
+ logical :: min_sync_set = .false.
+ integer :: min_sync = 0
+ logical :: n_2pass_set = .false.
+ integer :: n_2pass = 0
+ logical :: robust_mode_set = .false.
+ logical :: robust_mode = .false.
+ logical :: nagain_flag_set = .false.
+ logical :: nagain_flag = .false.
+ logical :: tx_mode_set = .false.
+ integer :: tx_mode = 0
+ logical :: clear_average_set = .false.
+ logical :: clear_average = .false.
+ ! Phase 6 (RFC v1 §2): FT8/FT4 specifics cluster — 19 bools + 5 ints, flat
+ ! 1:1 onto params_block. OBSERVABILITY (read-site map + binary
+ ! probe): 21 of 24 are INERT on the jt9 --stream FT8/JT9 fixtures — most are
+ ! read ONLY inside the multithreaded-FT8 block (guard
+ ! if(params%lmultift8 .and. nmode==8), decoder.f90:192), which streaming
+ ! forces off (lmultift8=.false. constructed at jt9.f90:316); jt65_ap_on is
+ ! JT65-only; superfox_mode/even_sequence are superfox-path-only;
+ ! ft8_decoder_start is non-stream (WAV/shmem) path; hint_mode is never read. Only
+ ! ft8_ap_on/ap_cq_only/ap_width_hz reach the single-pass FT8 decoder
+ ! (decoder.f90:1141-1146, the lmultift8=.false. branch). ap_width_hz stores
+ ! the RAW int (decode halves it at lib/ft8var/ft8bvar.f90:1040; §3 napwid
+ ! note) — do NOT pre-scale. nagain_filter/stop_hint/hint_mode map to logical(c_bool)
+ ! nagainfil/nstophint/nhint despite the n-prefix. Bools reuse the Phase 4/5
+ ! get_bool_/accept_bool path; the 5 ints use get_int_. multithreaded_ft8 is
+ ! PARSED faithfully but APPLY ignores a non-false value (a true re-enables the
+ ! broken multithread branch -> 0 decodes; see streaming_apply.f90).
+ logical :: multithreaded_ft8_set = .false.
+ logical :: multithreaded_ft8 = .false.
+ logical :: ft8_cycles_set = .false.
+ integer :: ft8_cycles = 0
+ logical :: ft8_rxf_sensitivity_set = .false.
+ integer :: ft8_rxf_sensitivity = 0
+ logical :: ft8_threads_set = .false.
+ integer :: ft8_threads = 0
+ logical :: ft8_decoder_start_set = .false.
+ integer :: ft8_decoder_start = 0
+ logical :: ft8_low_threshold_set = .false.
+ logical :: ft8_low_threshold = .false.
+ logical :: ft8_subpass_set = .false.
+ logical :: ft8_subpass = .false.
+ logical :: ft8_ap_on_set = .false.
+ logical :: ft8_ap_on = .false.
+ logical :: ap_cq_only_set = .false.
+ logical :: ap_cq_only = .false.
+ logical :: ap_my_call_set = .false.
+ logical :: ap_my_call = .false.
+ logical :: jt65_ap_on_set = .false.
+ logical :: jt65_ap_on = .false.
+ logical :: ap_width_hz_set = .false.
+ integer :: ap_width_hz = 0
+ logical :: hide_ft8_duplicates_set = .false.
+ logical :: hide_ft8_duplicates = .false.
+ logical :: common_ft8b_set = .false.
+ logical :: common_ft8b = .false.
+ logical :: enable_dxc_search_set = .false.
+ logical :: enable_dxc_search = .false.
+ logical :: wide_dxc_search_set = .false.
+ logical :: wide_dxc_search = .false.
+ logical :: superfox_mode_set = .false.
+ logical :: superfox_mode = .false.
+ logical :: even_sequence_set = .false.
+ logical :: even_sequence = .false.
+ logical :: hound_mode_set = .false.
+ logical :: hound_mode = .false.
+ logical :: multi_instance_set = .false.
+ logical :: multi_instance = .false.
+ logical :: skip_tx1_set = .false.
+ logical :: skip_tx1 = .false.
+ logical :: nagain_filter_set = .false.
+ logical :: nagain_filter = .false.
+ logical :: stop_hint_set = .false.
+ logical :: stop_hint = .false.
+ logical :: hint_mode_set = .false.
+ logical :: hint_mode = .false.
+ ! Phase 7 (RFC v1 §2): diagnostic / sequencing fields — 2 bools + 4 ints,
+ ! flat 1:1 onto params_block. OBSERVABILITY (read-site map):
+ ! ALL 6 are INERT on the jt9 --stream FT8/JT9 fixtures. Five are read ONLY
+ ! inside the multithreaded-FT8 block (guard
+ ! if(params%lmultift8 .and. nmode==8), decoder.f90:192..1148, which streaming
+ ! forces off via lmultift8=.false.): currently_txing (ltxing, decoder.f90:228),
+ ! mode_changed (lmodechanged, :193), sec_band_changed (nsecbandchanged,
+ ! :208), delay_units (ndelay, :201/:1077), last_tx_seconds_ago (nlasttx,
+ ! :337, consumed only by the multithread FT8-variant decoder ft8bvar/ft8svar).
+ ! qso_progress_state (nQSOProgress) DOES reach the single-pass FT8 decoder
+ ! (decoder.f90:1141) but only steers AP decoding passes; the FT8 fixture has
+ ! no AP-only decodes, so an IN-RANGE value is empirically inert (probed:
+ ! qso=5 gives a byte-identical 21-decode set). It is the one Phase 7 key the
+ ! apply GUARDS (streaming_apply.f90): an OUT-OF-range value (<0 or >5) is a raw
+ ! index into nappasses(0:5)/naptypes(0:5,4) at ft8b.f90:274/299 -> a decoder
+ ! crash, so the apply ignores it (valid [0,5] pass through; see the apply
+ ! comment). Parse stays a plain get_int_ (no parse-time range check -- v1 does
+ ! type validation only, not range validation). No decode-output gate is
+ ! possible for the inert in-range values -> parse-unit + apply-routing-unit +
+ ! no-regression are the coverage (like Phase 4); the out-of-range guard is
+ ! covered by a survival fixture + an apply-routing assert. The 4 ints use
+ ! get_int_; the 2 bools (currently_txing/mode_changed, logical(c_bool) in
+ ! jt9com.f90) reuse the get_bool_/accept_bool path.
+ !
+ ! OMITTED Phase 7 wire keys (intentionally NOT exposed in v1):
+ ! utc_list / utc_list_0..9 / nlist_count — map to listutc, which is read
+ ! ONLY by the JT4 averaging path (decoder.f90:1310, the nmode==4 block) and
+ ! has no writer in the decode core — dead for the FT8/JT9/FT4/Q65 stream
+ ! paths. Exposing it would be a no-op there.
+ ! datetime — read into a dead local at decoder.f90:99 (assigned, never used);
+ ! no decode effect. Only date->yymmdd carries time (Phase 8, §6.1).
+ ! from_wav_file (ndiskdat) / new_data_flag (newdat) — receiver-managed
+ ! invariants (§6.1/§9): the receiver hard-sets both, and a producer
+ ! override would break the one-shot decode contract. Not producer-settable.
+ logical :: last_tx_seconds_ago_set = .false.
+ integer :: last_tx_seconds_ago = 0
+ logical :: currently_txing_set = .false.
+ logical :: currently_txing = .false.
+ logical :: mode_changed_set = .false.
+ logical :: mode_changed = .false.
+ logical :: qso_progress_state_set = .false.
+ integer :: qso_progress_state = 0
+ logical :: sec_band_changed_set = .false.
+ integer :: sec_band_changed = 0
+ logical :: delay_units_set = .false.
+ integer :: delay_units = 0
+ ! Phase 8 (RFC v1 §2/§6): string & scaled / derived fields. Unlike Phases
+ ! 4-7 (flat value-extract), these REWRITE the wire value into the legacy
+ ! encoding AT PARSE, so the member holds the DERIVED legacy int, not the raw
+ ! wire form:
+ ! utc ("HH:MM:SS") -> utc_nutc = hh*10000+mm*100+ss (§6.3)
+ ! date ("YYYY-MM-DD") -> date_yymmdd = (yr-2000)*10000+mo*100+day (§6.4)
+ ! n_trials (int) -> n_trials_nranera = encode(n_trials) (§6.6)
+ ! parse_iso_time_/parse_iso_date_/ntrials_to_nranera_ do the work; a
+ ! malformed ISO string leaves the key UNSET (value-domain silent-skip, like a
+ ! bad mode name — type validation only, §4.1). TWO keys carry a PARSE-TIME
+ ! VALUE check that emits configure_type_error (the schema's first value-domain
+ ! errors, both RFC-mandated): n_trials NOT in {10^N, 3*10^N} (§6.6 — else a
+ ! bad nranera silently corrupts ntrials at decoder.f90:143-145) and date with
+ ! year >= 2100 (§6.4 — the 2000+offset YYMMDD encoding caps at 2099).
+ !
+ ! PRECEDENCE (§4.1): utc is a SECOND route to nutc alongside the legacy int
+ ! key nutc (kept for the legacy subset). utc_nutc is stored SEPARATELY from
+ ! nutc; apply_configure_fields applies nutc THEN utc_nutc, so utc WINS when a
+ ! frame carries both (richer ISO form). Order-independent at apply (the apply
+ ! sequence encodes precedence, not the parse order).
+ !
+ ! OBSERVABILITY (read-site map + binary probe): utc->nutc
+ ! round-trips through the decode "time" field (DECODE-OBSERVABLE via the
+ ! nutc round-trip fixtures). The other four are INERT on the FT8/JT9 stream
+ ! fixtures:
+ ! - candthin_threshold->ncandthin / dt_center_seconds->ndtcenter are read
+ ! ONLY by the multithread FT8-variant decoder my_ft8var%decodevar (all such
+ ! calls — first at decoder.f90:348 — scale /100 into the variant's sync
+ ! thresholds at lib/ft8var/sync8var.f90:17-18), and EVERY my_ft8var%decodevar
+ ! call lives inside the if(lmultift8 .and. nmode==8) block (opens
+ ! decoder.f90:192, else-arm at :1140) which streaming forces off — same class
+ ! as the Phase 6/7 multithread keys. The single-pass FT8 decoder
+ ! (my_ft8%decode, :1141) is NOT passed them. Probed inert: ncandthin
+ ! scaled to 5.0 and ndtcenter to a 2.0 s shift each gave the byte-identical
+ ! 21-decode FT8 set.
+ ! - n_trials->nranera->ntrials reaches only the JT65 deep-search decoder
+ ! (ntrials computed at decoder.f90:143-145, consumed at :1338/:1365), unused
+ ! on FT8/JT9.
+ ! - date->yymmdd's only param read site is decoder.f90:182 (guarded by
+ ! if(ncontest==7 .and. b_superfox .and. b_even_seq) -> superfox-only),
+ ! decoded into yr/mo/day at lib/superfox/sfrx_sub.f90:21,25-27.
+ ! None is an array index (array-bound check: nranera<=18 keeps the
+ ! decode-site 10**(nranera/2) within int32 for any parseable valid n_trials;
+ ! ncandthin/ndtcenter become real thresholds), so no out-of-range apply guard is
+ ! needed (unlike qso_progress_state). The four inert keys are guarded by
+ ! parse-unit + apply-routing-unit + no-regression (like Phase 4/6/7).
+ ! candthin_threshold/dt_center_seconds are real(8) members scaled at apply
+ ! (§4 — declare real(8), nint(wire*100), do NOT pre-store as int).
+ logical :: utc_set = .false.
+ integer :: utc_nutc = 0
+ logical :: date_set = .false.
+ integer :: date_yymmdd = 0
+ logical :: n_trials_set = .false.
+ integer :: n_trials_nranera = 0
+ logical :: candthin_threshold_set = .false.
+ real(8) :: candthin_threshold = 0.d0
+ logical :: dt_center_seconds_set = .false.
+ real(8) :: dt_center_seconds = 0.d0
+ ! ===== Phase 9 (RFC v1 §2.4/§2.5/§6.1/§6.2): bit-packed fields ===========
+ ! ndepth + nexp_decode are PACKED at parse (the post-pass pack_phase9_, called
+ ! after all keys are read) into the two derived *_packed members below, so
+ ! apply stays flat (mirrors Phase 8's derive-at-parse). The 9 unpacked keys +
+ ! their _set flags drive the pack; the post-pass also enforces the two
+ ! atomic-decline errors (the legacy depth full-int co-present with ANY unpacked
+ ! ndepth key -> conflicting encodings; depth_level vs q65_maxiters_level
+ ! inconsistency). Only depth_level is decode-observable on FT8/JT9 (the fixtures
+ ! run at depth=3 -> ndepth=3; depth_level=1 -> ndepth=1 changes the FT8 pass
+ ! structure ft8_decode.f90:178/182 and the JT9 iand(ndepth,7) tests
+ ! jt9_decode.f90:88,92) — the other 8 are Q65/JT65/FST4/JT4 or contest-branch
+ ! only (use_averaging q65_decode.f90:221/477+jt65_decode.f90:258;
+ ! deep_ap_search jt4_decode.f90:393+extract.f90:182; q65_auto_clear_average
+ ! q65_decode.f90:337/449; single_decode/vhf_features/noise_blanker reach
+ ! FST4/JT65 not the single-pass FT8 my_ft8%decode) -> parse-unit +
+ ! apply-routing-unit + no-regression (like Phase 4/6/7). NONE indexes an array
+ ! raw, so no out-of-range apply guard is needed; the pack instead
+ ! MASKS depth_level to 3 bits / q65_maxiters to 2 bits and CLAMPS the NB byte to
+ ! [0,255], so an out-of-range producer value cannot corrupt a sibling bit.
+ ! contest_type holds the COLLAPSED ncontest int (0-7) resolved at parse by
+ ! contest_string_to_int_ (SpecOp 5/8/9 -> 1; Configuration.hpp:318 enum).
+ ! -- ndepth group --
+ logical :: depth_level_set = .false.
+ integer :: depth_level = 0
+ logical :: q65_maxiters_level_set = .false.
+ integer :: q65_maxiters_level = 0
+ logical :: use_averaging_set = .false.
+ logical :: use_averaging = .false.
+ logical :: deep_ap_search_set = .false.
+ logical :: deep_ap_search = .false.
+ logical :: q65_auto_clear_average_set = .false.
+ logical :: q65_auto_clear_average = .false.
+ ! -- nexp_decode group --
+ logical :: contest_type_set = .false.
+ integer :: contest_type = 0 ! collapsed ncontest (0-7)
+ logical :: single_decode_set = .false.
+ logical :: single_decode = .false.
+ logical :: vhf_features_set = .false.
+ logical :: vhf_features = .false.
+ logical :: noise_blanker_level_set = .false.
+ integer :: noise_blanker_level = 0
+ ! -- derived packed ints (computed by pack_phase9_; apply routes these flat) --
+ logical :: ndepth_packed_set = .false.
+ integer :: ndepth_packed = 0
+ logical :: nexp_decode_packed_set = .false.
+ integer :: nexp_decode_packed = 0
+ end type configure_fields
+
+ ! Per-key type-validation result (RFC v1 §4.1, Phase 2). When a configure
+ ! frame carries a key whose JSON value type mismatches the schema (e.g.
+ ! {"depth":"abc"}), parse_control_frame records the FIRST such error here and
+ ! the caller declines the ENTIRE frame with configure_type_error (no partial
+ ! application). `present=.false.` means the frame is well-typed.
+ type, public :: control_type_error
+ logical :: present = .false.
+ character(len=24) :: key = ' ' ! offending key (no quotes)
+ character(len=16) :: expected = ' ' ! "int"/"real"/"string"/"string|int"
+ character(len=8) :: got = ' ' ! "string"/"number"/"bool"/"null"
+ end type control_type_error
+
+ public :: parse_control_frame
+ public :: mode_string_to_int
+
+contains
+
+ ! Parse a UTF-8 JSON line into an action and (for CONFIGURE) fields.
+ !
+ ! Type validation (RFC v1 §4.1, Phase 2): every configure key is checked
+ ! against its schema JSON type BEFORE its value is parsed. A key present with
+ ! a mismatched JSON type (e.g. {"depth":"abc"}) records the FIRST such error in
+ ! `terr`; the caller (streaming_io.f90 CTRL_CONFIGURE arm) then declines the
+ ! ENTIRE frame with configure_type_error — no partial application. Value-domain
+ ! issues (unknown mode name, over-length callsign, a fractional value for an
+ ! int key) are NOT type errors: they preserve the current silent behavior
+ ! (the key is simply left unset).
+ subroutine parse_control_frame(buf, action, cfg, terr)
+ character(len=*), intent(in) :: buf
+ integer, intent(out) :: action
+ type(configure_fields), intent(out) :: cfg
+ type(control_type_error), intent(out) :: terr
+
+ character(len=64) :: t_value
+ character(len=128) :: str_val
+ integer :: int_val, mode_value_start, mode_buffer_length
+ real(8) :: real_val
+ logical :: lval
+ logical :: ok, proceed, mode_present
+ integer :: hh, mm, ss, yr, mo, dy, enc ! Phase 8 ISO/encode temps
+ logical :: vok ! Phase 8 value-parse ok
+
+ action = CTRL_UNKNOWN
+ terr%present = .false.
+
+ ! Required: "t":<string>
+ call get_string_(buf, '"t"', t_value, ok)
+ if (.not. ok) then
+ action = CTRL_PARSE_ERR
+ return
+ end if
+
+ if (trim(t_value) .eq. 'halt') then
+ action = CTRL_HALT
+ return
+ end if
+
+ if (trim(t_value) .ne. 'configure') then
+ action = CTRL_UNKNOWN ! forward-compat: ignore unknown "t"
+ return
+ end if
+
+ action = CTRL_CONFIGURE
+
+ ! "mode" accepts a mode-name string ("FT8") or an integer code (8).
+ call check_type_(buf, '"mode"', 'mode', 'string|int', .true., .true., terr, proceed)
+ if (proceed) then
+ call get_string_(buf, '"mode"', str_val, ok)
+ if (ok) then
+ int_val = mode_string_to_int(trim(str_val))
+ if (int_val .ge. 0) then
+ cfg%mode_set = .true.
+ cfg%mode = int_val
+ else
+ cfg%mode_invalid = .true.
+ end if
+ else
+ call get_int_(buf, '"mode"', int_val, ok)
+ if (ok .and. valid_mode_int_(int_val)) then
+ cfg%mode_set = .true.
+ cfg%mode = int_val
+ else if (ok) then
+ cfg%mode_invalid = .true.
+ else
+ call find_key_(buf, '"mode"', mode_value_start, &
+ mode_buffer_length, mode_present)
+ cfg%mode_invalid = mode_present
+ end if
+ end if
+ end if
+
+ call check_type_(buf, '"depth"', 'depth', 'int', .false., .true., terr, proceed)
+ if (proceed) then
+ call get_int_(buf, '"depth"', int_val, ok)
+ if (ok) then
+ cfg%depth_set = .true.
+ cfg%depth = int_val
+ end if
+ end if
+
+ call check_type_(buf, '"rxfreq"', 'rxfreq', 'int', .false., .true., terr, proceed)
+ if (proceed) then
+ call get_int_(buf, '"rxfreq"', int_val, ok)
+ if (ok) then
+ cfg%rxfreq_set = .true.
+ cfg%rxfreq = int_val
+ end if
+ end if
+
+ call check_type_(buf, '"trperiod"', 'trperiod', 'real', .false., .true., terr, proceed)
+ if (proceed) then
+ call get_real_(buf, '"trperiod"', real_val, ok)
+ if (ok) then
+ cfg%trperiod_set = .true.
+ cfg%trperiod = real_val
+ end if
+ end if
+
+ ! "submode" accepts integer (0..n) or single-letter string ("A".."G").
+ call check_type_(buf, '"submode"', 'submode', 'string|int', .true., .true., terr, proceed)
+ if (proceed) then
+ call get_int_(buf, '"submode"', int_val, ok)
+ if (ok) then
+ cfg%submode_set = .true.
+ cfg%submode = int_val
+ else
+ call get_string_(buf, '"submode"', str_val, ok)
+ if (ok .and. len_trim(str_val) .ge. 1) then
+ cfg%submode_set = .true.
+ cfg%submode = iachar(str_val(1:1)) - iachar('A')
+ if (cfg%submode .lt. 0) cfg%submode = 0
+ end if
+ end if
+ end if
+
+ call check_type_(buf, '"mycall"', 'mycall', 'string', .true., .false., terr, proceed)
+ if (proceed) then
+ call get_string_(buf, '"mycall"', str_val, ok)
+ if (ok) then
+ cfg%mycall_set = .true.
+ cfg%mycall = str_val(:min(len(str_val), 12))
+ end if
+ end if
+
+ call check_type_(buf, '"mygrid"', 'mygrid', 'string', .true., .false., terr, proceed)
+ if (proceed) then
+ call get_string_(buf, '"mygrid"', str_val, ok)
+ if (ok) then
+ cfg%mygrid_set = .true.
+ cfg%mygrid = str_val(:min(len(str_val), 6))
+ end if
+ end if
+
+ call check_type_(buf, '"ntol"', 'ntol', 'int', .false., .true., terr, proceed)
+ if (proceed) then
+ call get_int_(buf, '"ntol"', int_val, ok)
+ if (ok) then
+ cfg%ntol_set = .true.
+ cfg%ntol = int_val
+ end if
+ end if
+
+ call check_type_(buf, '"nfa"', 'nfa', 'int', .false., .true., terr, proceed)
+ if (proceed) then
+ call get_int_(buf, '"nfa"', int_val, ok)
+ if (ok) then
+ cfg%nfa_set = .true.
+ cfg%nfa = int_val
+ end if
+ end if
+
+ call check_type_(buf, '"nfb"', 'nfb', 'int', .false., .true., terr, proceed)
+ if (proceed) then
+ call get_int_(buf, '"nfb"', int_val, ok)
+ if (ok) then
+ cfg%nfb_set = .true.
+ cfg%nfb = int_val
+ end if
+ end if
+
+ call check_type_(buf, '"nutc"', 'nutc', 'int', .false., .true., terr, proceed)
+ if (proceed) then
+ call get_int_(buf, '"nutc"', int_val, ok)
+ if (ok) then
+ cfg%nutc_set = .true.
+ cfg%nutc = int_val
+ end if
+ end if
+
+ ! ===== Phase 4: operator identity + frequency-window fields (RFC v1 §2) ===
+ ! his_call/his_grid/my_b_call/his_b_call: strings (like mycall/mygrid),
+ ! truncated to the struct char width at assignment (silent truncation).
+ call check_type_(buf, '"his_call"', 'his_call', 'string', .true., .false., terr, proceed)
+ if (proceed) then
+ call get_string_(buf, '"his_call"', str_val, ok)
+ if (ok) then
+ cfg%his_call_set = .true.
+ cfg%his_call = str_val(:min(len(str_val), 12))
+ end if
+ end if
+
+ call check_type_(buf, '"his_grid"', 'his_grid', 'string', .true., .false., terr, proceed)
+ if (proceed) then
+ call get_string_(buf, '"his_grid"', str_val, ok)
+ if (ok) then
+ cfg%his_grid_set = .true.
+ cfg%his_grid = str_val(:min(len(str_val), 6))
+ end if
+ end if
+
+ call check_type_(buf, '"my_b_call"', 'my_b_call', 'string', .true., .false., terr, proceed)
+ if (proceed) then
+ call get_string_(buf, '"my_b_call"', str_val, ok)
+ if (ok) then
+ cfg%my_b_call_set = .true.
+ cfg%my_b_call = str_val(:min(len(str_val), 12))
+ end if
+ end if
+
+ call check_type_(buf, '"his_b_call"', 'his_b_call', 'string', .true., .false., terr, proceed)
+ if (proceed) then
+ call get_string_(buf, '"his_b_call"', str_val, ok)
+ if (ok) then
+ cfg%his_b_call_set = .true.
+ cfg%his_b_call = str_val(:min(len(str_val), 12))
+ end if
+ end if
+
+ ! my_call_standard/his_call_standard: booleans (true/false). accept_bool
+ ! widens check_type_ to accept the 'bool' category for these two keys only.
+ call check_type_(buf, '"my_call_standard"', 'my_call_standard', 'bool', &
+ .false., .false., terr, proceed, accept_bool=.true.)
+ if (proceed) then
+ call get_bool_(buf, '"my_call_standard"', lval, ok)
+ if (ok) then
+ cfg%my_call_standard_set = .true.
+ cfg%my_call_standard = lval
+ end if
+ end if
+
+ call check_type_(buf, '"his_call_standard"', 'his_call_standard', 'bool', &
+ .false., .false., terr, proceed, accept_bool=.true.)
+ if (proceed) then
+ call get_bool_(buf, '"his_call_standard"', lval, ok)
+ if (ok) then
+ cfg%his_call_standard_set = .true.
+ cfg%his_call_standard = lval
+ end if
+ end if
+
+ ! Frequency-window ints (Hz).
+ call check_type_(buf, '"tx_audio_offset_hz"', 'tx_audio_offset_hz', 'int', &
+ .false., .true., terr, proceed)
+ if (proceed) then
+ call get_int_(buf, '"tx_audio_offset_hz"', int_val, ok)
+ if (ok) then
+ cfg%tx_audio_offset_hz_set = .true.
+ cfg%tx_audio_offset_hz = int_val
+ end if
+ end if
+
+ call check_type_(buf, '"jt65_jt9_split_hz"', 'jt65_jt9_split_hz', 'int', &
+ .false., .true., terr, proceed)
+ if (proceed) then
+ call get_int_(buf, '"jt65_jt9_split_hz"', int_val, ok)
+ if (ok) then
+ cfg%jt65_jt9_split_hz_set = .true.
+ cfg%jt65_jt9_split_hz = int_val
+ end if
+ end if
+
+ call check_type_(buf, '"max_drift_hz"', 'max_drift_hz', 'int', &
+ .false., .true., terr, proceed)
+ if (proceed) then
+ call get_int_(buf, '"max_drift_hz"', int_val, ok)
+ if (ok) then
+ cfg%max_drift_hz_set = .true.
+ cfg%max_drift_hz = int_val
+ end if
+ end if
+
+ ! ===== Phase 5: decoder-tuning basic fields (RFC v1 §2) =================
+ ! Two real keys (parsed as real(8); narrowed to real(c_float) at apply, §4).
+ call check_type_(buf, '"dt_tolerance_seconds"', 'dt_tolerance_seconds', &
+ 'real', .false., .true., terr, proceed)
+ if (proceed) then
+ call get_real_(buf, '"dt_tolerance_seconds"', real_val, ok)
+ if (ok) then
+ cfg%dt_tolerance_seconds_set = .true.
+ cfg%dt_tolerance_seconds = real_val
+ end if
+ end if
+
+ call check_type_(buf, '"eme_delay_seconds"', 'eme_delay_seconds', &
+ 'real', .false., .true., terr, proceed)
+ if (proceed) then
+ call get_real_(buf, '"eme_delay_seconds"', real_val, ok)
+ if (ok) then
+ cfg%eme_delay_seconds_set = .true.
+ cfg%eme_delay_seconds = real_val
+ end if
+ end if
+
+ ! Six int keys.
+ call check_type_(buf, '"kin_samples"', 'kin_samples', 'int', &
+ .false., .true., terr, proceed)
+ if (proceed) then
+ call get_int_(buf, '"kin_samples"', int_val, ok)
+ if (ok) then
+ cfg%kin_samples_set = .true.
+ cfg%kin_samples = int_val
+ end if
+ end if
+
+ call check_type_(buf, '"nzhsym_per_period"', 'nzhsym_per_period', 'int', &
+ .false., .true., terr, proceed)
+ if (proceed) then
+ call get_int_(buf, '"nzhsym_per_period"', int_val, ok)
+ if (ok) then
+ cfg%nzhsym_per_period_set = .true.
+ cfg%nzhsym_per_period = int_val
+ end if
+ end if
+
+ call check_type_(buf, '"npts_c0_array"', 'npts_c0_array', 'int', &
+ .false., .true., terr, proceed)
+ if (proceed) then
+ call get_int_(buf, '"npts_c0_array"', int_val, ok)
+ if (ok .and. int_val .ge. NPTS_C0_ARRAY_MIN .and. &
+ int_val .le. NPTS_C0_ARRAY_MAX) then
+ cfg%npts_c0_array_set = .true.
+ cfg%npts_c0_array = int_val
+ end if
+ end if
+
+ call check_type_(buf, '"min_width"', 'min_width', 'int', &
+ .false., .true., terr, proceed)
+ if (proceed) then
+ call get_int_(buf, '"min_width"', int_val, ok)
+ if (ok) then
+ cfg%min_width_set = .true.
+ cfg%min_width = int_val
+ end if
+ end if
+
+ call check_type_(buf, '"min_sync"', 'min_sync', 'int', &
+ .false., .true., terr, proceed)
+ if (proceed) then
+ call get_int_(buf, '"min_sync"', int_val, ok)
+ if (ok) then
+ cfg%min_sync_set = .true.
+ cfg%min_sync = int_val
+ end if
+ end if
+
+ call check_type_(buf, '"n_2pass"', 'n_2pass', 'int', &
+ .false., .true., terr, proceed)
+ if (proceed) then
+ call get_int_(buf, '"n_2pass"', int_val, ok)
+ if (ok) then
+ cfg%n_2pass_set = .true.
+ cfg%n_2pass = int_val
+ end if
+ end if
+
+ ! Three bool keys (reuse the Phase 4 get_bool_ / accept_bool path).
+ call check_type_(buf, '"robust_mode"', 'robust_mode', 'bool', &
+ .false., .false., terr, proceed, accept_bool=.true.)
+ if (proceed) then
+ call get_bool_(buf, '"robust_mode"', lval, ok)
+ if (ok) then
+ cfg%robust_mode_set = .true.
+ cfg%robust_mode = lval
+ end if
+ end if
+
+ call check_type_(buf, '"nagain_flag"', 'nagain_flag', 'bool', &
+ .false., .false., terr, proceed, accept_bool=.true.)
+ if (proceed) then
+ call get_bool_(buf, '"nagain_flag"', lval, ok)
+ if (ok) then
+ cfg%nagain_flag_set = .true.
+ cfg%nagain_flag = lval
+ end if
+ end if
+
+ call check_type_(buf, '"clear_average"', 'clear_average', 'bool', &
+ .false., .false., terr, proceed, accept_bool=.true.)
+ if (proceed) then
+ call get_bool_(buf, '"clear_average"', lval, ok)
+ if (ok) then
+ cfg%clear_average_set = .true.
+ cfg%clear_average = lval
+ end if
+ end if
+
+ ! tx_mode: enum string ("JT9"/"JT65") or int (9/65) -> ntxmode. Mirrors the
+ ! "mode" block (string|int via mode_string_to_int). A negative map (unknown
+ ! name) leaves tx_mode unset, like "mode".
+ call check_type_(buf, '"tx_mode"', 'tx_mode', 'string|int', .true., .true., &
+ terr, proceed)
+ if (proceed) then
+ call get_string_(buf, '"tx_mode"', str_val, ok)
+ if (ok) then
+ int_val = mode_string_to_int(trim(str_val))
+ if (int_val .ge. 0) then
+ cfg%tx_mode_set = .true.
+ cfg%tx_mode = int_val
+ end if
+ else
+ call get_int_(buf, '"tx_mode"', int_val, ok)
+ if (ok) then
+ cfg%tx_mode_set = .true.
+ cfg%tx_mode = int_val
+ end if
+ end if
+ end if
+
+ ! ===== Phase 6: FT8/FT4 specifics cluster (RFC v1 §2) ==================
+ ! 19 bools + 5 ints, flat 1:1. Bools reuse the get_bool_/accept_bool path;
+ ! ints use get_int_. ap_width_hz is a wire int stored RAW (decode halves it).
+ call check_type_(buf, '"multithreaded_ft8"', 'multithreaded_ft8', 'bool', &
+ .false., .false., terr, proceed, accept_bool=.true.)
+ if (proceed) then
+ call get_bool_(buf, '"multithreaded_ft8"', lval, ok)
+ if (ok) then
+ cfg%multithreaded_ft8_set = .true.
+ cfg%multithreaded_ft8 = lval
+ end if
+ end if
+
+ call check_type_(buf, '"ft8_cycles"', 'ft8_cycles', 'int', &
+ .false., .true., terr, proceed)
+ if (proceed) then
+ call get_int_(buf, '"ft8_cycles"', int_val, ok)
+ if (ok) then
+ cfg%ft8_cycles_set = .true.
+ cfg%ft8_cycles = int_val
+ end if
+ end if
+
+ call check_type_(buf, '"ft8_rxf_sensitivity"', 'ft8_rxf_sensitivity', &
+ 'int', .false., .true., terr, proceed)
+ if (proceed) then
+ call get_int_(buf, '"ft8_rxf_sensitivity"', int_val, ok)
+ if (ok) then
+ cfg%ft8_rxf_sensitivity_set = .true.
+ cfg%ft8_rxf_sensitivity = int_val
+ end if
+ end if
+
+ call check_type_(buf, '"ft8_threads"', 'ft8_threads', 'int', &
+ .false., .true., terr, proceed)
+ if (proceed) then
+ call get_int_(buf, '"ft8_threads"', int_val, ok)
+ if (ok) then
+ cfg%ft8_threads_set = .true.
+ cfg%ft8_threads = int_val
+ end if
+ end if
+
+ call check_type_(buf, '"ft8_decoder_start"', 'ft8_decoder_start', 'int', &
+ .false., .true., terr, proceed)
+ if (proceed) then
+ call get_int_(buf, '"ft8_decoder_start"', int_val, ok)
+ if (ok) then
+ cfg%ft8_decoder_start_set = .true.
+ cfg%ft8_decoder_start = int_val
+ end if
+ end if
+
+ call check_type_(buf, '"ft8_low_threshold"', 'ft8_low_threshold', 'bool', &
+ .false., .false., terr, proceed, accept_bool=.true.)
+ if (proceed) then
+ call get_bool_(buf, '"ft8_low_threshold"', lval, ok)
+ if (ok) then
+ cfg%ft8_low_threshold_set = .true.
+ cfg%ft8_low_threshold = lval
+ end if
+ end if
+
+ call check_type_(buf, '"ft8_subpass"', 'ft8_subpass', 'bool', &
+ .false., .false., terr, proceed, accept_bool=.true.)
+ if (proceed) then
+ call get_bool_(buf, '"ft8_subpass"', lval, ok)
+ if (ok) then
+ cfg%ft8_subpass_set = .true.
+ cfg%ft8_subpass = lval
+ end if
+ end if
+
+ call check_type_(buf, '"ft8_ap_on"', 'ft8_ap_on', 'bool', &
+ .false., .false., terr, proceed, accept_bool=.true.)
+ if (proceed) then
+ call get_bool_(buf, '"ft8_ap_on"', lval, ok)
+ if (ok) then
+ cfg%ft8_ap_on_set = .true.
+ cfg%ft8_ap_on = lval
+ end if
+ end if
+
+ call check_type_(buf, '"ap_cq_only"', 'ap_cq_only', 'bool', &
+ .false., .false., terr, proceed, accept_bool=.true.)
+ if (proceed) then
+ call get_bool_(buf, '"ap_cq_only"', lval, ok)
+ if (ok) then
+ cfg%ap_cq_only_set = .true.
+ cfg%ap_cq_only = lval
+ end if
+ end if
+
+ call check_type_(buf, '"ap_my_call"', 'ap_my_call', 'bool', &
+ .false., .false., terr, proceed, accept_bool=.true.)
+ if (proceed) then
+ call get_bool_(buf, '"ap_my_call"', lval, ok)
+ if (ok) then
+ cfg%ap_my_call_set = .true.
+ cfg%ap_my_call = lval
+ end if
+ end if
+
+ call check_type_(buf, '"jt65_ap_on"', 'jt65_ap_on', 'bool', &
+ .false., .false., terr, proceed, accept_bool=.true.)
+ if (proceed) then
+ call get_bool_(buf, '"jt65_ap_on"', lval, ok)
+ if (ok) then
+ cfg%jt65_ap_on_set = .true.
+ cfg%jt65_ap_on = lval
+ end if
+ end if
+
+ call check_type_(buf, '"ap_width_hz"', 'ap_width_hz', 'int', &
+ .false., .true., terr, proceed)
+ if (proceed) then
+ call get_int_(buf, '"ap_width_hz"', int_val, ok)
+ if (ok) then
+ cfg%ap_width_hz_set = .true.
+ cfg%ap_width_hz = int_val
+ end if
+ end if
+
+ call check_type_(buf, '"hide_ft8_duplicates"', 'hide_ft8_duplicates', &
+ 'bool', .false., .false., terr, proceed, accept_bool=.true.)
+ if (proceed) then
+ call get_bool_(buf, '"hide_ft8_duplicates"', lval, ok)
+ if (ok) then
+ cfg%hide_ft8_duplicates_set = .true.
+ cfg%hide_ft8_duplicates = lval
+ end if
+ end if
+
+ call check_type_(buf, '"common_ft8b"', 'common_ft8b', 'bool', &
+ .false., .false., terr, proceed, accept_bool=.true.)
+ if (proceed) then
+ call get_bool_(buf, '"common_ft8b"', lval, ok)
+ if (ok) then
+ cfg%common_ft8b_set = .true.
+ cfg%common_ft8b = lval
+ end if
+ end if
+
+ call check_type_(buf, '"enable_dxc_search"', 'enable_dxc_search', 'bool', &
+ .false., .false., terr, proceed, accept_bool=.true.)
+ if (proceed) then
+ call get_bool_(buf, '"enable_dxc_search"', lval, ok)
+ if (ok) then
+ cfg%enable_dxc_search_set = .true.
+ cfg%enable_dxc_search = lval
+ end if
+ end if
+
+ call check_type_(buf, '"wide_dxc_search"', 'wide_dxc_search', 'bool', &
+ .false., .false., terr, proceed, accept_bool=.true.)
+ if (proceed) then
+ call get_bool_(buf, '"wide_dxc_search"', lval, ok)
+ if (ok) then
+ cfg%wide_dxc_search_set = .true.
+ cfg%wide_dxc_search = lval
+ end if
+ end if
+
+ call check_type_(buf, '"superfox_mode"', 'superfox_mode', 'bool', &
+ .false., .false., terr, proceed, accept_bool=.true.)
+ if (proceed) then
+ call get_bool_(buf, '"superfox_mode"', lval, ok)
+ if (ok) then
+ cfg%superfox_mode_set = .true.
+ cfg%superfox_mode = lval
+ end if
+ end if
+
+ call check_type_(buf, '"even_sequence"', 'even_sequence', 'bool', &
+ .false., .false., terr, proceed, accept_bool=.true.)
+ if (proceed) then
+ call get_bool_(buf, '"even_sequence"', lval, ok)
+ if (ok) then
+ cfg%even_sequence_set = .true.
+ cfg%even_sequence = lval
+ end if
+ end if
+
+ call check_type_(buf, '"hound_mode"', 'hound_mode', 'bool', &
+ .false., .false., terr, proceed, accept_bool=.true.)
+ if (proceed) then
+ call get_bool_(buf, '"hound_mode"', lval, ok)
+ if (ok) then
+ cfg%hound_mode_set = .true.
+ cfg%hound_mode = lval
+ end if
+ end if
+
+ call check_type_(buf, '"multi_instance"', 'multi_instance', 'bool', &
+ .false., .false., terr, proceed, accept_bool=.true.)
+ if (proceed) then
+ call get_bool_(buf, '"multi_instance"', lval, ok)
+ if (ok) then
+ cfg%multi_instance_set = .true.
+ cfg%multi_instance = lval
+ end if
+ end if
+
+ call check_type_(buf, '"skip_tx1"', 'skip_tx1', 'bool', &
+ .false., .false., terr, proceed, accept_bool=.true.)
+ if (proceed) then
+ call get_bool_(buf, '"skip_tx1"', lval, ok)
+ if (ok) then
+ cfg%skip_tx1_set = .true.
+ cfg%skip_tx1 = lval
+ end if
+ end if
+
+ call check_type_(buf, '"nagain_filter"', 'nagain_filter', 'bool', &
+ .false., .false., terr, proceed, accept_bool=.true.)
+ if (proceed) then
+ call get_bool_(buf, '"nagain_filter"', lval, ok)
+ if (ok) then
+ cfg%nagain_filter_set = .true.
+ cfg%nagain_filter = lval
+ end if
+ end if
+
+ call check_type_(buf, '"stop_hint"', 'stop_hint', 'bool', &
+ .false., .false., terr, proceed, accept_bool=.true.)
+ if (proceed) then
+ call get_bool_(buf, '"stop_hint"', lval, ok)
+ if (ok) then
+ cfg%stop_hint_set = .true.
+ cfg%stop_hint = lval
+ end if
+ end if
+
+ call check_type_(buf, '"hint_mode"', 'hint_mode', 'bool', &
+ .false., .false., terr, proceed, accept_bool=.true.)
+ if (proceed) then
+ call get_bool_(buf, '"hint_mode"', lval, ok)
+ if (ok) then
+ cfg%hint_mode_set = .true.
+ cfg%hint_mode = lval
+ end if
+ end if
+
+ ! ===== Phase 7: diagnostic / sequencing fields (RFC v1 §2) =============
+ ! 2 bools + 4 ints, flat 1:1. Bools reuse the get_bool_/accept_bool path;
+ ! ints use get_int_. All inert on the stream path (multithread-block-only /
+ ! AP-only) — see the configure_fields Phase 7 comment for read sites + OMITs.
+ call check_type_(buf, '"last_tx_seconds_ago"', 'last_tx_seconds_ago', &
+ 'int', .false., .true., terr, proceed)
+ if (proceed) then
+ call get_int_(buf, '"last_tx_seconds_ago"', int_val, ok)
+ if (ok) then
+ cfg%last_tx_seconds_ago_set = .true.
+ cfg%last_tx_seconds_ago = int_val
+ end if
+ end if
+
+ call check_type_(buf, '"currently_txing"', 'currently_txing', 'bool', &
+ .false., .false., terr, proceed, accept_bool=.true.)
+ if (proceed) then
+ call get_bool_(buf, '"currently_txing"', lval, ok)
+ if (ok) then
+ cfg%currently_txing_set = .true.
+ cfg%currently_txing = lval
+ end if
+ end if
+
+ call check_type_(buf, '"mode_changed"', 'mode_changed', 'bool', &
+ .false., .false., terr, proceed, accept_bool=.true.)
+ if (proceed) then
+ call get_bool_(buf, '"mode_changed"', lval, ok)
+ if (ok) then
+ cfg%mode_changed_set = .true.
+ cfg%mode_changed = lval
+ end if
+ end if
+
+ call check_type_(buf, '"qso_progress_state"', 'qso_progress_state', &
+ 'int', .false., .true., terr, proceed)
+ if (proceed) then
+ call get_int_(buf, '"qso_progress_state"', int_val, ok)
+ if (ok) then
+ cfg%qso_progress_state_set = .true.
+ cfg%qso_progress_state = int_val
+ end if
+ end if
+
+ call check_type_(buf, '"sec_band_changed"', 'sec_band_changed', 'int', &
+ .false., .true., terr, proceed)
+ if (proceed) then
+ call get_int_(buf, '"sec_band_changed"', int_val, ok)
+ if (ok) then
+ cfg%sec_band_changed_set = .true.
+ cfg%sec_band_changed = int_val
+ end if
+ end if
+
+ call check_type_(buf, '"delay_units"', 'delay_units', 'int', &
+ .false., .true., terr, proceed)
+ if (proceed) then
+ call get_int_(buf, '"delay_units"', int_val, ok)
+ if (ok) then
+ cfg%delay_units_set = .true.
+ cfg%delay_units = int_val
+ end if
+ end if
+
+ ! ===== Phase 8: string & scaled / derived fields (RFC v1 §2/§6) =========
+ ! These derive the LEGACY encoding at parse (see the configure_fields Phase 8
+ ! comment): utc/date are ISO strings tokenized by parse_iso_time_/
+ ! parse_iso_date_; n_trials is encoded to nranera by ntrials_to_nranera_;
+ ! candthin_threshold/dt_center_seconds are wire reals scaled /100 at apply.
+ !
+ ! utc: ISO "HH:MM:SS" -> utc_nutc = hh*10000+mm*100+ss (§6.3, always full
+ ! HHMMSS). A malformed time string leaves utc unset (value-domain silent skip).
+ call check_type_(buf, '"utc"', 'utc', 'string', .true., .false., terr, proceed)
+ if (proceed) then
+ call get_string_(buf, '"utc"', str_val, ok)
+ if (ok) then
+ call parse_iso_time_(trim(str_val), hh, mm, ss, vok)
+ if (vok) then
+ cfg%utc_set = .true.
+ cfg%utc_nutc = hh * 10000 + mm * 100 + ss
+ end if
+ end if
+ end if
+
+ ! date: ISO "YYYY-MM-DD" -> date_yymmdd = (yr-2000)*10000+mo*100+day (§6.4).
+ ! The 2000+offset encoding caps at 2099 -> year >= 2100 is a configure_type_error
+ ! (RFC §6.4 "receiver emits error if year >= 2100"). A malformed date string
+ ! leaves date unset (value-domain silent skip). Only yymmdd is populated; the
+ ! datetime leg is intentionally OMITted (§6.1 — C/GUI filename field).
+ call check_type_(buf, '"date"', 'date', 'string', .true., .false., terr, proceed)
+ if (proceed) then
+ call get_string_(buf, '"date"', str_val, ok)
+ if (ok) then
+ call parse_iso_date_(trim(str_val), yr, mo, dy, vok)
+ if (vok) then
+ if (yr .ge. 2100) then
+ call set_type_error_(terr, 'date', 'year<2100', 'string')
+ else
+ cfg%date_set = .true.
+ cfg%date_yymmdd = (yr - 2000) * 10000 + mo * 100 + dy
+ end if
+ end if
+ end if
+ end if
+
+ ! n_trials: plain int on the wire -> encoded nranera (§6.6). The value MUST be
+ ! one of {10^N, 3*10^N}; anything else is a configure_type_error (§6.6 — a
+ ! non-conforming value would integer-divide into a silently-wrong ntrials at
+ ! decoder.f90:143-145). The check is a VALUE check (the JSON type is int), so it
+ ! runs AFTER the int parse and reuses the same configure_type_error envelope.
+ call check_type_(buf, '"n_trials"', 'n_trials', 'int', .false., .true., terr, proceed)
+ if (proceed) then
+ call get_int_(buf, '"n_trials"', int_val, ok)
+ if (ok) then
+ call ntrials_to_nranera_(int_val, enc, vok)
+ if (vok) then
+ cfg%n_trials_set = .true.
+ cfg%n_trials_nranera = enc
+ else
+ call set_type_error_(terr, 'n_trials', 'int 10^N|3*10^N', 'number')
+ end if
+ end if
+ end if
+
+ ! candthin_threshold / dt_center_seconds: wire reals, scaled /100 to int at
+ ! apply (§4/§6.5 — declare real(8), nint(wire*100)). Parsed like the Phase 5
+ ! reals (check_type_ 'real' -> get_real_).
+ call check_type_(buf, '"candthin_threshold"', 'candthin_threshold', &
+ 'real', .false., .true., terr, proceed)
+ if (proceed) then
+ call get_real_(buf, '"candthin_threshold"', real_val, ok)
+ if (ok) then
+ cfg%candthin_threshold_set = .true.
+ cfg%candthin_threshold = real_val
+ end if
+ end if
+
+ call check_type_(buf, '"dt_center_seconds"', 'dt_center_seconds', &
+ 'real', .false., .true., terr, proceed)
+ if (proceed) then
+ call get_real_(buf, '"dt_center_seconds"', real_val, ok)
+ if (ok) then
+ cfg%dt_center_seconds_set = .true.
+ cfg%dt_center_seconds = real_val
+ end if
+ end if
+
+ ! ===== Phase 9 (RFC v1 §2.4/§2.5/§6.1/§6.2): bit-packed unpacked keys ======
+ ! Each unpacked key parses into its own configure_fields member; pack_phase9_
+ ! (called after the version block) folds them into ndepth_packed /
+ ! nexp_decode_packed and enforces the two atomic-decline errors. depth_level/
+ ! q65_maxiters_level/noise_blanker_level are ints; use_averaging/deep_ap_search/
+ ! q65_auto_clear_average/single_decode/vhf_features are bools (get_bool_ /
+ ! accept_bool path); contest_type is an enum string resolved to the collapsed
+ ! ncontest int by contest_string_to_int_ (an unknown string leaves it unset — a
+ ! value-domain silent skip, exactly like an unknown mode name).
+ call check_type_(buf, '"depth_level"', 'depth_level', 'int', .false., .true., terr, proceed)
+ if (proceed) then
+ call get_int_(buf, '"depth_level"', int_val, ok)
+ if (ok) then
+ cfg%depth_level_set = .true.
+ cfg%depth_level = int_val
+ end if
+ end if
+
+ call check_type_(buf, '"q65_maxiters_level"', 'q65_maxiters_level', 'int', &
+ .false., .true., terr, proceed)
+ if (proceed) then
+ call get_int_(buf, '"q65_maxiters_level"', int_val, ok)
+ if (ok) then
+ cfg%q65_maxiters_level_set = .true.
+ cfg%q65_maxiters_level = int_val
+ end if
+ end if
+
+ call check_type_(buf, '"use_averaging"', 'use_averaging', 'bool', &
+ .false., .false., terr, proceed, accept_bool=.true.)
+ if (proceed) then
+ call get_bool_(buf, '"use_averaging"', lval, ok)
+ if (ok) then
+ cfg%use_averaging_set = .true.
+ cfg%use_averaging = lval
+ end if
+ end if
+
+ call check_type_(buf, '"deep_ap_search"', 'deep_ap_search', 'bool', &
+ .false., .false., terr, proceed, accept_bool=.true.)
+ if (proceed) then
+ call get_bool_(buf, '"deep_ap_search"', lval, ok)
+ if (ok) then
+ cfg%deep_ap_search_set = .true.
+ cfg%deep_ap_search = lval
+ end if
+ end if
+
+ call check_type_(buf, '"q65_auto_clear_average"', 'q65_auto_clear_average', &
+ 'bool', .false., .false., terr, proceed, accept_bool=.true.)
+ if (proceed) then
+ call get_bool_(buf, '"q65_auto_clear_average"', lval, ok)
+ if (ok) then
+ cfg%q65_auto_clear_average_set = .true.
+ cfg%q65_auto_clear_average = lval
+ end if
+ end if
+
+ ! contest_type: enum string -> collapsed ncontest int (0-7). Unknown -> unset.
+ call check_type_(buf, '"contest_type"', 'contest_type', 'string', &
+ .true., .false., terr, proceed)
+ if (proceed) then
+ call get_string_(buf, '"contest_type"', str_val, ok)
+ if (ok) then
+ int_val = contest_string_to_int_(trim(str_val))
+ if (int_val .ge. 0) then
+ cfg%contest_type_set = .true.
+ cfg%contest_type = int_val
+ end if
+ end if
+ end if
+
+ call check_type_(buf, '"single_decode"', 'single_decode', 'bool', &
+ .false., .false., terr, proceed, accept_bool=.true.)
+ if (proceed) then
+ call get_bool_(buf, '"single_decode"', lval, ok)
+ if (ok) then
+ cfg%single_decode_set = .true.
+ cfg%single_decode = lval
+ end if
+ end if
+
+ call check_type_(buf, '"vhf_features"', 'vhf_features', 'bool', &
+ .false., .false., terr, proceed, accept_bool=.true.)
+ if (proceed) then
+ call get_bool_(buf, '"vhf_features"', lval, ok)
+ if (ok) then
+ cfg%vhf_features_set = .true.
+ cfg%vhf_features = lval
+ end if
+ end if
+
+ call check_type_(buf, '"noise_blanker_level"', 'noise_blanker_level', 'int', &
+ .false., .true., terr, proceed)
+ if (proceed) then
+ call get_int_(buf, '"noise_blanker_level"', int_val, ok)
+ if (ok) then
+ cfg%noise_blanker_level_set = .true.
+ cfg%noise_blanker_level = int_val
+ end if
+ end if
+
+ ! Body schema version (RFC v1 §3). Absent => stays at the default 1.
+ call check_type_(buf, '"version"', 'version', 'int', .false., .true., terr, proceed)
+ if (proceed) then
+ call get_int_(buf, '"version"', int_val, ok)
+ if (ok) then
+ cfg%version_set = .true.
+ cfg%version = int_val
+ end if
+ end if
+
+ ! ===== Phase 9 post-pass: pack ndepth / nexp_decode + atomic-decline checks =
+ ! Runs after ALL keys are parsed (the depth-vs-unpacked conflict is cross-key).
+ call pack_phase9_(cfg, terr)
+
+ end subroutine parse_control_frame
+
+ ! Map a mode name string to the jt9 integer mode code. Returns -1 for
+ ! an unknown name. Mirrors lib/jt9.f90's case-table accepted modes.
+ function mode_string_to_int(name) result(mode_int)
+ character(len=*), intent(in) :: name
+ integer :: mode_int
+ character(len=16) :: u
+
+ u = upper_(name)
+ mode_int = -1
+ select case (trim(u))
+ case ('FT8'); mode_int = 8
+ case ('FT4'); mode_int = 5
+ case ('JT9'); mode_int = 9
+ case ('JT65'); mode_int = 65
+ case ('JT65+JT9'); mode_int = 74
+ case ('JT4'); mode_int = 4
+ case ('FST4'); mode_int = 240
+ case ('FST4W'); mode_int = 241
+ case ('Q65'); mode_int = 66
+ case ('MSK144'); mode_int = 144
+ end select
+ end function mode_string_to_int
+
+ pure function valid_mode_int_(mode_int) result(valid)
+ integer, intent(in) :: mode_int
+ logical :: valid
+
+ select case (mode_int)
+ case (4, 5, 8, 9, 65, 66, 74, 144, 240, 241, 242)
+ valid = .true.
+ case default
+ valid = .false.
+ end select
+ end function valid_mode_int_
+
+ ! ===== internals ======================================================
+
+ ! Find a string value in a flat JSON: looks for `key:"value"`, returns
+ ! `value` unescaped. ok=.false. on miss or syntax error.
+ subroutine get_string_(buf, key, val, ok)
+ character(len=*), intent(in) :: buf, key
+ character(len=*), intent(out) :: val
+ logical, intent(out) :: ok
+ integer :: vstart, vend, blen
+ logical :: found
+
+ val = ' '
+ ok = .false.
+ call find_key_(buf, key, vstart, blen, found)
+ if (.not. found) return
+ if (vstart .gt. blen) return
+ if (buf(vstart:vstart) .ne. '"') return
+ vstart = vstart + 1
+ vend = index(buf(vstart:blen), '"')
+ if (vend .le. 0) return
+ val = buf(vstart : vstart + vend - 2)
+ ok = .true.
+ end subroutine get_string_
+
+ ! Find an integer value in a flat JSON: looks for `key:NNN`, value is
+ ! decimal integer with optional sign. ok=.false. on miss or non-int.
+ subroutine get_int_(buf, key, val, ok)
+ character(len=*), intent(in) :: buf, key
+ integer, intent(out) :: val
+ logical, intent(out) :: ok
+ integer :: vstart, vend, blen, ios
+ character :: ch
+ logical :: found
+
+ val = 0
+ ok = .false.
+ call find_key_(buf, key, vstart, blen, found)
+ if (.not. found) return
+ if (vstart .gt. blen) return
+ if (buf(vstart:vstart) .eq. '"') return ! string, not int
+ vend = vstart
+ do while (vend .le. blen)
+ ch = buf(vend:vend)
+ if (ch .eq. ',' .or. ch .eq. '}' .or. ch .eq. ' ') exit
+ vend = vend + 1
+ end do
+ if (vend .le. vstart) return
+ read(buf(vstart : vend - 1), *, iostat=ios) val
+ if (ios .eq. 0) ok = .true.
+ end subroutine get_int_
+
+ ! Find a real value (e.g., trperiod=15 or 7.5).
+ subroutine get_real_(buf, key, val, ok)
+ character(len=*), intent(in) :: buf, key
+ real(8), intent(out) :: val
+ logical, intent(out) :: ok
+ integer :: vstart, vend, blen, ios
+ character :: ch
+ logical :: found
+
+ val = 0.d0
+ ok = .false.
+ call find_key_(buf, key, vstart, blen, found)
+ if (.not. found) return
+ if (vstart .gt. blen) return
+ if (buf(vstart:vstart) .eq. '"') return
+ vend = vstart
+ do while (vend .le. blen)
+ ch = buf(vend:vend)
+ if (ch .eq. ',' .or. ch .eq. '}' .or. ch .eq. ' ') exit
+ vend = vend + 1
+ end do
+ if (vend .le. vstart) return
+ read(buf(vstart : vend - 1), *, iostat=ios) val
+ if (ios .eq. 0) ok = .true.
+ end subroutine get_real_
+
+ ! Find a boolean value in a flat JSON: looks for `key:true` or `key:false`,
+ ! keying off the value's leading char ('t'/'f'). ok=.false. on miss or a
+ ! non-boolean value. Value EXTRACTION uses the same unanchored index() as
+ ! get_int_/get_string_/get_real_ (wire-parity — it only ever leaves a key
+ ! unset, never misapplies; TYPE validation anchors via check_type_/find_key_).
+ subroutine get_bool_(buf, key, val, ok)
+ character(len=*), intent(in) :: buf, key
+ logical, intent(out) :: val
+ logical, intent(out) :: ok
+ integer :: vstart, blen
+ character :: ch
+ logical :: found
+
+ val = .false.
+ ok = .false.
+ call find_key_(buf, key, vstart, blen, found)
+ if (.not. found) return
+ if (vstart .gt. blen) return
+ ch = buf(vstart:vstart)
+ if (ch .eq. 't') then
+ val = .true.; ok = .true.
+ else if (ch .eq. 'f') then
+ val = .false.; ok = .true.
+ end if
+ end subroutine get_bool_
+
+ ! ===== Phase 8 derivations (ISO parsers + nranera encoder) ===============
+
+ ! Read a NON-EMPTY all-digit field into an integer. ok=.false. if empty or any
+ ! char is a non-digit. A strict digit scan (not a bare list-directed read) is
+ ! required so a malformed ISO field like "34" missing from "13:34" or a stray
+ ! "30:99" tail is rejected rather than silently read as a partial number.
+ subroutine read_int_field_(s, val, ok)
+ character(len=*), intent(in) :: s
+ integer, intent(out) :: val
+ logical, intent(out) :: ok
+ integer :: i, c, ios
+ val = 0; ok = .false.
+ if (len(s) .lt. 1) return
+ do i = 1, len(s)
+ c = iachar(s(i:i))
+ if (c .lt. iachar('0') .or. c .gt. iachar('9')) return
+ end do
+ read(s, *, iostat=ios) val
+ if (ios .eq. 0) ok = .true.
+ end subroutine read_int_field_
+
+ ! Parse ISO 8601 time "HH:MM:SS" -> three ints (§6.3). ok=.false. on a malformed
+ ! string (not exactly two ':' separators with a non-empty all-digit field
+ ! between/around each). Ranges are NOT enforced (the caller packs HHMMSS; an
+ ! out-of-range component is a value-domain matter, not a parse error).
+ subroutine parse_iso_time_(s, hh, mm, ss, ok)
+ character(len=*), intent(in) :: s
+ integer, intent(out) :: hh, mm, ss
+ logical, intent(out) :: ok
+ integer :: c1, c2, n
+ hh = 0; mm = 0; ss = 0; ok = .false.
+ n = len_trim(s)
+ c1 = index(s(1:n), ':')
+ if (c1 .le. 1) return ! no 1st ':' or empty HH
+ c2 = index(s(c1+1:n), ':')
+ if (c2 .le. 1) return ! no 2nd ':' or empty MM
+ c2 = c1 + c2 ! absolute index of the 2nd ':'
+ if (c2 .ge. n) return ! nothing after the 2nd ':'
+ call read_int_field_(s(1:c1-1), hh, ok); if (.not. ok) return
+ call read_int_field_(s(c1+1:c2-1), mm, ok); if (.not. ok) return
+ call read_int_field_(s(c2+1:n), ss, ok)
+ end subroutine parse_iso_time_
+
+ ! Parse ISO 8601 date "YYYY-MM-DD" -> three ints (§6.4). ok=.false. on a
+ ! malformed string. The caller enforces the year<2100 cap.
+ subroutine parse_iso_date_(s, yr, mo, dy, ok)
+ character(len=*), intent(in) :: s
+ integer, intent(out) :: yr, mo, dy
+ logical, intent(out) :: ok
+ integer :: d1, d2, n
+ yr = 0; mo = 0; dy = 0; ok = .false.
+ n = len_trim(s)
+ d1 = index(s(1:n), '-')
+ if (d1 .le. 1) return ! no 1st '-' or empty YYYY
+ d2 = index(s(d1+1:n), '-')
+ if (d2 .le. 1) return ! no 2nd '-' or empty MM
+ d2 = d1 + d2 ! absolute index of the 2nd '-'
+ if (d2 .ge. n) return ! nothing after the 2nd '-'
+ call read_int_field_(s(1:d1-1), yr, ok); if (.not. ok) return
+ call read_int_field_(s(d1+1:d2-1), mo, ok); if (.not. ok) return
+ call read_int_field_(s(d2+1:n), dy, ok)
+ end subroutine parse_iso_date_
+
+ ! Encode a desired trial count n_trials into the legacy nranera index (§6.6):
+ ! nranera even -> ntrials = 10**(nranera/2) (decoder.f90:143)
+ ! nranera odd -> ntrials = 3*10**(nranera/2) (decoder.f90:144)
+ ! so n_trials must be 10^k or 3*10^k. ok=.false. for any other value (the caller
+ ! then emits configure_type_error). Strip trailing factors of 10; the residual
+ ! must be 1 (pure power of 10 -> nranera=2k) or 3 (3x -> nranera=2k+1). This is
+ ! functionally equivalent to the RFC §6.6 reference algorithm (a log10-based form;
+ ! same {10^N,3*10^N} acceptance set and same mapping), which likewise returns
+ ! nranera=0 for n_trials=1; note
+ ! decoder.f90:145 then special-cases nranera=0 -> ntrials=0 (a legacy-encoding
+ ! quirk a producer hits only by sending the degenerate n_trials=1 — documented,
+ ! not "fixed", per the wire-parity scope guardrail). nranera stays <= 18 for any
+ ! n_trials that fits int32 (10^9), so the decode-site 10**(nranera/2) cannot
+ ! overflow (read-site bound check — no out-of-range guard needed).
+ subroutine ntrials_to_nranera_(n_trials, nranera, ok)
+ integer, intent(in) :: n_trials
+ integer, intent(out) :: nranera
+ logical, intent(out) :: ok
+ integer :: v, k
+ nranera = 0; ok = .false.
+ if (n_trials .le. 0) return
+ v = n_trials
+ k = 0
+ do while (mod(v, 10) .eq. 0)
+ v = v / 10
+ k = k + 1
+ end do
+ if (v .eq. 1) then
+ nranera = 2 * k; ok = .true.
+ else if (v .eq. 3) then
+ nranera = 2 * k + 1; ok = .true.
+ end if
+ end subroutine ntrials_to_nranera_
+
+ ! Phase 9 post-pass: fold the unpacked ndepth/nexp_decode keys into the two
+ ! derived packed ints (cfg%ndepth_packed / cfg%nexp_decode_packed) and emit the
+ ! two RFC §6.1/§4.1 atomic-decline errors. Called once after all keys are parsed
+ ! (the legacy-depth-vs-unpacked conflict is inherently cross-key). Pack rule
+ ! (RFC §6.1/§6.2):
+ ! ndepth = depth_level(bits0-2) | use_avg<<4 | deep_ap<<5 | autoclr<<7
+ ! nexp_decode = ncontest(bits0-2) | single<<5 | vhf<<6 | q65_pileup<<7 | (nb+3)<<8
+ ! depth_level is masked to 3 bits and q65_maxiters to 2, the NB byte clamped to
+ ! [0,255], so an out-of-range producer value cannot corrupt a sibling bit (none
+ ! of these reaches a raw array index, so no decode crash). The
+ ! legacy `depth` full-int is applied verbatim by streaming_apply when NO
+ ! unpacked ndepth key is set; co-present with any unpacked key it is a conflict
+ ! (declined here, reusing the configure_type_error envelope for a VALUE-domain
+ ! error like Phase 8's n_trials/date checks).
+ subroutine pack_phase9_(cfg, terr)
+ type(configure_fields), intent(inout) :: cfg
+ type(control_type_error), intent(inout) :: terr
+ logical :: any_ndepth, any_nexp
+ integer :: dl, nb
+
+ any_ndepth = cfg%depth_level_set .or. cfg%q65_maxiters_level_set .or. &
+ cfg%use_averaging_set .or. cfg%deep_ap_search_set .or. &
+ cfg%q65_auto_clear_average_set
+ any_nexp = cfg%contest_type_set .or. cfg%single_decode_set .or. &
+ cfg%vhf_features_set .or. cfg%noise_blanker_level_set
+
+ ! Conflict: legacy depth (full int) AND any unpacked ndepth key -> decline.
+ if (cfg%depth_set .and. any_ndepth) then
+ call set_type_error_(terr, 'ndepth', 'depth|unpacked', 'conflict')
+ return
+ end if
+
+ ! Consistency: depth_level (bits 0-2) and q65_maxiters_level (bits 0-1) overlap
+ ! on bits 0-1 (RFC §6.1). If both are set they MUST agree; an inconsistent pair
+ ! is a configure_type_error.
+ if (cfg%depth_level_set .and. cfg%q65_maxiters_level_set) then
+ if (iand(cfg%depth_level, 3) .ne. iand(cfg%q65_maxiters_level, 3)) then
+ call set_type_error_(terr, 'q65_maxiters_level', 'match depth_lvl', 'conflict')
+ return
+ end if
+ end if
+
+ if (any_ndepth) then
+ ! Effective depth_level (bits 0-2): depth_level wins; else derive from
+ ! q65_maxiters_level (bits 0-1); else 0.
+ if (cfg%depth_level_set) then
+ dl = iand(cfg%depth_level, 7)
+ else if (cfg%q65_maxiters_level_set) then
+ dl = iand(cfg%q65_maxiters_level, 3)
+ else
+ dl = 0
+ end if
+ cfg%ndepth_packed = dl
+ if (cfg%use_averaging_set .and. cfg%use_averaging) &
+ cfg%ndepth_packed = ior(cfg%ndepth_packed, 16)
+ if (cfg%deep_ap_search_set .and. cfg%deep_ap_search) &
+ cfg%ndepth_packed = ior(cfg%ndepth_packed, 32)
+ if (cfg%q65_auto_clear_average_set .and. cfg%q65_auto_clear_average) &
+ cfg%ndepth_packed = ior(cfg%ndepth_packed, 128)
+ cfg%ndepth_packed_set = .true.
+ end if
+
+ if (any_nexp) then
+ cfg%nexp_decode_packed = iand(cfg%contest_type, 7) ! bits 0-2 (collapsed)
+ if (cfg%single_decode_set .and. cfg%single_decode) &
+ cfg%nexp_decode_packed = ior(cfg%nexp_decode_packed, 32)
+ if (cfg%vhf_features_set .and. cfg%vhf_features) &
+ cfg%nexp_decode_packed = ior(cfg%nexp_decode_packed, 64)
+ if (cfg%noise_blanker_level_set) then
+ nb = cfg%noise_blanker_level + 3 ! -3 offset (RFC §6.2; 3 = off)
+ if (nb .lt. 0) nb = 0
+ if (nb .gt. 255) nb = 255
+ cfg%nexp_decode_packed = cfg%nexp_decode_packed + nb * 256
+ end if
+ cfg%nexp_decode_packed_set = .true.
+ end if
+ end subroutine pack_phase9_
+
+ ! Map a contest_type wire string to the legacy ncontest int (nexp_decode bits
+ ! 0-2), applying the GUI's SpecOp 5/8/9 -> 1 collapse. The
+ ! SpecialOperatingActivity enum (Configuration.hpp:318, compiled only into the
+ ! widgets/GUI build so the headless core does not link it -> hardcoded here; this
+ ! comment guards a future upstream enum reorder) is:
+ ! NONE=0 NA_VHF=1 EU_VHF=2 FIELD_DAY=3 RTTY=4 WW_DIGI=5 FOX=6 HOUND=7
+ ! ARRL_DIGI=8 Q65_PILEUP=9 ; mainwindow.cpp:5469-5475 collapses 5,8,9 -> 1.
+ ! Returns -1 for an unknown string (caller leaves contest_type unset — a
+ ! value-domain silent skip, like an unknown mode name). Wire strings are the
+ ! lowercase snake_case names of RFC §6.2.
+ pure function contest_string_to_int_(s) result(n)
+ character(len=*), intent(in) :: s
+ integer :: n
+ select case (trim(s))
+ case ('none'); n = 0
+ case ('na_vhf'); n = 1
+ case ('eu_vhf'); n = 2
+ case ('field_day'); n = 3
+ case ('rtty'); n = 4
+ case ('ww_digi'); n = 1 ! SpecOp 5 -> collapsed to 1
+ case ('fox'); n = 6
+ case ('hound'); n = 7
+ case ('arrl_digi'); n = 1 ! SpecOp 8 -> collapsed to 1
+ case ('q65_pileup'); n = 1 ! SpecOp 9 -> collapsed to 1
+ case default; n = -1
+ end select
+ end function contest_string_to_int_
+
+ pure function upper_(s) result(u)
+ character(len=*), intent(in) :: s
+ character(len=len(s)) :: u
+ integer :: i, c
+ do i = 1, len(s)
+ c = iachar(s(i:i))
+ if (c .ge. iachar('a') .and. c .le. iachar('z')) then
+ u(i:i) = achar(c - 32)
+ else
+ u(i:i) = s(i:i)
+ end if
+ end do
+ end function upper_
+
+ ! Locate `key` (a quoted token such as '"depth"') at a STRUCTURAL key position
+ ! in a flat JSON buffer: preceded (after optional spaces) by '{' or ',' AND
+ ! followed (after optional spaces) by ':'. Returns found=.true. and vstart =
+ ! the index of the first value char (after the ':' and any spaces).
+ !
+ ! Anchoring on the structural form is what stops a quoted string VALUE that
+ ! happens to equal a key token (e.g. {"mycall":"mygrid"}) from being mistaken
+ ! for that key. The unanchored index() in get_int_/get_string_/get_real_ still
+ ! carries that pre-existing flaw for value EXTRACTION (left as-is for
+ ! wire-parity — it only ever leaves a key unset, never misapplies), but it must
+ ! NOT leak into TYPE validation: an unanchored hit on a value would falsely
+ ! decline a well-typed frame, or mask a genuine type error on the real key.
+ ! Scans matches left-to-right and returns the first real key.
+ subroutine find_key_(buf, key, vstart, blen, found)
+ character(len=*), intent(in) :: buf, key
+ integer, intent(out) :: vstart, blen
+ logical, intent(out) :: found
+ integer :: start, rel, kpos, klen, p
+
+ found = .false.
+ vstart = 0
+ blen = len_trim(buf)
+ klen = len_trim(key)
+ start = 1
+ do
+ if (start .gt. blen) return
+ rel = index(buf(start:blen), key)
+ if (rel .eq. 0) return
+ kpos = start + rel - 1 ! absolute start of this match
+ start = kpos + 1 ! next search resumes after this match
+ ! preceding non-space char must be '{' or ',' (a structural key position)
+ p = kpos - 1
+ do while (p .ge. 1)
+ if (buf(p:p) .ne. ' ') exit
+ p = p - 1
+ end do
+ if (p .lt. 1) cycle
+ if (buf(p:p) .ne. '{' .and. buf(p:p) .ne. ',') cycle
+ ! following non-space char must be ':'
+ p = kpos + klen
+ do while (p .le. blen)
+ if (buf(p:p) .ne. ' ') exit
+ p = p + 1
+ end do
+ if (p .gt. blen) cycle
+ if (buf(p:p) .ne. ':') cycle
+ ! skip ':' and following spaces -> first value char
+ p = p + 1
+ do while (p .le. blen)
+ if (buf(p:p) .ne. ' ') exit
+ p = p + 1
+ end do
+ vstart = p
+ found = .true.
+ return
+ end do
+ end subroutine find_key_
+
+ ! Classify the JSON value type of `key` in a flat JSON buffer, WITHOUT parsing
+ ! it, using the structural key locator above. Categorizes by the value's
+ ! leading char:
+ ! '"' -> 'string'
+ ! 't' / 'f' -> 'bool' (true/false)
+ ! 'n' -> 'null'
+ ! '}' / ',' -> 'absent' (empty value, e.g. {"mycall":}) — treated as
+ ! absent so malformed-empty values keep the
+ ! current silent-skip (configure_parse_error
+ ! territory, not a type error)
+ ! anything else -> 'number' (digit, sign, '.', or an odd value the typed
+ ! parser will soft-reject as today)
+ ! 'absent' means the key is not present (or has no value), which is never a
+ ! type error (RFC §4.1: absent key -> leave at current value).
+ subroutine value_category_(buf, key, cat)
+ character(len=*), intent(in) :: buf, key
+ character(len=*), intent(out) :: cat
+ integer :: vstart, blen
+ logical :: found
+ character :: c
+
+ cat = 'absent'
+ call find_key_(buf, key, vstart, blen, found)
+ if (.not. found) return
+ if (vstart .gt. blen) return
+ c = buf(vstart:vstart)
+ select case (c)
+ case ('"'); cat = 'string'
+ case ('t', 'f'); cat = 'bool'
+ case ('n'); cat = 'null'
+ case ('}', ','); cat = 'absent'
+ case default; cat = 'number'
+ end select
+ end subroutine value_category_
+
+ ! Type-check one configure key against its schema JSON type. Sets
+ ! proceed=.true. when the key is absent OR present with an accepted category
+ ! (the caller then parses it). Sets proceed=.false. and records the first
+ ! type error in `terr` when the key is present with a mismatched category.
+ ! accept_str : the key accepts a JSON string value
+ ! accept_num : the key accepts a JSON number value
+ ! accept_bool : (optional, default .false.) the key accepts a JSON boolean.
+ ! Added in Phase 4 for my_call_standard/his_call_standard;
+ ! existing int/real/string callers omit it and reject bools.
+ ! (a 'null' value is always a mismatch for the keys handled here.)
+ subroutine check_type_(buf, key, keyname, expected, accept_str, accept_num, &
+ terr, proceed, accept_bool)
+ character(len=*), intent(in) :: buf, key, keyname, expected
+ logical, intent(in) :: accept_str, accept_num
+ type(control_type_error), intent(inout) :: terr
+ logical, intent(out) :: proceed
+ logical, optional, intent(in) :: accept_bool
+ character(len=8) :: cat
+ logical :: acc_bool
+
+ acc_bool = .false.
+ if (present(accept_bool)) acc_bool = accept_bool
+ call value_category_(buf, key, cat)
+ proceed = .true.
+ if (trim(cat) .eq. 'absent') return
+ if (trim(cat) .eq. 'string' .and. accept_str) return
+ if (trim(cat) .eq. 'number' .and. accept_num) return
+ if (trim(cat) .eq. 'bool' .and. acc_bool) return
+ proceed = .false.
+ call set_type_error_(terr, keyname, expected, cat)
+ end subroutine check_type_
+
+ ! Record the FIRST per-key type error of a frame (subsequent ones are ignored;
+ ! the whole frame is declined regardless).
+ subroutine set_type_error_(terr, keyname, expected, got)
+ type(control_type_error), intent(inout) :: terr
+ character(len=*), intent(in) :: keyname, expected, got
+ if (terr%present) return
+ terr%present = .true.
+ terr%key = keyname
+ terr%expected = expected
+ terr%got = got
+ end subroutine set_type_error_
+
+end module streaming_control
diff --git a/lib/streaming_emit.f90 b/lib/streaming_emit.f90
new file mode 100644
index 00000000..fc86246a
--- /dev/null
+++ b/lib/streaming_emit.f90
@@ -0,0 +1,288 @@
+! Streaming NDJSON emitter.
+!
+! Hand-rolled JSON output for the streaming protocol.
+! Zero-dependency (no Qt, no nlohmann). One line per message on stdout.
+!
+! Schema (v=1):
+! ready {"v":1,"t":"ready","modes":[...],"protocol":1}
+! decode {"v":1,"t":"decode","mode":"FT8","time":"HHMMSS",
+! "snr":-12,"dt":0.6,"freq":1500,"message":"CQ ..."}
+! decode_finished {"v":1,"t":"decode_finished","period_end":"HHMMSS"}
+! error {"v":1,"t":"error","msg":"..."}
+! error (coded) {"v":1,"t":"error","code":"configure_parse_error","detail":"..."}
+! error (version) {"v":1,"t":"error","code":"unknown_schema_version","got":N}
+! error (type) {"v":1,"t":"error","code":"configure_type_error",
+! "key":"depth","expected":"int","got":"string"}
+! warning {"v":1,"t":"warning","code":"period_boundary_discard",
+! "discarded_samples":N}
+!
+! Activation: program jt9 calls streaming_emit_set_enabled(.true.) when
+! --stream is parsed. Decoder per-mode sites in lib/decoder.f90 query
+! streaming_emit_enabled() and call streaming_emit_decode() instead of
+! the legacy write(*,...) text format. When disabled, every routine in
+! this module is a no-op so non-streaming jt9 (WAV / shmem) is unchanged.
+
+module streaming_emit
+ use, intrinsic :: iso_fortran_env, only: int64, output_unit
+ implicit none
+ private
+
+ logical, save :: enabled_ = .false.
+
+ public :: streaming_emit_set_enabled
+ public :: streaming_emit_enabled
+ public :: streaming_emit_ready
+ public :: streaming_emit_decode
+ public :: streaming_emit_decode_finished
+ public :: streaming_emit_error
+ public :: streaming_emit_error_code
+ public :: streaming_emit_error_version
+ public :: streaming_emit_error_type
+ public :: streaming_emit_warning_samples
+
+contains
+
+ subroutine streaming_emit_set_enabled(flag)
+ logical, intent(in) :: flag
+ enabled_ = flag
+ end subroutine streaming_emit_set_enabled
+
+ pure function streaming_emit_enabled() result(v)
+ logical :: v
+ v = enabled_
+ end function streaming_emit_enabled
+
+ subroutine streaming_emit_ready()
+ if (.not. enabled_) return
+ ! Full jt9-internal mode support (FT8/FT4/JT9/JT65/JT4/FST4/
+ ! FST4W/Q65/MSK144). Modes outside this set (e.g., wsprd C2 streaming,
+ ! map65 I/Q) may extend this list later.
+ write(output_unit, '(a)') &
+ '{"v":1,"t":"ready","modes":["FT8","FT4","JT9","JT65","JT4","FST4","FST4W","Q65","MSK144"],"protocol":1}'
+ flush(output_unit)
+ end subroutine streaming_emit_ready
+
+ ! Emit one decode line.
+ !
+ ! mode_str : "FT8" / "FT4" / "JT9" / etc. (no escaping)
+ ! nutc : 4-digit (HHMM) or 6-digit (HHMMSS) integer time
+ ! snr : SNR in dB (integer; negative allowed)
+ ! dt : DT seconds (float)
+ ! freq : decode frequency offset in Hz (integer)
+ ! msg : decoded message text (gets JSON-escaped + trimmed)
+ subroutine streaming_emit_decode(mode_str, nutc, snr, dt, freq, msg)
+ character(len=*), intent(in) :: mode_str
+ integer, intent(in) :: nutc
+ integer, intent(in) :: snr
+ real, intent(in) :: dt
+ integer, intent(in) :: freq
+ character(len=*), intent(in) :: msg
+
+ character(len=8) :: time_str
+ character(len=320) :: msg_escaped
+ character(len=16) :: dt_str
+ integer :: msg_len
+
+ if (.not. enabled_) return
+
+ call format_utc_(nutc, time_str)
+ call json_escape_(msg, msg_escaped, msg_len)
+ call format_dt_(dt, dt_str)
+
+ write(output_unit, '(5a,i0,3a,i0,3a)') &
+ '{"v":1,"t":"decode","mode":"', trim(mode_str), &
+ '","time":"', trim(time_str), &
+ '","snr":', snr, &
+ ',"dt":', trim(dt_str), &
+ ',"freq":', freq, &
+ ',"message":"', msg_escaped(1:msg_len), &
+ '"}'
+ flush(output_unit)
+ end subroutine streaming_emit_decode
+
+ subroutine streaming_emit_decode_finished(nutc)
+ integer, intent(in) :: nutc
+ character(len=8) :: time_str
+ if (.not. enabled_) return
+ call format_utc_(nutc, time_str)
+ write(output_unit, '(3a)') &
+ '{"v":1,"t":"decode_finished","period_end":"', trim(time_str), &
+ '"}'
+ flush(output_unit)
+ end subroutine streaming_emit_decode_finished
+
+ subroutine streaming_emit_error(msg)
+ character(len=*), intent(in) :: msg
+ character(len=320) :: msg_escaped
+ integer :: msg_len
+ if (.not. enabled_) return
+ call json_escape_(msg, msg_escaped, msg_len)
+ write(output_unit, '(3a)') &
+ '{"v":1,"t":"error","msg":"', msg_escaped(1:msg_len), '"}'
+ flush(output_unit)
+ end subroutine streaming_emit_error
+
+ ! Structured configure-frame error (RFC v1 §4.1). Machine-readable `code`
+ ! plus a free-text `detail` (JSON-escaped). Used for configure_parse_error.
+ ! {"v":1,"t":"error","code":"<code>","detail":"<detail>"}
+ subroutine streaming_emit_error_code(code, detail)
+ character(len=*), intent(in) :: code
+ character(len=*), intent(in) :: detail
+ character(len=320) :: d_escaped
+ integer :: d_len
+ if (.not. enabled_) return
+ call json_escape_(detail, d_escaped, d_len)
+ write(output_unit, '(5a)') &
+ '{"v":1,"t":"error","code":"', trim(code), &
+ '","detail":"', d_escaped(1:d_len), '"}'
+ flush(output_unit)
+ end subroutine streaming_emit_error_code
+
+ ! Unknown schema-version error (RFC v1 §3/§4.1). `got` is the rejected
+ ! schema version the producer sent in the configure frame.
+ ! {"v":1,"t":"error","code":"unknown_schema_version","got":<n>}
+ subroutine streaming_emit_error_version(got)
+ integer, intent(in) :: got
+ if (.not. enabled_) return
+ write(output_unit, '(a,i0,a)') &
+ '{"v":1,"t":"error","code":"unknown_schema_version","got":', &
+ got, '}'
+ flush(output_unit)
+ end subroutine streaming_emit_error_version
+
+ ! Per-key type-mismatch error (RFC v1 §4.1). The producer sent `key` with a
+ ! JSON value of type `got` where the schema expects `expected`; the whole
+ ! configure frame is declined (no partial application). `key`/`expected`/`got`
+ ! are controlled-vocabulary ASCII tokens (no escaping needed).
+ ! {"v":1,"t":"error","code":"configure_type_error","key":"<k>",
+ ! "expected":"<e>","got":"<g>"}
+ subroutine streaming_emit_error_type(key, expected, got)
+ character(len=*), intent(in) :: key, expected, got
+ if (.not. enabled_) return
+ write(output_unit, '(7a)') &
+ '{"v":1,"t":"error","code":"configure_type_error","key":"', &
+ trim(key), '","expected":"', trim(expected), &
+ '","got":"', trim(got), '"}'
+ flush(output_unit)
+ end subroutine streaming_emit_error_type
+
+ subroutine streaming_emit_warning_samples(code, discarded_samples)
+ character(len=*), intent(in) :: code
+ integer(int64), intent(in) :: discarded_samples
+ if (.not. enabled_) return
+ write(output_unit, '(3a,i0,a)') &
+ '{"v":1,"t":"warning","code":"', trim(code), &
+ '","discarded_samples":', discarded_samples, '}'
+ flush(output_unit)
+ end subroutine streaming_emit_warning_samples
+
+ ! Internals -------------------------------------------------------------
+
+ ! Format dt (real seconds) as a JSON-safe number. gfortran's f0.x format
+ ! omits the leading zero (".25" instead of "0.25"), which violates RFC
+ ! 8259. This wrapper formats with f0.2, then re-inserts a leading zero
+ ! when the result starts with "." or "-.".
+ subroutine format_dt_(dt, str)
+ real, intent(in) :: dt
+ character(len=*), intent(out) :: str
+ character(len=16) :: tmp
+ write(tmp, '(f0.2)') dt
+ if (tmp(1:1) .eq. '.') then
+ str = '0' // trim(tmp)
+ else if (tmp(1:2) .eq. '-.') then
+ str = '-0' // trim(tmp(2:))
+ else
+ str = trim(tmp)
+ end if
+ end subroutine format_dt_
+
+ ! Format the integer nutc time as 6 chars. 4-digit HHMM gets
+ ! zero-extended to HHMM00 so consumers always see a 6-char field.
+ subroutine format_utc_(nutc, str)
+ integer, intent(in) :: nutc
+ character(len=*), intent(out) :: str
+ integer :: hh, mm, ss
+ str = '000000'
+ if (nutc .ge. 100000) then
+ hh = nutc / 10000
+ mm = mod(nutc/100, 100)
+ ss = mod(nutc, 100)
+ write(str, '(i2.2,i2.2,i2.2)') hh, mm, ss
+ else if (nutc .ge. 0) then
+ hh = nutc / 100
+ mm = mod(nutc, 100)
+ write(str, '(i2.2,i2.2,a2)') hh, mm, '00'
+ end if
+ end subroutine format_utc_
+
+ ! Minimal RFC-8259 JSON string escape covering the chars that can
+ ! appear in WSJT decode payloads:
+ ! - " -> \"
+ ! - \ -> \\
+ ! - \b \t \n \f \r -> \b \t \n \f \r
+ ! - other 0..0x1F -> \u00xx
+ ! - everything else (incl. printable ASCII, UTF-8 bytes) passes through
+ !
+ ! Trailing trim: the input is silently trimmed to its non-blank length
+ ! before escaping (decoder messages are right-padded fixed-width strings).
+ ! Output buffer must be large enough for worst case 6x input len.
+ subroutine json_escape_(in_str, out_str, out_len)
+ character(len=*), intent(in) :: in_str
+ character(len=*), intent(out) :: out_str
+ integer, intent(out) :: out_len
+
+ integer :: i, n, code
+ character :: c
+
+ n = len_trim(in_str)
+ out_len = 0
+ out_str = ' '
+
+ do i = 1, n
+ c = in_str(i:i)
+ code = iachar(c)
+ select case (code)
+ case (iachar('"'))
+ call append_pair_('\', '"', out_str, out_len)
+ case (iachar('\'))
+ call append_pair_('\', '\', out_str, out_len)
+ case (8) ! BS
+ call append_pair_('\', 'b', out_str, out_len)
+ case (9) ! HT
+ call append_pair_('\', 't', out_str, out_len)
+ case (10) ! LF
+ call append_pair_('\', 'n', out_str, out_len)
+ case (12) ! FF
+ call append_pair_('\', 'f', out_str, out_len)
+ case (13) ! CR
+ call append_pair_('\', 'r', out_str, out_len)
+ case (0:7, 11, 14:31)
+ call append_unicode_(code, out_str, out_len)
+ case default
+ out_len = out_len + 1
+ out_str(out_len:out_len) = c
+ end select
+ end do
+ end subroutine json_escape_
+
+ subroutine append_pair_(a, b, buf, idx)
+ character, intent(in) :: a, b
+ character(len=*), intent(inout) :: buf
+ integer, intent(inout) :: idx
+ idx = idx + 1; buf(idx:idx) = a
+ idx = idx + 1; buf(idx:idx) = b
+ end subroutine append_pair_
+
+ subroutine append_unicode_(code, buf, idx)
+ integer, intent(in) :: code
+ character(len=*), intent(inout) :: buf
+ integer, intent(inout) :: idx
+ character(len=4) :: hex4
+ write(hex4, '(z4.4)') code
+ idx = idx + 1; buf(idx:idx) = '\'
+ idx = idx + 1; buf(idx:idx) = 'u'
+ buf(idx+1:idx+4) = hex4
+ idx = idx + 4
+ end subroutine append_unicode_
+
+end module streaming_emit
diff --git a/lib/streaming_io.f90 b/lib/streaming_io.f90
new file mode 100644
index 00000000..98c9a13e
--- /dev/null
+++ b/lib/streaming_io.f90
@@ -0,0 +1,466 @@
+! Streaming I/O — framed audio + control on stdin.
+!
+! Reads framed messages from stdin. After a
+! one-time 8-byte WSJT session header (4-byte magic 'WSJT' + 1-byte fmt
+! + 1-byte channels + 2-byte rate_kHz LE), stdin carries a sequence of
+! frames:
+!
+! [type:1][len:4 LE][body:len bytes]
+!
+! Frame types:
+! 0x01 audio chunk body = N samples in declared format
+! 0x02 control JSON body = UTF-8 JSON line (no trailing newline)
+!
+! Other types are skipped (forward-compat: consumers ignore unknown
+! frame types just as NDJSON consumers ignore unknown "t" values).
+!
+! Control frames recognized today: {"t":"configure",...}, {"t":"halt"}.
+! See lib/streaming_control.f90 for the parser + schema.
+!
+! Apply policy:
+! configure : applied immediately at receive. If mode changes, the
+! in-flight sample accumulator is discarded (k=0) — the
+! buffered audio is wrong-format for the new mode anyway.
+! Producers should send `configure` FIRST, before any
+! audio frames; subsequent audio is interpreted under the
+! most recent configure.
+! halt : drain current period (call decoder if k>0), exit clean.
+!
+! Period boundary: when k accumulates to `npts` samples (mode-dependent),
+! we run the decoder. Audio frames that overflow `npts` have the excess
+! discarded — producers should chunk audio so that any single frame fits
+! within one period, OR send exactly `npts` samples per period. An
+! external producer should honor this.
+!
+! Format support: fmt=0x00 (int16 PCM) only. Other formats may be
+! added later.
+!
+! Platform: reads stdin through a portable C read-fully helper on fd 0
+! (stream_stdin_read_fully, lib/stream_stdin.c) — the same code path on
+! every platform. Fortran unit I/O cannot read a redirected stdin
+! portably: native Windows has no /dev/stdin, and re-OPENing the
+! preconnected unit 5 with ACCESS='STREAM' is non-conforming (F2018
+! 12.5.6.1 — ACCESS is not a changeable mode), rejected by libgfortran
+! everywhere. Binary mode is forced on Windows first via
+! stream_set_stdin_binary (lib/stream_setmode.c; no-op on POSIX). The
+! helper loops read() until the request fills or the stream truly ends,
+! so a pipe short-read is never mistaken for EOF.
+
+subroutine jt9_stream(shared_data, mode, TRperiod)
+ use, intrinsic :: iso_fortran_env, only: int8, int16, int64, error_unit
+ use, intrinsic :: ieee_arithmetic, only: ieee_is_finite
+ use, intrinsic :: iso_c_binding, only: c_int64_t
+ use prog_args, only: data_dir
+ use timer_module, only: timer
+ use streaming_emit, only: streaming_emit_ready, &
+ streaming_emit_decode_finished, streaming_emit_error, &
+ streaming_emit_error_code, streaming_emit_error_version, &
+ streaming_emit_error_type, streaming_emit_warning_samples
+ use streaming_control, only: parse_control_frame, configure_fields, &
+ control_type_error, CTRL_CONFIGURE, CTRL_HALT, CTRL_PARSE_ERR
+ use streaming_apply, only: apply_configure_fields
+
+ include 'jt9com.f90'
+
+ type(dec_data) :: shared_data
+ integer :: mode
+ real(8) :: TRperiod
+
+ integer, parameter :: HDR_LEN = 8
+ integer, parameter :: NFSAMPLE = 12000
+ integer, parameter :: FRAME_AUDIO = 1
+ integer, parameter :: FRAME_CONTROL = 2
+ integer, parameter :: CTL_BUF_LEN = 1024
+ ! 4-byte session magic "WSJT" (W=0x57 S=0x53 J=0x4A T=0x54)
+ integer(int8), parameter :: MAGIC(4) = [ &
+ int(z'57', int8), int(z'53', int8), &
+ int(z'4A', int8), int(z'54', int8) ]
+
+ integer :: ios, fmt, ch, rate_khz
+ integer(int8) :: hdr(HDR_LEN), type_byte(1), len_bytes(4)
+ integer(int64) :: frame_len_wide, max_audio_frame_bytes
+ integer :: frame_len
+
+ integer :: nsps, kstep, npts, k, nhsym, nhsym0
+ integer :: ingain, nminw, ihsym, npts8
+ real :: pxdb, df3, pxdbmax, s(NSMAX)
+ integer :: npct_unused
+ integer :: body_left, take_bytes, take_samples
+ integer(int64) :: discarded_samples
+ integer(int16) :: chunk(4096)
+ integer(int8) :: byte_sink(4096)
+ ! FT8 progressive-decode working buffer (mirrors jt9.f90:19's id2a) — the
+ ! FT8 decoder's `dd` array is populated only on nzhsym <= 47 calls, so we
+ ! mirror the WAV path's 41/47/50 call cadence with a working copy zeroed
+ ! past the per-call sample boundary.
+ integer(int16), save :: id2a(180000) !Keep this big array off the stack
+ character(len=CTL_BUF_LEN) :: ctl_buf
+ integer(int8) :: ctl_bytes(CTL_BUF_LEN)
+ integer :: i_ctl, prev_mode
+ ! Session-baseline nfa/nfb stashed after jt9.f90's init_streaming_extra_fields
+ ! returned. apply_configure_fields restores these on mode change with no
+ ! explicit consumer override; passed in as dummy args.
+ integer :: baseline_nfa, baseline_nfb
+ logical :: bLowSidelobes, eof_period, halt_req
+ type(configure_fields) :: cfg
+ type(control_type_error) :: terr
+ integer :: action
+
+ ! C stdin helpers. stream_set_stdin_binary (lib/stream_setmode.c) is a
+ ! no-op on POSIX; stream_stdin_read_fully (lib/stream_stdin.c) is the
+ ! read-fully byte reader used on all platforms.
+ interface
+ subroutine stream_set_stdin_binary() bind(C, name="stream_set_stdin_binary")
+ end subroutine stream_set_stdin_binary
+ function stream_stdin_read_fully(buf, n) result(nread) &
+ bind(C, name="stream_stdin_read_fully")
+ import :: c_int64_t
+ type(*), dimension(*), intent(inout) :: buf
+ integer(c_int64_t), value :: n
+ integer(c_int64_t) :: nread
+ end function stream_stdin_read_fully
+ end interface
+
+ bLowSidelobes = .false.
+ ingain = 0
+ nminw = 1
+
+ ! Read the framed byte stream from stdin via the C helper (stdin_read
+ ! below) — no Fortran unit is opened. Binary mode must be forced before
+ ! the first read on Windows or the CRT stops at 0x1A and rewrites CRLF.
+ call stream_set_stdin_binary()
+
+ call stdin_read(hdr, HDR_LEN, ios)
+ if (ios /= 0) then
+ call streaming_emit_error('short header (need 8 bytes)')
+ write(error_unit, '(a)') 'jt9 --stream: short header (need 8 bytes)'
+ stop 1
+ end if
+
+ if (any(hdr(1:4) /= MAGIC)) then
+ call streaming_emit_error('bad magic (expected ''WSJT'')')
+ write(error_unit, '(a)') 'jt9 --stream: bad magic (expected ''WSJT'')'
+ stop 1
+ end if
+
+ fmt = iand(int(hdr(5)), 255)
+ ch = iand(int(hdr(6)), 255)
+ rate_khz = iand(int(hdr(7)), 255) + ishft(iand(int(hdr(8)), 255), 8)
+
+ if (fmt /= 0) then
+ call streaming_emit_error('unsupported format (only fmt=0 int16 PCM supported)')
+ write(error_unit, '(a,i0,a)') &
+ 'jt9 --stream: unsupported fmt=', fmt, ' (only int16 PCM supported)'
+ stop 1
+ end if
+
+ if (ch /= 1) then
+ call streaming_emit_error('unsupported channel count (only mono supported)')
+ write(error_unit, '(a,i0,a)') &
+ 'jt9 --stream: unsupported channels=', ch, ' (only mono supported)'
+ stop 1
+ end if
+
+ if (rate_khz /= 12) then
+ call streaming_emit_error('unsupported sample rate (only 12 kHz supported)')
+ write(error_unit, '(a,i0,a)') &
+ 'jt9 --stream: unsupported rate=', rate_khz, ' kHz (only 12 kHz supported)'
+ stop 1
+ end if
+
+ write(error_unit, '(a,i0,a,i0,a,i0,a)') &
+ 'jt9 --stream: header ok (fmt=', fmt, ' ch=', ch, &
+ ' rate=', rate_khz, ' kHz)'
+
+ nsps = 6912
+ kstep = nsps / 2
+
+ ! Streaming-specific params override. The full params init was already
+ ! performed in jt9.f90's stream-mode dispatch arm via
+ ! init_default_params + init_streaming_extra_fields;
+ ! all that remains here is the streaming-vs-WAV diff.
+ !
+ ! CRITICAL: ndiskdat = .true. Without it, ft8_decode.f90:141 bails out at
+ ! tseq >= 14.3s ("real-time mode, leave time for next period") — but
+ ! streaming calls multimode_decoder once per period at end-of-period when
+ ! tseq >= 15.0, so the bail ALWAYS fires and zero decodes are produced.
+ ! ndiskdat=.true. tells the decoder "complete-period one-shot, don't bail".
+ shared_data%params%ndiskdat = .true.
+
+ ! Stash session-baseline nfa/nfb. apply_configure_fields
+ ! restores these on mode change with no explicit consumer override —
+ ! mirrors WAV semantics where each invocation starts from CLI defaults.
+ baseline_nfa = shared_data%params%nfa
+ baseline_nfb = shared_data%params%nfb
+
+ call streaming_emit_ready()
+ max_audio_frame_bytes = 2_int64 * int(size(shared_data%id2), int64)
+
+ ! ===== Outer period loop ===========================================
+ do
+ ! Compute per-period sample target. (Same multi-mode logic.)
+ npts = int(TRperiod * NFSAMPLE)
+ if (mode .eq. 5) npts = 21 * 3456
+ if (npts > size(shared_data%id2)) npts = size(shared_data%id2)
+ if (npts < 1) npts = NFSAMPLE
+ if (mode .eq. 8 .and. npts .gt. 50 * 3456) npts = 50 * 3456
+
+ shared_data%id2 = 0
+ k = 0
+ nhsym = 0
+ nhsym0 = 0 ! seed at 0 so the symspec catch-up loop is O(nhsym)
+ eof_period = .false.
+ halt_req = .false.
+
+ ! Inner frame loop: read frames until period full, halt, or EOF.
+ do while (k .lt. npts .and. .not. halt_req .and. .not. eof_period)
+ call stdin_read(type_byte, 1, ios)
+ if (ios /= 0) then
+ eof_period = .true.; exit
+ end if
+ call stdin_read(len_bytes, 4, ios)
+ if (ios /= 0) then
+ eof_period = .true.; exit
+ end if
+ frame_len_wide = iand(int(len_bytes(1), int64), int(z'FF', int64)) &
+ + 256_int64 * iand(int(len_bytes(2), int64), int(z'FF', int64)) &
+ + 65536_int64 * iand(int(len_bytes(3), int64), int(z'FF', int64)) &
+ + 16777216_int64 * iand(int(len_bytes(4), int64), int(z'FF', int64))
+ if (frame_len_wide .gt. max_audio_frame_bytes) then
+ call streaming_emit_error_code('frame_too_large', &
+ 'frame length exceeds the streaming sample-buffer capacity')
+ write(error_unit, '(a,i0,a,i0)') 'jt9 --stream: frame length ', &
+ frame_len_wide, ' exceeds capacity ', max_audio_frame_bytes
+ stop 1
+ end if
+ frame_len = int(frame_len_wide)
+
+ if (iand(int(type_byte(1)), 255) .eq. FRAME_AUDIO) then
+ if (mod(frame_len, 2) /= 0) then
+ call streaming_emit_error_code('odd_audio_frame', &
+ 'audio frame length must contain whole int16 samples')
+ body_left = frame_len
+ do while (body_left .gt. 0)
+ take_bytes = min(body_left, size(byte_sink))
+ call stdin_read(byte_sink, take_bytes, ios)
+ if (ios /= 0) then
+ eof_period = .true.; exit
+ end if
+ body_left = body_left - take_bytes
+ end do
+ cycle
+ end if
+ discarded_samples = max(0_int64, frame_len_wide / 2_int64 &
+ - int(npts - k, int64))
+ if (discarded_samples .gt. 0_int64) then
+ call streaming_emit_warning_samples('period_boundary_discard', &
+ discarded_samples)
+ end if
+ body_left = frame_len
+ do while (body_left .gt. 0)
+ if (k .lt. npts) then
+ take_bytes = min(body_left, 2 * size(chunk))
+ take_samples = take_bytes / 2
+ call stdin_read(chunk, 2*take_samples, ios)
+ if (ios /= 0) then
+ eof_period = .true.; exit
+ end if
+ if (k + take_samples .gt. npts) take_samples = npts - k
+ shared_data%id2(k+1 : k+take_samples) = &
+ chunk(1:take_samples)
+ k = k + take_samples
+ body_left = body_left - take_bytes
+ ! Incremental symspec for JT9-family at kstep boundaries.
+ ! Cap at nhsym=181 to match the WAV-path exit condition
+ ! (jt9.f90:442-443) — exceeding it overruns ss(184,*).
+ do while ((k - 2048) / kstep .gt. nhsym0 .and. nhsym0 .lt. 181)
+ nhsym0 = nhsym0 + 1
+ if (nhsym0 .lt. 1) cycle
+ nhsym = nhsym0
+ if (mode .eq. 9 .or. mode .eq. 74) then
+ call timer('symspec ', 0)
+ call symspec(shared_data, nhsym*kstep + 2048, nsps, &
+ ingain, bLowSidelobes, nminw, pxdb, s, df3, &
+ ihsym, npts8, pxdbmax, npct_unused)
+ call timer('symspec ', 1)
+ end if
+ end do
+ else
+ ! Period full: drain the rest of this audio frame.
+ take_bytes = min(body_left, size(byte_sink))
+ call stdin_read(byte_sink, take_bytes, ios)
+ if (ios /= 0) then
+ eof_period = .true.; exit
+ end if
+ body_left = body_left - take_bytes
+ end if
+ end do
+
+ else if (iand(int(type_byte(1)), 255) .eq. FRAME_CONTROL) then
+ ! Read JSON body into char buffer (cap at CTL_BUF_LEN)
+ if (frame_len .gt. CTL_BUF_LEN) then
+ call streaming_emit_error_code('control_frame_too_large', &
+ 'control frame exceeds the configured buffer capacity')
+ ! drain + skip
+ body_left = frame_len
+ do while (body_left .gt. 0)
+ take_bytes = min(body_left, size(byte_sink))
+ call stdin_read(byte_sink, take_bytes, ios)
+ if (ios /= 0) exit
+ body_left = body_left - take_bytes
+ end do
+ cycle
+ end if
+ call stdin_read(ctl_bytes, frame_len, ios)
+ if (ios /= 0) then
+ eof_period = .true.; exit
+ end if
+ ctl_buf = ' '
+ do i_ctl = 1, frame_len
+ ctl_buf(i_ctl:i_ctl) = achar(iand(int(ctl_bytes(i_ctl)), 255))
+ end do
+ call parse_control_frame(ctl_buf(1:frame_len), action, cfg, terr)
+ select case (action)
+ case (CTRL_HALT)
+ halt_req = .true.
+ case (CTRL_CONFIGURE)
+ if (cfg%version_set .and. cfg%version .ne. 1) then
+ ! RFC v1 §3/§4.1: unknown schema version -> decline this frame.
+ ! Checked BEFORE per-key types: an unrecognized version means
+ ! we cannot trust the body's schema. (A wrong-TYPED version
+ ! leaves version_set=.false., so it falls through to the
+ ! type-error gate below — reported as configure_type_error
+ ! key:"version" only if version is the sole mistyped key;
+ ! otherwise the FIRST mistyped key wins, since parse records
+ ! one error and checks version last. Either way: declined.)
+ call streaming_emit_error_version(cfg%version)
+ cycle
+ end if
+ if (terr%present) then
+ ! RFC v1 §4.1: a key's JSON value type mismatched the schema.
+ ! Decline the ENTIRE frame — no field is applied (the apply
+ ! below is gated on reaching it; cycle skips it AND the npts/
+ ! buffer-discard logic, so a co-present valid key never takes
+ ! effect).
+ call streaming_emit_error_type(trim(terr%key), &
+ trim(terr%expected), trim(terr%got))
+ cycle
+ end if
+ if (cfg%mode_invalid) then
+ call streaming_emit_error_code('unknown_mode', &
+ 'configure frame contains an unsupported mode')
+ cycle
+ end if
+ if (cfg%trperiod_set .and. &
+ (.not. ieee_is_finite(cfg%trperiod) .or. &
+ cfg%trperiod .le. 0.d0 .or. &
+ cfg%trperiod .gt. dble(NTMAX))) then
+ call streaming_emit_error_code('invalid_trperiod', &
+ 'trperiod must be finite and between 0 and 1800 seconds')
+ cycle
+ end if
+ prev_mode = mode
+ call apply_configure_fields(cfg, mode, TRperiod, &
+ shared_data%params, baseline_nfa, baseline_nfb)
+ ! Mode changed: in-flight samples are wrong format. Discard
+ ! and recompute npts. Producer should configure FIRST so
+ ! this branch is rare/diagnostic.
+ if (cfg%mode_set .and. mode .ne. prev_mode) then
+ npts = int(TRperiod * NFSAMPLE)
+ if (mode .eq. 5) npts = 21 * 3456
+ if (npts .gt. size(shared_data%id2)) npts = size(shared_data%id2)
+ if (npts .lt. 1) npts = NFSAMPLE
+ if (mode .eq. 8 .and. npts .gt. 50 * 3456) npts = 50 * 3456
+ shared_data%id2 = 0
+ k = 0
+ nhsym = 0
+ nhsym0 = 0
+ else if (cfg%trperiod_set) then
+ ! TRperiod-only change: recompute npts but keep accumulated samples.
+ npts = int(TRperiod * NFSAMPLE)
+ if (mode .eq. 5) npts = 21 * 3456
+ if (mode .eq. 8 .and. npts .gt. 50 * 3456) npts = 50 * 3456
+ if (npts .gt. size(shared_data%id2)) npts = size(shared_data%id2)
+ end if
+ case (CTRL_PARSE_ERR)
+ call streaming_emit_error_code('configure_parse_error', &
+ 'malformed control frame (missing or invalid t field)')
+ end select
+
+ else
+ ! Unknown frame type: drain body
+ body_left = frame_len
+ do while (body_left .gt. 0)
+ take_bytes = min(body_left, size(byte_sink))
+ call stdin_read(byte_sink, take_bytes, ios)
+ if (ios /= 0) then
+ eof_period = .true.; exit
+ end if
+ body_left = body_left - take_bytes
+ end do
+ end if
+ end do
+
+ ! Run decoder if we accumulated any samples this period.
+ if (k .gt. 0) then
+ shared_data%params%newdat = .true.
+ shared_data%params%nzhsym = nhsym
+ ! FT8 override: decoder is tuned for nzhsym=50 (cf. jt9.f90:552).
+ if (mode .eq. 8) shared_data%params%nzhsym = 50
+ ! Non-FT8/FST4/Q65: cap at 181 to match WAV-path exit (ss array bound).
+ if (mode .ne. 8 .and. mode .ne. 240 .and. mode .ne. 241 .and. &
+ mode .ne. 242 .and. mode .ne. 66 .and. shared_data%params%nzhsym .gt. 181) then
+ shared_data%params%nzhsym = 181
+ end if
+ shared_data%params%kin = 64800
+ if (mode .eq. 240) shared_data%params%kin = 720000
+ if (mode .eq. 241) shared_data%params%kin = 720000
+ if (mode .eq. 242) shared_data%params%kin = 720000
+
+ if (mode .eq. 144) then
+ call decode_msk144(shared_data%id2, shared_data%params, data_dir)
+ else if (mode .eq. 8 .and. .not. shared_data%params%lmultift8) then
+ ! FT8 progressive 41/47/50 sequence (mirrors jt9.f90:562-581).
+ ! Without the early calls, ft8_decode.f90's saved `dd` array stays
+ ! unset and the final nzhsym=50 call decodes silence. With the
+ ! sequence, dd is populated on the nzhsym=41/47 passes and the
+ ! nzhsym=50 final pass produces real decodes.
+ shared_data%params%nzhsym = 41
+ id2a(1:41*3456) = shared_data%id2(1:41*3456)
+ id2a(41*3456+1:) = 0
+ call multimode_decoder(shared_data%ss, id2a, shared_data%params, NFSAMPLE)
+
+ shared_data%params%nzhsym = 47
+ id2a(1:47*3456) = shared_data%id2(1:47*3456)
+ id2a(47*3456+1:) = 0
+ call multimode_decoder(shared_data%ss, id2a, shared_data%params, NFSAMPLE)
+
+ shared_data%params%nzhsym = 50
+ id2a(1:50*3456) = shared_data%id2(1:50*3456)
+ id2a(50*3456+1:) = 0
+ call multimode_decoder(shared_data%ss, id2a, shared_data%params, NFSAMPLE)
+ else
+ call multimode_decoder(shared_data%ss, shared_data%id2, &
+ shared_data%params, NFSAMPLE)
+ end if
+ end if
+
+ if (halt_req .or. eof_period) return
+ end do
+
+contains
+
+ ! Read exactly nbytes from stdin via the C helper; ios=0 on success,
+ ! ios=1 on end-of-stream (short delivery — the producer closed the
+ ! pipe). Every caller treats nonzero ios as end-of-stream, matching
+ ! the old unformatted-stream-read iostat contract.
+ subroutine stdin_read(buf, nbytes, ios)
+ type(*), dimension(*), intent(inout) :: buf
+ integer, intent(in) :: nbytes
+ integer, intent(out) :: ios
+ ios = 0
+ if (stream_stdin_read_fully(buf, int(nbytes, c_int64_t)) /= &
+ int(nbytes, c_int64_t)) ios = 1
+ end subroutine stdin_read
+
+end subroutine jt9_stream
diff --git a/lib/subtract65.f90 b/lib/subtract65.f90
index cf6e00e3..7469472c 100644
--- a/lib/subtract65.f90
+++ b/lib/subtract65.f90
@@ -62,7 +62,7 @@ subroutine subtract65(dd,npts,f0,dt)
cref(ind)=cexp(cmplx(0.0,phi))
phi=modulo(phi+dphi,2*pi)
id=nstart-1+ind
- if(id.ge.1) camp(ind)=dd(id)*conjg(cref(ind))
+ if(id.ge.1 .and. id.le.npts) camp(ind)=dd(id)*conjg(cref(ind))
ind=ind+1
enddo
enddo
diff --git a/lib/sumsim.f90 b/lib/sumsim.f90
index 594b8b20..7236b47c 100644
--- a/lib/sumsim.f90
+++ b/lib/sumsim.f90
@@ -35,7 +35,7 @@ program sumsim
fac=1.0/nargs
iwave(1:npts)=nint(fac*wave(1:npts))
- open(12,file='000001_0000.wav',access='stream',status='unknown')
+ open(12,file='000001_0000.wav',access='stream',status='replace')
write(12) h,iwave(1:npts)
close(12)
diff --git a/lib/superfox/qpc/nhash2.c b/lib/superfox/qpc/nhash2.c
index 78817c7d..5453947b 100644
--- a/lib/superfox/qpc/nhash2.c
+++ b/lib/superfox/qpc/nhash2.c
@@ -1,383 +1,9 @@
-/*
-
- File name: nhash2.c
-
- *------------------------------------------------------------------------------
- *
- * This file is part of the WSPR application, Weak Signal Propogation Reporter
- *
- * File Name: nhash.c
- * Description: Functions to produce 32-bit hashes for hash table lookup
- *
- * Copyright (C) 2008-2014 Joseph Taylor, K1JT
- * License: GNU GPL v3+
- *
- * 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 3 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., 51 Franklin
- * Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Files: lookup3.c
- * Copyright: Copyright (C) 2006 Bob Jenkins <bob_jenkins@burtleburtle.net>
- * License: public-domain
- * You may use this code any way you wish, private, educational, or commercial.
- * It's free.
- *
- *-------------------------------------------------------------------------------
-*/
-
-/*
-These are functions for producing 32-bit hashes for hash table lookup.
-hashword(), hashlittle(), hashlittle2(), hashbig(), mix(), and final()
-are externally useful functions. Routines to test the hash are included
-if SELF_TEST is defined. You can use this free for any purpose. It's in
-the public domain. It has no warranty.
-
-You probably want to use hashlittle(). hashlittle() and hashbig()
-hash byte arrays. hashlittle() is is faster than hashbig() on
-little-endian machines. Intel and AMD are little-endian machines.
-On second thought, you probably want hashlittle2(), which is identical to
-hashlittle() except it returns two 32-bit hashes for the price of one.
-You could implement hashbig2() if you wanted but I haven't bothered here.
-
-If you want to find a hash of, say, exactly 7 integers, do
- a = i1; b = i2; c = i3;
- mix(a,b,c);
- a += i4; b += i5; c += i6;
- mix(a,b,c);
- a += i7;
- final(a,b,c);
-then use c as the hash value. If you have a variable length array of
-4-byte integers to hash, use hashword(). If you have a byte array (like
-a character string), use hashlittle(). If you have several byte arrays, or
-a mix of things, see the comments above hashlittle().
-
-Why is this so big? I read 12 bytes at a time into 3 4-byte integers,
-then mix those integers. This is fast (you can do a lot more thorough
-mixing with 12*3 instructions on 3 integers than you can with 3 instructions
-on 1 byte), but shoehorning those bytes into integers efficiently is messy.
-*/
-
-#define SELF_TEST 1
-
-#include <stdio.h> /* defines printf for tests */
-#include <time.h> /* defines time_t for timings in the test */
#include "nhash2.h"
-//#include <sys/param.h> /* attempt to define endianness */
-//#ifdef linux
-//# include <endian.h> /* attempt to define endianness */
-//#endif
-
-#define HASH_LITTLE_ENDIAN 1
-
-#define hashsize(n) ((uint32_t)1<<(n))
-#define hashmask(n) (hashsize(n)-1)
-#define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
-
-/*
--------------------------------------------------------------------------------
-mix -- mix 3 32-bit values reversibly.
-
-This is reversible, so any information in (a,b,c) before mix() is
-still in (a,b,c) after mix().
-
-If four pairs of (a,b,c) inputs are run through mix(), or through
-mix() in reverse, there are at least 32 bits of the output that
-are sometimes the same for one pair and different for another pair.
-This was tested for:
-* pairs that differed by one bit, by two bits, in any combination
- of top bits of (a,b,c), or in any combination of bottom bits of
- (a,b,c).
-* "differ" is defined as +, -, ^, or ~^. For + and -, I transformed
- the output delta to a Gray code (a^(a>>1)) so a string of 1's (as
- is commonly produced by subtraction) look like a single 1-bit
- difference.
-* the base values were pseudorandom, all zero but one bit set, or
- all zero plus a counter that starts at zero.
-
-Some k values for my "a-=c; a^=rot(c,k); c+=b;" arrangement that
-satisfy this are
- 4 6 8 16 19 4
- 9 15 3 18 27 15
- 14 9 3 7 17 3
-Well, "9 15 3 18 27 15" didn't quite get 32 bits diffing
-for "differ" defined as + with a one-bit base and a two-bit delta. I
-used http://burtleburtle.net/bob/hash/avalanche.html to choose
-the operations, constants, and arrangements of the variables.
-
-This does not achieve avalanche. There are input bits of (a,b,c)
-that fail to affect some output bits of (a,b,c), especially of a. The
-most thoroughly mixed value is c, but it doesn't really even achieve
-avalanche in c.
-
-This allows some parallelism. Read-after-writes are good at doubling
-the number of bits affected, so the goal of mixing pulls in the opposite
-direction as the goal of parallelism. I did what I could. Rotates
-seem to cost as much as shifts on every machine I could lay my hands
-on, and rotates are much kinder to the top and bottom bits, so I used
-rotates.
--------------------------------------------------------------------------------
-*/
-#define mix(a,b,c) \
-{ \
- a -= c; a ^= rot(c, 4); c += b; \
- b -= a; b ^= rot(a, 6); a += c; \
- c -= b; c ^= rot(b, 8); b += a; \
- a -= c; a ^= rot(c,16); c += b; \
- b -= a; b ^= rot(a,19); a += c; \
- c -= b; c ^= rot(b, 4); b += a; \
-}
-
-/*
--------------------------------------------------------------------------------
-final -- final mixing of 3 32-bit values (a,b,c) into c
-
-Pairs of (a,b,c) values differing in only a few bits will usually
-produce values of c that look totally different. This was tested for
-* pairs that differed by one bit, by two bits, in any combination
- of top bits of (a,b,c), or in any combination of bottom bits of
- (a,b,c).
-* "differ" is defined as +, -, ^, or ~^. For + and -, I transformed
- the output delta to a Gray code (a^(a>>1)) so a string of 1's (as
- is commonly produced by subtraction) look like a single 1-bit
- difference.
-* the base values were pseudorandom, all zero but one bit set, or
- all zero plus a counter that starts at zero.
-
-These constants passed:
- 14 11 25 16 4 14 24
- 12 14 25 16 4 14 24
-and these came close:
- 4 8 15 26 3 22 24
- 10 8 15 26 3 22 24
- 11 8 15 26 3 22 24
--------------------------------------------------------------------------------
-*/
-#define final(a,b,c) \
-{ \
- c ^= b; c -= rot(b,14); \
- a ^= c; a -= rot(c,11); \
- b ^= a; b -= rot(a,25); \
- c ^= b; c -= rot(b,16); \
- a ^= c; a -= rot(c,4); \
- b ^= a; b -= rot(a,14); \
- c ^= b; c -= rot(b,24); \
-}
-/*
--------------------------------------------------------------------------------
-hashlittle() -- hash a variable-length key into a 32-bit value
- k : the key (the unaligned variable-length array of bytes)
- length : the length of the key, counting by bytes
- initval : can be any 4-byte value
-Returns a 32-bit value. Every bit of the key affects every bit of
-the return value. Two keys differing by one or two bits will have
-totally different hash values.
+#include "../../lookup3.h"
-The best hash table sizes are powers of 2. There is no need to do
-mod a prime (mod is sooo slow!). If you need less than 32 bits,
-use a bitmask. For example, if you need only 10 bits, do
- h = (h & hashmask(10));
-In which case, the hash table should have hashsize(10) elements.
-
-If you are hashing n strings (uint8_t **)k, do it like this:
- for (i=0, h=0; i<n; ++i) h = hashlittle( k[i], len[i], h);
-
-By Bob Jenkins, 2006. bob_jenkins@burtleburtle.net. You may use this
-code any way you wish, private, educational, or commercial. It's free.
-
-Use for hash table lookup, or anything where one collision in 2^^32 is
-acceptable. Do NOT use for cryptographic purposes.
--------------------------------------------------------------------------------
-*/
-
-uint32_t nhash2( const void *key, uint64_t length, uint32_t initval)
-//int nhash( const char *key, int length, int initval)
+uint32_t nhash2(const void *key, uint64_t length, uint32_t initval)
{
- uint32_t a,b,c; /* internal state */
- union { const void *ptr; size_t i; } u; /* needed for Mac Powerbook G4 */
-
- /* Set up the internal state */
- a = b = c = 0xdeadbeef + ((uint32_t)length) + initval;
-
- u.ptr = key;
- if (HASH_LITTLE_ENDIAN && ((u.i & 0x3) == 0)) {
- const uint32_t *k = (const uint32_t *)key; /* read 32-bit chunks */
-
- /*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */
- while (length > 12)
- {
- a += k[0];
- b += k[1];
- c += k[2];
- mix(a,b,c);
- length -= 12;
- k += 3;
- }
-
- // printf("AAA %x %d %x %d\n",c,c,c&32767,c&32767);
-
- /*----------------------------- handle the last (probably partial) block */
- /*
- * "k[2]&0xffffff" actually reads beyond the end of the string, but
- * then masks off the part it's not allowed to read. Because the
- * string is aligned, the masked-off tail is in the same word as the
- * rest of the string. Every machine with memory protection I've seen
- * does it on word boundaries, so is OK with this. But VALGRIND will
- * still catch it and complain. The masking trick does make the hash
- * noticably faster for short strings (like English words).
- */
-#ifndef VALGRIND
-
- switch(length)
- {
- case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
- case 11: c+=k[2]&0xffffff; b+=k[1]; a+=k[0]; break;
- case 10: c+=k[2]&0xffff; b+=k[1]; a+=k[0]; break;
- case 9 : c+=k[2]&0xff; b+=k[1]; a+=k[0]; break;
- case 8 : b+=k[1]; a+=k[0]; break;
- case 7 : b+=k[1]&0xffffff; a+=k[0]; break;
- case 6 : b+=k[1]&0xffff; a+=k[0]; break;
- case 5 : b+=k[1]&0xff; a+=k[0]; break;
- case 4 : a+=k[0]; break;
- case 3 : a+=k[0]&0xffffff; break;
- case 2 : a+=k[0]&0xffff; break;
- case 1 : a+=k[0]&0xff; break;
- case 0 : return c; /* zero length strings require no mixing */
- }
-
-#else /* make valgrind happy */
-
- k8 = (const uint8_t *)k;
- switch(length)
- {
- case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
- case 11: c+=((uint32_t)k8[10])<<16; /* fall through */
- case 10: c+=((uint32_t)k8[9])<<8; /* fall through */
- case 9 : c+=k8[8]; /* fall through */
- case 8 : b+=k[1]; a+=k[0]; break;
- case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */
- case 6 : b+=((uint32_t)k8[5])<<8; /* fall through */
- case 5 : b+=k8[4]; /* fall through */
- case 4 : a+=k[0]; break;
- case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */
- case 2 : a+=((uint32_t)k8[1])<<8; /* fall through */
- case 1 : a+=k8[0]; break;
- case 0 : return c;
- }
-
-#endif /* !valgrind */
-
- } else if (HASH_LITTLE_ENDIAN && ((u.i & 0x1) == 0)) {
- const uint16_t *k = (const uint16_t *)key; /* read 16-bit chunks */
- const uint8_t *k8;
-
- /*--------------- all but last block: aligned reads and different mixing */
- while (length > 12)
- {
- a += k[0] + (((uint32_t)k[1])<<16);
- b += k[2] + (((uint32_t)k[3])<<16);
- c += k[4] + (((uint32_t)k[5])<<16);
- mix(a,b,c);
- length -= 12;
- k += 6;
- }
-
- /*----------------------------- handle the last (probably partial) block */
- k8 = (const uint8_t *)k;
- switch(length)
- {
- case 12: c+=k[4]+(((uint32_t)k[5])<<16);
- b+=k[2]+(((uint32_t)k[3])<<16);
- a+=k[0]+(((uint32_t)k[1])<<16);
- break;
- case 11: c+=((uint32_t)k8[10])<<16; /* fall through */
- case 10: c+=k[4];
- b+=k[2]+(((uint32_t)k[3])<<16);
- a+=k[0]+(((uint32_t)k[1])<<16);
- break;
- case 9 : c+=k8[8]; /* fall through */
- case 8 : b+=k[2]+(((uint32_t)k[3])<<16);
- a+=k[0]+(((uint32_t)k[1])<<16);
- break;
- case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */
- case 6 : b+=k[2];
- a+=k[0]+(((uint32_t)k[1])<<16);
- break;
- case 5 : b+=k8[4]; /* fall through */
- case 4 : a+=k[0]+(((uint32_t)k[1])<<16);
- break;
- case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */
- case 2 : a+=k[0];
- break;
- case 1 : a+=k8[0];
- break;
- case 0 : return c; /* zero length requires no mixing */
- }
-
- } else { /* need to read the key one byte at a time */
- const uint8_t *k = (const uint8_t *)key;
-
- /*--------------- all but the last block: affect some 32 bits of (a,b,c) */
- while (length > 12)
- {
- a += k[0];
- a += ((uint32_t)k[1])<<8;
- a += ((uint32_t)k[2])<<16;
- a += ((uint32_t)k[3])<<24;
- b += k[4];
- b += ((uint32_t)k[5])<<8;
- b += ((uint32_t)k[6])<<16;
- b += ((uint32_t)k[7])<<24;
- c += k[8];
- c += ((uint32_t)k[9])<<8;
- c += ((uint32_t)k[10])<<16;
- c += ((uint32_t)k[11])<<24;
- mix(a,b,c);
- length -= 12;
- k += 12;
- }
-
- /*-------------------------------- last block: affect all 32 bits of (c) */
- switch(length) /* all the case statements fall through */
- {
- case 12: c+=((uint32_t)k[11])<<24;
- /* fall through */
- case 11: c+=((uint32_t)k[10])<<16;
- /* fall through */
- case 10: c+=((uint32_t)k[9])<<8;
- /* fall through */
- case 9 : c+=k[8];
- /* fall through */
- case 8 : b+=((uint32_t)k[7])<<24;
- /* fall through */
- case 7 : b+=((uint32_t)k[6])<<16;
- /* fall through */
- case 6 : b+=((uint32_t)k[5])<<8;
- /* fall through */
- case 5 : b+=k[4];
- /* fall through */
- case 4 : a+=((uint32_t)k[3])<<24;
- /* fall through */
- case 3 : a+=((uint32_t)k[2])<<16;
- /* fall through */
- case 2 : a+=((uint32_t)k[1])<<8;
- /* fall through */
- case 1 : a+=k[0];
- break;
- case 0 : return c;
- }
- }
-
- final(a,b,c);
- return c;
+ /* SuperFox applies its 21-bit CRC mask after hashing. */
+ return wsjt_hashlittle(key, (size_t)length, initval);
}
diff --git a/lib/superfox/qpc/nhash2.h b/lib/superfox/qpc/nhash2.h
index 1864a93f..4cdcd4a1 100644
--- a/lib/superfox/qpc/nhash2.h
+++ b/lib/superfox/qpc/nhash2.h
@@ -1,5 +1,5 @@
-#ifndef NHASH_H_
-#define NHASH_H_
+#ifndef SUPERFOX_NHASH2_H_
+#define SUPERFOX_NHASH2_H_
#ifdef Win32
#include "win_stdint.h" /* defines uint32_t etc */
@@ -12,8 +12,7 @@
extern "C" {
#endif
-uint32_t nhash( const void * key, uint64_t length, uint32_t initval);
- //int nhash(const char *key, int length, int initval);
+uint32_t nhash2(const void *key, uint64_t length, uint32_t initval);
#ifdef __cplusplus
}
diff --git a/lib/superfox/qpc/np_rnd.c b/lib/superfox/qpc/np_rnd.c
index df2afacc..ca6f675b 100644
--- a/lib/superfox/qpc/np_rnd.c
+++ b/lib/superfox/qpc/np_rnd.c
@@ -27,7 +27,7 @@
#elif _SVID_SOURCE || _XOPEN_SOURCE || __unix__ || (defined (__APPLE__) && defined(__MACH__)) /* POSIX or Unix or Apple */
#include <stdlib.h>
#define rand_s(x) (*x)=(unsigned int)lrand48() // returns unsigned integers in the range 0..0x7FFFFFFF
- #define K_RAND_MAX 0x7FFFFFFF // that's the max number
+ #define K_RAND_MAX 2147483647.0f // that's the max number
// generated by lrand48
#else
#error "No good quality PRNG found"
diff --git a/lib/superfox/qpc_decode2.f90 b/lib/superfox/qpc_decode2.f90
index 57152ab8..fb1dde88 100644
--- a/lib/superfox/qpc_decode2.f90
+++ b/lib/superfox/qpc_decode2.f90
@@ -5,11 +5,11 @@ subroutine qpc_decode2(c0,fsync,ftol,xdec,ndepth,dth,damp,crc_ok, &
parameter(NMAX=15*12000,NFT=365,NZ=100)
complex c0(NMAX) !Signal as received
- complex c(NMAX) !Signal as received
+ complex, allocatable :: c(:) !Signal as received
real py(0:127,0:127) !Probabilities for received synbol values
real py0(0:127,0:127) !Probabilities for strong signal
real pyd(0:127,0:127) !Dithered values for py
- real s2(0:127,0:151) !Symbol spectra, including sync
+ real, allocatable :: s2(:,:) !Symbol spectra, including sync
real s3(0:127,0:127) !Synchronized symbol spectra
real No
integer crc_chk,crc_sent
@@ -49,6 +49,8 @@ subroutine qpc_decode2(c0,fsync,ftol,xdec,ndepth,dth,damp,crc_ok, &
-5, 4, -4, 3, -5, 4, -4, -5, 4, -5/
+ allocate(c(NMAX),s2(0:127,0:151))
+ s2=0.0
fsample=12000.0
baud=12000.0/1024.0
nstype=1
diff --git a/lib/superfox/qpc_sync.f90 b/lib/superfox/qpc_sync.f90
index ea9afb5b..9c80b390 100644
--- a/lib/superfox/qpc_sync.f90
+++ b/lib/superfox/qpc_sync.f90
@@ -46,6 +46,12 @@ subroutine qpc_sync(crcvd0,fsample,isync,fsync,ftol,f2,t2,snrsync)
s0=s0+s(i)
s1=s1+(i-i0)*s(i)
enddo
+ if(.not. (s0 .gt. 0.0)) then
+ f2=fsync-750.0
+ t2=0.0
+ snrsync=0.0
+ return
+ endif
delta=s1/s0
i0=nint(i0+delta)
f2=i0*df2-750.0
@@ -105,9 +111,22 @@ subroutine qpc_sync(crcvd0,fsample,isync,fsync,ftol,f2,t2,snrsync)
sp=sp + p(lag)
sq=sq + p(lag)*p(lag)
enddo
+ if(nsum .le. 0) then
+ snrsync=0.0
+ return
+ endif
ave=sp/nsum
- rms=sqrt(sq/nsum-ave*ave)
- snrsync=(pmax-ave)/rms
+ var=sq/nsum-ave*ave
+ if(.not. (var .gt. 0.0)) then
+ snrsync=0.0
+ return
+ endif
+ rms=sqrt(var)
+ if(rms .gt. 0.0) then
+ snrsync=(pmax-ave)/rms
+ else
+ snrsync=0.0
+ endif
return
end subroutine qpc_sync
diff --git a/lib/superfox/ran1.f90 b/lib/superfox/ran1.f90
index b09b9bab..8ea83bdf 100644
--- a/lib/superfox/ran1.f90
+++ b/lib/superfox/ran1.f90
@@ -1,18 +1,24 @@
FUNCTION ran1(idum)
- INTEGER idum,IA,IM,IQ,IR,NTAB,NDIV
- REAL ran1,AM,EPS,RNMX
- PARAMETER (IA=16807,IM=2147483647,AM=1./IM,IQ=127773,IR=2836, &
- NTAB=32,NDIV=1+(IM-1)/NTAB,EPS=1.2e-7,RNMX=1.-EPS)
+ INTEGER idum
+ INTEGER, PARAMETER :: IA=16807,IM=2147483647,IQ=127773,IR=2836,NTAB=32
+ INTEGER, PARAMETER :: NDIV=1+INT(DBLE(IM-1)/DBLE(NTAB))
+ REAL ran1
+ REAL, PARAMETER :: AM=1.0/REAL(IM),EPS=1.2e-7,RNMX=1.-EPS
INTEGER j,k,iv(NTAB),iy
SAVE iv,iy
DATA iv /NTAB*0/, iy /0/
if (idum.le.0.or.iy.eq.0) then
idum=max(-idum,1)
- do j=NTAB+8,1,-1
+ do j=NTAB+8,NTAB+1,-1
k=idum/IQ
idum=IA*(idum-k*IQ)-IR*k
if (idum.lt.0) idum=idum+IM
- if (j.le.NTAB) iv(j)=idum
+ enddo
+ do j=NTAB,1,-1
+ k=idum/IQ
+ idum=IA*(idum-k*IQ)-IR*k
+ if (idum.lt.0) idum=idum+IM
+ iv(j)=idum
enddo
iy=iv(1)
endif
diff --git a/lib/superfox/sfox_pack.f90 b/lib/superfox/sfox_pack.f90
index c5a6d94c..1a482422 100644
--- a/lib/superfox/sfox_pack.f90
+++ b/lib/superfox/sfox_pack.f90
@@ -1,79 +1,132 @@
-subroutine sfox_pack(line,ckey,bMoreCQs,bSendMsg,freeTextMsg,xin)
+subroutine sfox_pack(line,ckey,bMoreCQs,bSendMsg,freeTextMsg,xin,pack_error)
use qpc_mod
use packjt
use packjt77
- use julian
parameter (NQU1RKS=203514677)
- integer*8 n47,n58,now
+ integer*8 n47,n58
integer*1 xin(0:49) !Packed message as 7-bit symbols
logical*1 bMoreCQs,bSendMsg
- logical text,allz
+ integer pack_error
+ integer, parameter :: SFOX_PACK_OK=0
+ integer, parameter :: SFOX_PACK_BAD_TOKEN=1
+ integer, parameter :: SFOX_PACK_BAD_OTP=2
+ integer, parameter :: SFOX_PACK_BAD_CQ=3
+ integer, parameter :: SFOX_PACK_BAD_CALL=4
+ integer, parameter :: SFOX_PACK_BAD_REPORT=5
+ integer, parameter :: SFOX_PACK_BAD_FREE_TEXT=6
+ logical text,allz,split_success
character*120 line !SuperFox message pieces
character*10 ckey
character*26 freeTextMsg
character*13 w(16)
+ character*13 w1,w2,w3 !Scalar copies of w() elements passed to
+ !explicit-interface functions/subroutines
+ !below: gfortran's -Wcharacter-truncation
+ !treats an array-element actual argument
+ !as spanning the rest of w()'s storage
+ !sequence, so pass a same-length scalar
+ !instead to give it an exact length
character*11 c11
character*329 msgbits !Packed message as bits
character*38 c
data c/' 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ/'/
- i0=index(line,'/')
+ pack_error=SFOX_PACK_BAD_TOKEN
+ xin=0
i3=0 !Default to i3=0, standard message
nh1=0 !Number of Hound calls with RR73
nh2=0 !Number of Hound calls with report
! Split the command line into words
- w=' '
- i1=1
- do j=1,16
- do i=i1,min(i1+12,120)
- if(line(i:i).eq.' ') exit
- enddo
- i2=i-1
- w(j)=line(i1:i2)
- do i=i2+1,120
- if(line(i:i).ne.' ') exit
- enddo
- i1=i
- if(i1.ge.120) exit
- enddo
- nwords=j
-
- do i=1,nwords
- if(w(i)(1:1).eq.' ') then
- nwords=i-1
- exit
- endif
- enddo
+ call split_sfox_line(line,w,nwords,split_success)
+ if(.not.split_success .or. nwords.lt.1) then
+ pack_error=SFOX_PACK_BAD_TOKEN
+ return
+ endif
do i=1,329 !Set all msgbits to '0'
msgbits(i:i)='0'
enddo
- now=itime8()/30
- now=30*now
- read(ckey(5:10),*) notp
+ read(ckey(5:10),*,err=910) notp
write(msgbits(307:326),'(b20.20)') notp !Insert the digital signature
if(w(1)(1:3).eq.'CQ ') then
+ if(nwords.ne.3) then
+ pack_error=SFOX_PACK_BAD_CQ
+ return
+ endif
+ w2=w(2)
+ w3=w(3)
+ if(.not.valid_sfox_cq_call(w2) .or. .not.valid_sfox_grid4(w3)) then
+ pack_error=SFOX_PACK_BAD_CQ
+ return
+ endif
i3=3
- c11=w(2)(1:11)
+ c11=w2(1:11)
n58=0
do i=1,11
n58=n58*38 + index(c,c11(i:i)) - 1
enddo
write(msgbits(1:58),'(b58.58)') n58
- call packgrid(w(3)(1:4),n15,text)
+ call packgrid(w3(1:4),n15,text)
+ if(text) then
+ pack_error=SFOX_PACK_BAD_CQ
+ return
+ endif
write(msgbits(59:73),'(b15.15)') n15
write(msgbits(327:329),'(b3.3)') i3 !Message type i3=3
go to 800
endif
- call pack28(w(1),n28) !Fox call
+ w1=w(1)
+ if(.not.valid_sfox_call(w1)) then
+ pack_error=SFOX_PACK_BAD_CALL
+ return
+ endif
+ call pack28(w1,n28) !Fox call
write(msgbits(1:28),'(b28.28)') n28
+ nrr73_total=0
+ nreport_total=0
+ i=2
+ do while(i.le.nwords)
+ if(w(i)(1:1).eq.'+' .or. w(i)(1:1).eq.'-') then
+ pack_error=SFOX_PACK_BAD_TOKEN
+ return
+ endif
+ if(.not.valid_sfox_call(w(i))) then
+ pack_error=SFOX_PACK_BAD_CALL
+ return
+ endif
+ i1=i+1
+ if(i1.le.nwords .and. &
+ (w(i1)(1:1).eq.'+' .or. w(i1)(1:1).eq.'-')) then
+ if(.not.valid_sfox_report(w(i1),n)) then
+ pack_error=SFOX_PACK_BAD_REPORT
+ return
+ endif
+ nreport_total=nreport_total+1
+ i=i+2
+ else
+ nrr73_total=nrr73_total+1
+ i=i+1
+ endif
+ enddo
+
+ if(bSendMsg) then
+ if(nrr73_total+nreport_total.gt.4 .or. nreport_total.gt.4) then
+ pack_error=SFOX_PACK_BAD_TOKEN
+ return
+ endif
+ else if(nrr73_total.gt.5 .or. nreport_total.gt.4 .or. &
+ nrr73_total+nreport_total.gt.9) then
+ pack_error=SFOX_PACK_BAD_TOKEN
+ return
+ endif
+
! Default report is RR73 if we're also sending a free text message.
if(bSendMsg) msgbits(141:160)='11111111111111111111'
@@ -84,6 +137,10 @@ subroutine sfox_pack(line,ckey,bMoreCQs,bSendMsg,freeTextMsg,xin)
if(w(i)(1:1).eq.'+' .or. w(i)(1:1).eq.'-') cycle !Skip report words
i1=min(i+1,nwords)
if(w(i1)(1:1) .eq.'+' .or. w(i1)(1:1).eq.'-') cycle !Skip if i+1 is report
+ if(.not.valid_sfox_call(w(i))) then
+ pack_error=SFOX_PACK_BAD_CALL
+ return
+ endif
call pack28(w(i),n28)
write(msgbits(j:j+27),1002) n28 !Insert this call for RR73 message
1002 format(b28.28)
@@ -104,11 +161,16 @@ subroutine sfox_pack(line,ckey,bMoreCQs,bSendMsg,freeTextMsg,xin)
do i=2,nwords
i1=min(i+1,nwords)
if(w(i1)(1:1).eq.'+' .or. w(i1)(1:1).eq.'-') then
+ if(.not.valid_sfox_call(w(i))) then
+ pack_error=SFOX_PACK_BAD_CALL
+ return
+ endif
call pack28(w(i),n28)
write(msgbits(j:j+27),1002) n28 !Insert this call
- read(w(i1),*) n !Valid reports are -18 to +12, plus RR73
- if(n.lt.-18) n=-18 !... Even numbers only ...
- if(n.gt.12) n=12
+ if(.not.valid_sfox_report(w(i1),n)) then
+ pack_error=SFOX_PACK_BAD_REPORT
+ return
+ endif
write(msgbits(j2:j2+4),1000) n+18
1000 format(b5.5)
w(i1)=""
@@ -121,6 +183,10 @@ subroutine sfox_pack(line,ckey,bMoreCQs,bSendMsg,freeTextMsg,xin)
enddo
800 if(bSendMsg) then
+ if(.not.valid_sfox_free_text(freeTextMsg)) then
+ pack_error=SFOX_PACK_BAD_FREE_TEXT
+ return
+ endif
i1=26
do i=1,26
if(freeTextMsg(i:i).ne.' ') i1=i
@@ -174,5 +240,116 @@ subroutine sfox_pack(line,ckey,bMoreCQs,bSendMsg,freeTextMsg,xin)
xin=xin(49:0:-1) !Reverse the symbol order
! NB: CRC is now in first three symbols, fox call in the last four.
+ pack_error=SFOX_PACK_OK
+900 continue
return
+910 pack_error=SFOX_PACK_BAD_OTP
+ go to 900
+
+contains
+
+ subroutine split_sfox_line(text,words,nwords,success)
+ character*120 text
+ character*13 words(16)
+ integer nwords
+ logical success
+ integer first,last
+
+ words=' '
+ nwords=0
+ success=.true.
+ first=1
+ do while(first.le.120)
+ do while(first.le.120)
+ if(text(first:first).ne.' ') exit
+ first=first+1
+ enddo
+ if(first.gt.120) exit
+
+ last=first
+ do while(last.le.120)
+ if(text(last:last).eq.' ') exit
+ last=last+1
+ enddo
+ if(last-first.gt.13) then
+ success=.false.
+ return
+ endif
+ if(nwords.ge.16) then
+ success=.false.
+ return
+ endif
+ nwords=nwords+1
+ words(nwords)=text(first:last-1)
+ first=last+1
+ enddo
+ end subroutine split_sfox_line
+
+ logical function valid_sfox_call(call)
+ character*13 call
+ character*13 decoded
+ logical success
+ integer n28
+
+ valid_sfox_call=.false.
+ call pack28(call,n28)
+ call unpack28(n28,decoded,success)
+ if(.not.success) return
+ valid_sfox_call=trim(decoded).eq.trim(call)
+ return
+ end function valid_sfox_call
+
+ logical function valid_sfox_cq_call(callsign)
+ character*13 callsign
+ integer n
+
+ valid_sfox_cq_call=.false.
+ n=len(trim(callsign))
+ if(n.lt.3 .or. n.gt.11) return
+ do i=1,n
+ if(index(c(2:38),callsign(i:i)).eq.0) return
+ enddo
+
+ valid_sfox_cq_call=.true.
+ return
+ end function valid_sfox_cq_call
+
+ logical function valid_sfox_grid4(grid)
+ character*13 grid
+
+ valid_sfox_grid4=len(trim(grid)).eq.4 .and. &
+ grid(1:1).ge.'A' .and. grid(1:1).le.'R' .and. &
+ grid(2:2).ge.'A' .and. grid(2:2).le.'R' .and. &
+ grid(3:3).ge.'0' .and. grid(3:3).le.'9' .and. &
+ grid(4:4).ge.'0' .and. grid(4:4).le.'9'
+ return
+ end function valid_sfox_grid4
+
+ logical function valid_sfox_report(word,n)
+ character*13 word
+ integer n
+
+ valid_sfox_report=.false.
+ read(word,*,err=910,end=910) n
+ if(n.lt.-18 .or. n.gt.12) return
+ valid_sfox_report=.true.
+910 return
+ end function valid_sfox_report
+
+ logical function valid_sfox_free_text(text)
+ character*26 text
+ character*42 text_chars
+! Authoritative free-text charset; the GUI precheck in on_pbFreeText_clicked
+! (widgets/mainwindow_slots.cpp) must mirror this string.
+ data text_chars/' 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ+-./?'/
+
+ valid_sfox_free_text=.true.
+ do i=1,26
+ if(index(text_chars,text(i:i)).eq.0) then
+ valid_sfox_free_text=.false.
+ return
+ endif
+ enddo
+ return
+ end function valid_sfox_free_text
end subroutine sfox_pack
diff --git a/lib/superfox/sfox_remove_ft8.f90 b/lib/superfox/sfox_remove_ft8.f90
index fc990bca..75687659 100644
--- a/lib/superfox/sfox_remove_ft8.f90
+++ b/lib/superfox/sfox_remove_ft8.f90
@@ -133,8 +133,11 @@ subroutine sfox_remove_ft8(dd,npts)
nt=2**(3*nsym)
do ihalf=1,2
do k=1,29,nsym
- if(ihalf.eq.1) ks=k+7
- if(ihalf.eq.2) ks=k+43
+ if(ihalf.eq.1) then
+ ks=k+7
+ else
+ ks=k+43
+ endif
amax=-1.0
do i=0,nt-1
i3=iand(i,7)
diff --git a/lib/superfox/sfox_remove_tone.f90 b/lib/superfox/sfox_remove_tone.f90
index c8f9e033..35a6fbec 100644
--- a/lib/superfox/sfox_remove_tone.f90
+++ b/lib/superfox/sfox_remove_tone.f90
@@ -68,6 +68,7 @@ subroutine sfox_remove_tone(c0,fsync)
s0=s0+s(i)
s1=s1+(i-i0)*s(i)
enddo
+ if(.not. (s0 .gt. 0.0)) exit
delta=s1/s0
i0=nint(i0+delta)
f2=i0*df
diff --git a/lib/superfox/sfox_unpack.f90 b/lib/superfox/sfox_unpack.f90
index 56168963..fd940347 100644
--- a/lib/superfox/sfox_unpack.f90
+++ b/lib/superfox/sfox_unpack.f90
@@ -23,16 +23,16 @@ subroutine sfox_unpack(nutc,x,nsnr,f0,dt0,foxcall,notp)
endif
write(msgbits,1000) x(0:46)
1000 format(47b7.7)
- read(msgbits(327:329),'(b6)') i3 !Message type
+ read(msgbits(327:329),'(b3)') i3 !Message type
read(msgbits(1:28),'(b28)') n28 !Standard Fox call
call unpack28(n28,foxcall,success)
- if(i3.eq.1) then !Compound Fox callsign
-! read(msgbits(87:101),'(b15)') n15
-! call unpackgrid(n15,grid4)
-! msg(1)='CQ '//trim(foxcall)//' '//grid4
-! write(*,1100) nutc,nsnr,dt0,nint(f0),trim(msg(1))
-! go to 100
+ if(i3.eq.1) then
+! Type i3=1 is documented for a compound-Fox c58 layout, but the
+! current transmitter does not emit it and this decoder does not
+! implement the c58 field offsets. Do not render hound messages with
+! a mis-decoded c28 Fox call.
+ go to 900
else if(i3.eq.2) then !Up to 4 Hound calls and free text
call unpacktext77(msgbits(161:231),freeTextMsg(1:13))
call unpacktext77(msgbits(232:302),freeTextMsg(14:26))
@@ -54,8 +54,12 @@ subroutine sfox_unpack(nutc,x,nsnr,f0,dt0,foxcall,notp)
call unpackgrid(n15,grid4)
msg(1)='CQ '//trim(foxcall)//' '//grid4
write(*,1100) nutc,nsnr,dt0,nint(f0),trim(msg(1))
- read(msgbits(74:105),'(b32)') n32
- if(n32.eq.NQU1RKS) go to 100
+ allz=1
+ do i=0,6
+ read(msgbits(74+32*i:105+32*i),'(b32)') n32
+ if(n32.ne.NQU1RKS) allz=0
+ enddo
+ if(allz.eq.1) go to 100
call unpacktext77(msgbits(74:144),freeTextMsg(1:13))
call unpacktext77(msgbits(145:215),freeTextMsg(14:26))
do i=26,1,-1
@@ -112,8 +116,9 @@ subroutine sfox_unpack(nutc,x,nsnr,f0,dt0,foxcall,notp)
100 read(msgbits(307:326),'(b20)') notp
if (use_otp) then
- write(ssignature,'(I6.6)') notp
- write(*,1100) nutc,nsnr,dt0,nint(f0),'$VERIFY$ '//trim(foxcall)//' '//trim(ssignature)
- endif
- return
+ write(ssignature,'(I6.6)') notp
+ write(*,1100) nutc,nsnr,dt0,nint(f0),'$VERIFY$ '//trim(foxcall)// &
+ ' '//trim(ssignature)
+ endif
+900 return
end subroutine sfox_unpack
diff --git a/lib/superfox/sfoxsim.f90 b/lib/superfox/sfoxsim.f90
index 86f7019e..1b4bb9f2 100644
--- a/lib/superfox/sfoxsim.f90
+++ b/lib/superfox/sfoxsim.f90
@@ -11,6 +11,7 @@ program sfoxsim
type(hdr) h !Header for .wav file
logical*1 bMoreCQs !Include a CQ when space available?
logical*1 bSendMsg !Send a Free text message
+ integer pack_error
integer*2 iwave(NMAX) !Generated i*2 waveform
integer isync(24) !Indices of sync symbols
integer itone(151) !Symbol values, data and sync
@@ -112,7 +113,8 @@ program sfoxsim
! Generate a SuperFox message
nslots=5
call foxgen2(nslots,cmsg,line,foxcall) !Parse old-style Fox messages
- call sfox_pack(line,ckey,bMoreCQs,bSendMsg,text_msg,xin)
+ call sfox_pack(line,ckey,bMoreCQs,bSendMsg,text_msg,xin,pack_error)
+ if(pack_error.ne.0) error stop 'SuperFox pack failed'
call qpc_encode(y,xin)
y=cshift(y,1)
@@ -137,6 +139,7 @@ program sfoxsim
xdt=ran1(idum)-0.5
endif
! Generate cdat, the SuperFox waveform
+ cdat=0.
call sfox_gen_gfsk(chansym,f1,isync,itone,cdat)
crcvd=0.
@@ -156,7 +159,7 @@ program sfoxsim
nmin=(nsec-nhr*3600)/60
nsec=mod(nsec,60)
write(fname(8:13),'(3i2.2)') nhr,nmin,nsec
- open(10,file=trim(fname),access='stream',status='unknown')
+ open(10,file=trim(fname),access='stream',status='replace')
write(10) h,iwave(1:NMAX) !Save the .wav file
close(10)
enddo ! ifile
diff --git a/lib/superfox/sfrx_sub.f90 b/lib/superfox/sfrx_sub.f90
index 12a48e08..fed03461 100644
--- a/lib/superfox/sfrx_sub.f90
+++ b/lib/superfox/sfrx_sub.f90
@@ -7,8 +7,8 @@ subroutine sfrx_sub(nyymmdd,nutc,nfqso,ntol,iwave)
integer*8 secday,ntime8
integer*1 xdec(0:49)
character*13 foxcall
- complex c0(NMAX) !Complex form of signal as received
- real dd(NMAX)
+ complex, allocatable :: c0(:) !Complex form of signal as received
+ real, allocatable :: dd(:)
logical crc_ok
data secday/86400/
@@ -31,6 +31,7 @@ subroutine sfrx_sub(nyymmdd,nutc,nfqso,ntol,iwave)
ntime8=secday*(JD(iyr,imo,iday)-2440588) + 3600*ih + 60*im + is
endif
+ allocate(c0(NMAX),dd(NMAX))
dd=iwave
call sfox_remove_ft8(dd,npts)
diff --git a/lib/superfox/sftx.f90 b/lib/superfox/sftx.f90
index 78b5ca15..d629eb7d 100644
--- a/lib/superfox/sftx.f90
+++ b/lib/superfox/sftx.f90
@@ -17,22 +17,15 @@ program sftx
character*120 line !List of SuperFox message pieces
character*40 cmsg(5) !Old-style Fox messages
character*26 freeTextMsg
- character*2 arg
character*10 ckey
! character*9 foxkey
character*11 foxcall0,foxcall
logical*1 bMoreCQs,bSendMsg
- logical crc_ok
- real py(0:127,0:127) !Probabilities for received synbol values
- integer*8 n47
+ integer pack_error
integer itone(151) !SuperFox channel-symbol values
integer*1 xin(0:49) !Packed message as 7-bit symbols
- integer*1 xdec(0:49) !Decoded message
integer*1 y(0:127) !Encoded symbols as i*1 integers
- integer*1 ydec(0:127) !Decoded codeword
- integer*1 yy(0:10)
integer chansym0(127) !Transmitted symbols, data only
- integer chansym(127) !Received symbols, data only
integer isync(24) !Symbol numbers for sync tones
data isync/1,2,4,7,11,16,22,29,37,39,42,43,45,48,52,57,63,70,78,80, &
83,84,86,89/
@@ -70,15 +63,21 @@ program sftx
freeTextMsg=' '
bMoreCQs=cmsg(1)(40:40).eq.'1'
bSendMsg=cmsg(nslots)(39:39).eq.'1'
+ nDataSlots=nslots
if(bSendMsg) then
freeTextMsg=cmsg(nslots)(1:26)
- if(nslots.gt.2) nslots=2
+ nDataSlots=nslots-1
+ if(nDataSlots.gt.4) nDataSlots=4
endif
- call foxgen2(nslots,cmsg,line,foxcall) !Parse old-style Fox messages
+ call foxgen2(nDataSlots,cmsg,line,foxcall) !Parse old-style Fox messages
! Pack message information and CRC into xin(0:49)
- call sfox_pack(line,ckey,bMoreCQs,bSendMsg,freeTextMsg,xin)
+ call sfox_pack(line,ckey,bMoreCQs,bSendMsg,freeTextMsg,xin,pack_error)
+ if(pack_error.ne.0) then
+ itone=-99
+ go to 100
+ endif
call qpc_encode(y,xin) !Encode the message to 128 symbols
y=cshift(y,1) !Puncture the code by removing y(0)
y(127)=0
diff --git a/lib/superfox/sftx_sub.f90 b/lib/superfox/sftx_sub.f90
index ed6c678c..310bb059 100644
--- a/lib/superfox/sftx_sub.f90
+++ b/lib/superfox/sftx_sub.f90
@@ -1,4 +1,4 @@
-subroutine sftx_sub(ckey0)
+subroutine sftx_sub(ckey0,pack_error)
! This routine is required in order to create a SuperFox transmission.
@@ -20,6 +20,7 @@ subroutine sftx_sub(ckey0)
character*10 ckey
character*11 foxcall
logical*1 bMoreCQs,bSendMsg
+ integer pack_error
integer*1 xin(0:49) !Packed message as 7-bit symbols
integer*1 y(0:127) !Encoded symbols as i*1 integers
integer chansym0(127) !Transmitted symbols, data only
@@ -35,15 +36,21 @@ subroutine sftx_sub(ckey0)
freeTextMsg=' '
bMoreCQs=cmsg(1)(40:40).eq.'1'
bSendMsg=cmsg(nslots)(39:39).eq.'1'
+ nDataSlots=nslots
if(bSendMsg) then
freeTextMsg=cmsg(nslots)(1:26)
- if(nslots.gt.4) nslots=4
+ nDataSlots=nslots-1
+ if(nDataSlots.gt.4) nDataSlots=4
endif
- call foxgen2(nslots,cmsg,line,foxcall) !Parse old-style Fox messages
+ call foxgen2(nDataSlots,cmsg,line,foxcall) !Parse old-style Fox messages
! Pack message information and CRC into xin(0:49)
- call sfox_pack(line,ckey,bMoreCQs,bSendMsg,freeTextMsg,xin)
+ call sfox_pack(line,ckey,bMoreCQs,bSendMsg,freeTextMsg,xin,pack_error)
+ if(pack_error.ne.0) then
+ itone=-99
+ return
+ endif
call qpc_encode(y,xin) !Encode the message to 128 symbols
y=cshift(y,1) !Puncture the code by removing y(0)
y(127)=0
diff --git a/lib/superfox/superfox_qpc_2.txt b/lib/superfox/superfox_qpc_2.txt
index f89bffe1..51bf80ac 100644
--- a/lib/superfox/superfox_qpc_2.txt
+++ b/lib/superfox/superfox_qpc_2.txt
@@ -50,13 +50,14 @@ G Grid locator (15 bits)
H Hound call (28 bits)
M Message type (3 bits)
Q MoreCQs flag
-R Report, (5 bits: -18 to +12 dB, or RR73)
+R Report, (5 bits: integer dB value -18 through +12, or RR73)
T Free text, up to 26 characters total
U Unused bits
Unused callsign slots are set to the numerical value for "QU1RKS", and
ignored when received. Similarly for unused t71 slots. Unused report
-slots are set to 0 (-20 dB). "CQ FoxCall" will be displayed along
+slots are set to raw value 0, which decodes as -18 dB if displayed.
+"CQ FoxCall" will be displayed along
with other messages if the "q1" bit is 1.
The SuperFox decoder displays its results with a separate line for each Hound.
diff --git a/lib/symspec.f90 b/lib/symspec.f90
index 3f338aa2..9847eb3f 100644
--- a/lib/symspec.f90
+++ b/lib/symspec.f90
@@ -57,7 +57,6 @@ subroutine symspec(shared_data,k,nsps,ingain,bLowSidelobes, &
ja=0
ssum=0.
ihsym=0
- if(.not. shared_data%params%ndiskdat) shared_data%id2(k+1:)=0 !Needed to prevent "ghosts". Not sure why.
endif
gain=10.0**(0.1*ingain)
sq=0.
diff --git a/lib/testEchoCall.f90 b/lib/testEchoCall.f90
index 72059f7f..5f493791 100644
--- a/lib/testEchoCall.f90
+++ b/lib/testEchoCall.f90
@@ -1,17 +1,27 @@
program testEchoCall
+ use, intrinsic :: iso_fortran_env, only: error_unit
+ use readwav, only: wav_header
+
parameter (NSPS=4096,NH=NSPS/2,NZ=3*12000)
integer*2 iwave(NZ) !Raw data, 12000 Hz sample rate
- integer ihdr(11)
- integer*1 itone(6)
- character*120 fname
- character*6 rxcall,hhmmss
+ integer*4 itone(6)
+ type(wav_header) wav
+ character(:), allocatable :: fname
+ character*256 iomsg
+ character*6 rxcall,hhmmss,txcall
+ character*4 extension
+ logical*1 bDiskData,bEchoCall
+ logical valid_time
+ integer argument_length,i,ich,ios,name_length,nerrors,samples_read
common/echocom/nclearave,nsum,blue(4096),red(4096)
common/echocom2/fspread_self,fspread_dx
- narg=iargc()
+ nerrors=0
+ narg=command_argument_count()
if(narg.lt.1) then
print*,'Usage: testEchoCall fname1 [fname2, ...]'
+ nerrors=1
go to 999
endif
@@ -23,21 +33,90 @@ program testEchoCall
navg=10
nauto=1
nqual=0
+ bDiskData=.true.
+ bEchoCall=.false.
+ txcall=' '
do ifile=1,narg
- call getarg(ifile,fname)
- open(10,file=trim(fname),access='stream',status='unknown')
- read(10) ihdr,iwave
- close(10)
+ call get_command_argument(ifile,length=argument_length,status=ios)
+ if(ios.ne.0) then
+ write(error_unit,'(a,i0)') 'testEchoCall: cannot read argument ',ifile
+ nerrors=nerrors+1
+ cycle
+ endif
+ if(allocated(fname)) deallocate(fname)
+ allocate(character(len=max(1,argument_length)) :: fname)
+ call get_command_argument(ifile,value=fname,status=ios)
+ if(ios.ne.0) then
+ write(error_unit,'(a,i0)') 'testEchoCall: cannot read argument ',ifile
+ nerrors=nerrors+1
+ cycle
+ endif
+ name_length=len_trim(fname)
+ valid_time=.false.
+ if(name_length.ge.10) then
+ extension=fname(name_length-3:name_length)
+ do i=1,len(extension)
+ ich=iachar(extension(i:i))
+ if(ich.ge.iachar('A') .and. ich.le.iachar('Z')) then
+ extension(i:i)=achar(ich + iachar('a') - iachar('A'))
+ endif
+ enddo
+ hhmmss=fname(name_length-9:name_length-4)
+ if(extension.eq.'.wav' .and. verify(hhmmss,'0123456789').eq.0) then
+ read(hhmmss,'(3i2)',iostat=ios) ih,im,is
+ if(ios.eq.0) then
+ valid_time=ih.le.23 .and. im.le.59 .and. is.le.59
+ endif
+ endif
+ endif
+ if(.not.valid_time) then
+ write(error_unit,'(a)') &
+ 'testEchoCall: filename must end with a valid HHMMSS.wav timestamp: '//trim(fname)
+ nerrors=nerrors+1
+ cycle
+ endif
+
+ call wav%read(trim(fname),ios,iomsg)
+ if(ios.ne.0) then
+ if(trim(iomsg).eq.'cannot open file') then
+ write(error_unit,'(a)') 'testEchoCall: cannot open '//trim(fname)//': '//trim(iomsg)
+ else
+ write(error_unit,'(a)') 'testEchoCall: cannot read '//trim(fname)//': '//trim(iomsg)
+ endif
+ nerrors=nerrors+1
+ cycle
+ endif
+
+ if(wav%audio_format%sample_rate.ne.12000) then
+ close(wav%lun)
+ write(error_unit,'(a)') &
+ 'testEchoCall: cannot read '//trim(fname)//': expected a 12000 Hz WAV file'
+ nerrors=nerrors+1
+ cycle
+ endif
+
+ call wav%read_samples(iwave,samples_read,ios,iomsg)
+ close(wav%lun)
+ if(ios.ne.0) then
+ write(error_unit,'(a)') &
+ 'testEchoCall: cannot read '//trim(fname)//': '//trim(iomsg)
+ nerrors=nerrors+1
+ cycle
+ endif
+ if(samples_read.lt.NZ) then
+ write(error_unit,'(a,i0,a,i0)') 'testEchoCall: cannot read '//trim(fname)// &
+ ': expected ',NZ,' samples, found ',samples_read
+ nerrors=nerrors+1
+ cycle
+ endif
! Retrieve params known at time of transmissiion and saved in iwave
call save_echo_params(nDop,nDopAudio,nfrit,f1,fspread,ndf,itone,iwave,-1)
fspread_self=fspread
+ width=fspread
- call avecho(iwave,0,nfrit,ndf,nauto,navg,nqual,f1,xlevel,snrdb,db_err,dfreq, &
+ call avecho(iwave,0,nfrit,nauto,navg,nqual,f1,xlevel,snrdb,db_err,dfreq, &
width,bDiskData,bEchoCall,txcall,rxcall)
- i1=index(fname,'.wav')
- hhmmss=fname(i1-6:i1-1)
- read(hhmmss,'(3i2)') ih,im,is
hour=ih + im/60.0 + is/3600.0
write(*,1110) hhmmss,hour,xlevel,ndop,fspread,nsum,nqual,nint(dfreq), &
snrdb,db_err,rxcall
@@ -45,4 +124,5 @@ program testEchoCall
nclearave=0
enddo
-999 end program testEchoCall
+999 if(nerrors.gt.0) stop 1
+end program testEchoCall
diff --git a/lib/tweak1.f90 b/lib/tweak1.f90
index c62c4087..668ba198 100644
--- a/lib/tweak1.f90
+++ b/lib/tweak1.f90
@@ -3,13 +3,10 @@ subroutine tweak1(ca,jz,f0,cb)
! Shift frequency of analytic signal ca, with output to cb
complex ca(jz),cb(jz)
- real*8 twopi
+ real*8, parameter :: twopi=6.283185307179586476925286766559d0
complex*16 w,wstep
complex w4
- data twopi/0.d0/
- save twopi
- if(twopi.eq.0.d0) twopi=8.d0*atan(1.d0)
w=1.d0
dphi=twopi*f0/12000.d0
wstep=cmplx(cos(dphi),sin(dphi))
diff --git a/lib/twkfreq.f90 b/lib/twkfreq.f90
index 7ffe396f..d5c99337 100644
--- a/lib/twkfreq.f90
+++ b/lib/twkfreq.f90
@@ -12,6 +12,15 @@ subroutine twkfreq(c3,c4,npts,fsample,a)
! Mix the complex signal
w=1.0
+ if(a(2).eq.0.0 .and. a(3).eq.0.0) then
+ dphi=a(1)*(twopi/fsample)
+ wstep=cmplx(cos(dphi),sin(dphi))
+ do i=1,npts
+ w=w*wstep
+ c4(i)=w*c3(i)
+ enddo
+ return
+ endif
wstep=1.0
x0=0.5*(npts+1)
s=2.0/npts
diff --git a/lib/types.f90 b/lib/types.f90
index 0fb82320..d3eced0a 100644
--- a/lib/types.f90
+++ b/lib/types.f90
@@ -5,7 +5,6 @@ module types
! use the Fortran 2008 intrinsic constants to define real kinds
integer, parameter :: sp = REAL32
integer, parameter :: dp = REAL64
- integer, parameter :: qp = REAL128
type q3list
character*6 call
diff --git a/lib/vit213.c b/lib/vit213.c
index 93f803ab..73a1f01c 100644
--- a/lib/vit213.c
+++ b/lib/vit213.c
@@ -83,7 +83,7 @@ unsigned int endstate /* Encoder ending state */
){
int bitcnt = -(K-1);
int m0,m1;
- int i,j,sym,ipp;
+ int i,j,sym;
int mets[1 << N];
unsigned int paths[(MAXNBITS+K-1)*D];
unsigned int *pp,mask;
@@ -113,7 +113,6 @@ unsigned int endstate /* Encoder ending state */
cmetric[startstate] = 0;
pp = paths;
- ipp=0;
for(;;){ /* For each data bit */
/* Read input symbols and compute branch metrics */
for(i=0;i< 1<<N;i++){
@@ -152,12 +151,10 @@ unsigned int endstate /* Encoder ending state */
if(mask == 0){
mask = 1;
pp++;
- ipp++;
}
}
if(mask != 1){
pp++;
- ipp++;
}
if(++bitcnt == (int)nbits){
*metric = nmetric[endstate];
@@ -174,7 +171,6 @@ unsigned int endstate /* Encoder ending state */
for(i=nbits-1;i >= 0;i--){
// int a0,a1;
pp -= D;
- ipp -= D;
m0=endstate >> LOGLONGBITS;
m1=1L << (endstate & (LONGBITS-1));
if(pp[m0] & m1) {
diff --git a/lib/wav12.f90 b/lib/wav12.f90
index ff655436..989c9b54 100644
--- a/lib/wav12.f90
+++ b/lib/wav12.f90
@@ -20,6 +20,7 @@ subroutine wav12(d2,d1,npts,nbitsam2)
complex cx(0:NFFT2/2)
integer*2 nbitsam2
equivalence (x,cx),(i1,i2)
+ save d1a,x,cx
jz=min(NZ11,npts)
if(nbitsam2.eq.8) then
diff --git a/lib/wqencode.f90 b/lib/wqencode.f90
index 59b24706..47236856 100644
--- a/lib/wqencode.f90
+++ b/lib/wqencode.f90
@@ -19,7 +19,7 @@ subroutine wqencode(msg,ntype,data0)
call1=msg(:i1-1)
if(i1.lt.3 .or. i1.gt.7 .or. i2.gt.0 .or. i3.gt.0) go to 10
grid4=msg(i1+1:i1+4)
- call packcall(call1,n1,lbad1)
+ call packcall(call1(1:6),n1,lbad1)
call packgrid(grid4,ng,lbad2)
if(lbad1 .or. lbad2) go to 10
ndbm=0
@@ -49,7 +49,7 @@ subroutine wqencode(msg,ntype,data0)
i5=index(trim(msg(i1+1:)),' ')
! Convert grid to valid callsign format - first character moved to end
call2=msg(i1+2:i1+i5-1)//msg(i1+1:i1+1)//' '
- call packcall(call2,n1,lbad1)
+ call packcall(call2(1:6),n1,lbad1)
ndbm=0
read(msg(i1+i5+1:),*) ndbm
if(ndbm.lt.0) ndbm=0
diff --git a/lib/wsprcode/go.sh b/lib/wsprcode/go.sh
index dfce99ea..3c4e1656 100644
--- a/lib/wsprcode/go.sh
+++ b/lib/wsprcode/go.sh
@@ -1 +1 @@
- gfortran -o wsprcode -fbounds-check wsprcode.f90 nhash.c
+ gfortran -o wsprcode -fbounds-check wsprcode.f90 nhash.c ../lookup3.c
diff --git a/lib/wsprcode/nhash.c b/lib/wsprcode/nhash.c
index cbf6df8f..a10f45fb 100644
--- a/lib/wsprcode/nhash.c
+++ b/lib/wsprcode/nhash.c
@@ -1,384 +1,17 @@
-/*
- *-------------------------------------------------------------------------------
- *
- * This file is part of the WSPR application, Weak Signal Propagation Reporter
- *
- * File Name: nhash.c
- * Description: Functions to produce 32-bit hashes for hash table lookup
- *
- * Copyright (C) 2008-2014 Joseph Taylor, K1JT
- * License: GPL-3
- *
- * 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 3 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., 51 Franklin
- * Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Files: lookup3.c
- * Copyright: Copyright (C) 2006 Bob Jenkins <bob_jenkins@burtleburtle.net>
- * License: public-domain
- * You may use this code any way you wish, private, educational, or commercial.
- * It's free.
- *
- *-------------------------------------------------------------------------------
-*/
+#include <stddef.h>
+#include <stdint.h>
-/*
-These are functions for producing 32-bit hashes for hash table lookup.
-hashword(), hashlittle(), hashlittle2(), hashbig(), mix(), and final()
-are externally useful functions. Routines to test the hash are included
-if SELF_TEST is defined. You can use this free for any purpose. It's in
-the public domain. It has no warranty.
+#include "../lookup3.h"
-You probably want to use hashlittle(). hashlittle() and hashbig()
-hash byte arrays. hashlittle() is is faster than hashbig() on
-little-endian machines. Intel and AMD are little-endian machines.
-On second thought, you probably want hashlittle2(), which is identical to
-hashlittle() except it returns two 32-bit hashes for the price of one.
-You could implement hashbig2() if you wanted but I haven't bothered here.
-
-If you want to find a hash of, say, exactly 7 integers, do
- a = i1; b = i2; c = i3;
- mix(a,b,c);
- a += i4; b += i5; c += i6;
- mix(a,b,c);
- a += i7;
- final(a,b,c);
-then use c as the hash value. If you have a variable length array of
-4-byte integers to hash, use hashword(). If you have a byte array (like
-a character string), use hashlittle(). If you have several byte arrays, or
-a mix of things, see the comments above hashlittle().
-
-Why is this so big? I read 12 bytes at a time into 3 4-byte integers,
-then mix those integers. This is fast (you can do a lot more thorough
-mixing with 12*3 instructions on 3 integers than you can with 3 instructions
-on 1 byte), but shoehorning those bytes into integers efficiently is messy.
-*/
-
-#define SELF_TEST 1
-
-#include <stdio.h> /* defines printf for tests */
-#include <time.h> /* defines time_t for timings in the test */
-#ifdef Win32
-#include "win_stdint.h" /* defines uint32_t etc */
-#else
-#include <stdint.h> /* defines uint32_t etc */
-#endif
-//#include <sys/param.h> /* attempt to define endianness */
-//#ifdef linux
-//# include <endian.h> /* attempt to define endianness */
-//#endif
-
-#define HASH_LITTLE_ENDIAN 1
-
-#define hashsize(n) ((uint32_t)1<<(n))
-#define hashmask(n) (hashsize(n)-1)
-#define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
-
-/*
--------------------------------------------------------------------------------
-mix -- mix 3 32-bit values reversibly.
-
-This is reversible, so any information in (a,b,c) before mix() is
-still in (a,b,c) after mix().
-
-If four pairs of (a,b,c) inputs are run through mix(), or through
-mix() in reverse, there are at least 32 bits of the output that
-are sometimes the same for one pair and different for another pair.
-This was tested for:
-* pairs that differed by one bit, by two bits, in any combination
- of top bits of (a,b,c), or in any combination of bottom bits of
- (a,b,c).
-* "differ" is defined as +, -, ^, or ~^. For + and -, I transformed
- the output delta to a Gray code (a^(a>>1)) so a string of 1's (as
- is commonly produced by subtraction) look like a single 1-bit
- difference.
-* the base values were pseudorandom, all zero but one bit set, or
- all zero plus a counter that starts at zero.
-
-Some k values for my "a-=c; a^=rot(c,k); c+=b;" arrangement that
-satisfy this are
- 4 6 8 16 19 4
- 9 15 3 18 27 15
- 14 9 3 7 17 3
-Well, "9 15 3 18 27 15" didn't quite get 32 bits diffing
-for "differ" defined as + with a one-bit base and a two-bit delta. I
-used http://burtleburtle.net/bob/hash/avalanche.html to choose
-the operations, constants, and arrangements of the variables.
-
-This does not achieve avalanche. There are input bits of (a,b,c)
-that fail to affect some output bits of (a,b,c), especially of a. The
-most thoroughly mixed value is c, but it doesn't really even achieve
-avalanche in c.
-
-This allows some parallelism. Read-after-writes are good at doubling
-the number of bits affected, so the goal of mixing pulls in the opposite
-direction as the goal of parallelism. I did what I could. Rotates
-seem to cost as much as shifts on every machine I could lay my hands
-on, and rotates are much kinder to the top and bottom bits, so I used
-rotates.
--------------------------------------------------------------------------------
-*/
-#define mix(a,b,c) \
-{ \
- a -= c; a ^= rot(c, 4); c += b; \
- b -= a; b ^= rot(a, 6); a += c; \
- c -= b; c ^= rot(b, 8); b += a; \
- a -= c; a ^= rot(c,16); c += b; \
- b -= a; b ^= rot(a,19); a += c; \
- c -= b; c ^= rot(b, 4); b += a; \
-}
-
-/*
--------------------------------------------------------------------------------
-final -- final mixing of 3 32-bit values (a,b,c) into c
-
-Pairs of (a,b,c) values differing in only a few bits will usually
-produce values of c that look totally different. This was tested for
-* pairs that differed by one bit, by two bits, in any combination
- of top bits of (a,b,c), or in any combination of bottom bits of
- (a,b,c).
-* "differ" is defined as +, -, ^, or ~^. For + and -, I transformed
- the output delta to a Gray code (a^(a>>1)) so a string of 1's (as
- is commonly produced by subtraction) look like a single 1-bit
- difference.
-* the base values were pseudorandom, all zero but one bit set, or
- all zero plus a counter that starts at zero.
-
-These constants passed:
- 14 11 25 16 4 14 24
- 12 14 25 16 4 14 24
-and these came close:
- 4 8 15 26 3 22 24
- 10 8 15 26 3 22 24
- 11 8 15 26 3 22 24
--------------------------------------------------------------------------------
-*/
-#define final(a,b,c) \
-{ \
- c ^= b; c -= rot(b,14); \
- a ^= c; a -= rot(c,11); \
- b ^= a; b -= rot(a,25); \
- c ^= b; c -= rot(b,16); \
- a ^= c; a -= rot(c,4); \
- b ^= a; b -= rot(a,14); \
- c ^= b; c -= rot(b,24); \
-}
-
-/*
--------------------------------------------------------------------------------
-hashlittle() -- hash a variable-length key into a 32-bit value
- k : the key (the unaligned variable-length array of bytes)
- length : the length of the key, counting by bytes
- initval : can be any 4-byte value
-Returns a 32-bit value. Every bit of the key affects every bit of
-the return value. Two keys differing by one or two bits will have
-totally different hash values.
-
-The best hash table sizes are powers of 2. There is no need to do
-mod a prime (mod is sooo slow!). If you need less than 32 bits,
-use a bitmask. For example, if you need only 10 bits, do
- h = (h & hashmask(10));
-In which case, the hash table should have hashsize(10) elements.
-
-If you are hashing n strings (uint8_t **)k, do it like this:
- for (i=0, h=0; i<n; ++i) h = hashlittle( k[i], len[i], h);
-
-By Bob Jenkins, 2006. bob_jenkins@burtleburtle.net. You may use this
-code any way you wish, private, educational, or commercial. It's free.
-
-Use for hash table lookup, or anything where one collision in 2^^32 is
-acceptable. Do NOT use for cryptographic purposes.
--------------------------------------------------------------------------------
-*/
-
-//uint32_t hashlittle( const void *key, size_t length, uint32_t initval)
+/* Legacy WSPR expects compiler-specific Fortran names and the raw hash. */
#ifdef STDCALL
-uint32_t __stdcall NHASH( const void *key, size_t *length0, uint32_t *initval0)
+uint32_t __stdcall NHASH(const void *key, size_t *length, uint32_t *initval)
+{
+ return wsjt_hashlittle(key, *length, *initval);
+}
#else
-uint32_t nhash_( const void *key, int *length0, uint32_t *initval0)
-#endif
+uint32_t nhash_(const void *key, int *length, uint32_t *initval)
{
- uint32_t a,b,c; /* internal state */
- size_t length;
- uint32_t initval;
- union { const void *ptr; size_t i; } u; /* needed for Mac Powerbook G4 */
-
- length=*length0;
- initval=*initval0;
-
- /* Set up the internal state */
- a = b = c = 0xdeadbeef + ((uint32_t)length) + initval;
-
- u.ptr = key;
- if (HASH_LITTLE_ENDIAN && ((u.i & 0x3) == 0)) {
- const uint32_t *k = (const uint32_t *)key; /* read 32-bit chunks */
- const uint8_t *k8;
-
- k8=0; //Silence compiler warning
- /*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */
- while (length > 12)
- {
- a += k[0];
- b += k[1];
- c += k[2];
- mix(a,b,c);
- length -= 12;
- k += 3;
- }
-
- /*----------------------------- handle the last (probably partial) block */
- /*
- * "k[2]&0xffffff" actually reads beyond the end of the string, but
- * then masks off the part it's not allowed to read. Because the
- * string is aligned, the masked-off tail is in the same word as the
- * rest of the string. Every machine with memory protection I've seen
- * does it on word boundaries, so is OK with this. But VALGRIND will
- * still catch it and complain. The masking trick does make the hash
- * noticably faster for short strings (like English words).
- */
-#ifndef VALGRIND
-
- switch(length)
- {
- case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
- case 11: c+=k[2]&0xffffff; b+=k[1]; a+=k[0]; break;
- case 10: c+=k[2]&0xffff; b+=k[1]; a+=k[0]; break;
- case 9 : c+=k[2]&0xff; b+=k[1]; a+=k[0]; break;
- case 8 : b+=k[1]; a+=k[0]; break;
- case 7 : b+=k[1]&0xffffff; a+=k[0]; break;
- case 6 : b+=k[1]&0xffff; a+=k[0]; break;
- case 5 : b+=k[1]&0xff; a+=k[0]; break;
- case 4 : a+=k[0]; break;
- case 3 : a+=k[0]&0xffffff; break;
- case 2 : a+=k[0]&0xffff; break;
- case 1 : a+=k[0]&0xff; break;
- case 0 : return c; /* zero length strings require no mixing */
- }
-
-#else /* make valgrind happy */
-
- k8 = (const uint8_t *)k;
- switch(length)
- {
- case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
- case 11: c+=((uint32_t)k8[10])<<16; /* fall through */
- case 10: c+=((uint32_t)k8[9])<<8; /* fall through */
- case 9 : c+=k8[8]; /* fall through */
- case 8 : b+=k[1]; a+=k[0]; break;
- case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */
- case 6 : b+=((uint32_t)k8[5])<<8; /* fall through */
- case 5 : b+=k8[4]; /* fall through */
- case 4 : a+=k[0]; break;
- case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */
- case 2 : a+=((uint32_t)k8[1])<<8; /* fall through */
- case 1 : a+=k8[0]; break;
- case 0 : return c;
- }
-
-#endif /* !valgrind */
-
- } else if (HASH_LITTLE_ENDIAN && ((u.i & 0x1) == 0)) {
- const uint16_t *k = (const uint16_t *)key; /* read 16-bit chunks */
- const uint8_t *k8;
-
- /*--------------- all but last block: aligned reads and different mixing */
- while (length > 12)
- {
- a += k[0] + (((uint32_t)k[1])<<16);
- b += k[2] + (((uint32_t)k[3])<<16);
- c += k[4] + (((uint32_t)k[5])<<16);
- mix(a,b,c);
- length -= 12;
- k += 6;
- }
-
- /*----------------------------- handle the last (probably partial) block */
- k8 = (const uint8_t *)k;
- switch(length)
- {
- case 12: c+=k[4]+(((uint32_t)k[5])<<16);
- b+=k[2]+(((uint32_t)k[3])<<16);
- a+=k[0]+(((uint32_t)k[1])<<16);
- break;
- case 11: c+=((uint32_t)k8[10])<<16; /* fall through */
- case 10: c+=k[4];
- b+=k[2]+(((uint32_t)k[3])<<16);
- a+=k[0]+(((uint32_t)k[1])<<16);
- break;
- case 9 : c+=k8[8]; /* fall through */
- case 8 : b+=k[2]+(((uint32_t)k[3])<<16);
- a+=k[0]+(((uint32_t)k[1])<<16);
- break;
- case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */
- case 6 : b+=k[2];
- a+=k[0]+(((uint32_t)k[1])<<16);
- break;
- case 5 : b+=k8[4]; /* fall through */
- case 4 : a+=k[0]+(((uint32_t)k[1])<<16);
- break;
- case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */
- case 2 : a+=k[0];
- break;
- case 1 : a+=k8[0];
- break;
- case 0 : return c; /* zero length requires no mixing */
- }
-
- } else { /* need to read the key one byte at a time */
- const uint8_t *k = (const uint8_t *)key;
-
- /*--------------- all but the last block: affect some 32 bits of (a,b,c) */
- while (length > 12)
- {
- a += k[0];
- a += ((uint32_t)k[1])<<8;
- a += ((uint32_t)k[2])<<16;
- a += ((uint32_t)k[3])<<24;
- b += k[4];
- b += ((uint32_t)k[5])<<8;
- b += ((uint32_t)k[6])<<16;
- b += ((uint32_t)k[7])<<24;
- c += k[8];
- c += ((uint32_t)k[9])<<8;
- c += ((uint32_t)k[10])<<16;
- c += ((uint32_t)k[11])<<24;
- mix(a,b,c);
- length -= 12;
- k += 12;
- }
-
- /*-------------------------------- last block: affect all 32 bits of (c) */
- switch(length) /* all the case statements fall through */
- {
- case 12: c+=((uint32_t)k[11])<<24; /* fall through */
- case 11: c+=((uint32_t)k[10])<<16; /* fall through */
- case 10: c+=((uint32_t)k[9])<<8; /* fall through */
- case 9 : c+=k[8]; /* fall through */
- case 8 : b+=((uint32_t)k[7])<<24; /* fall through */
- case 7 : b+=((uint32_t)k[6])<<16; /* fall through */
- case 6 : b+=((uint32_t)k[5])<<8; /* fall through */
- case 5 : b+=k[4]; /* fall through */
- case 4 : a+=((uint32_t)k[3])<<24; /* fall through */
- case 3 : a+=((uint32_t)k[2])<<16; /* fall through */
- case 2 : a+=((uint32_t)k[1])<<8; /* fall through */
- case 1 : a+=k[0];
- break;
- case 0 : return c;
- }
- }
-
- final(a,b,c);
- return c;
+ return wsjt_hashlittle(key, (size_t)*length, *initval);
}
-
-//uint32_t __stdcall NHASH(const void *key, size_t length, uint32_t initval)
+#endif
diff --git a/lib/wsprcode/wspr_old_subs.f90 b/lib/wsprcode/wspr_old_subs.f90
index a8b5c503..a44dc896 100644
--- a/lib/wsprcode/wspr_old_subs.f90
+++ b/lib/wsprcode/wspr_old_subs.f90
@@ -608,7 +608,7 @@ subroutine packpfx(call1,n1,ng,nadd)
if(call1(i1+2:i1+2).eq.' ') then
! Single-character add-on suffix (maybe also fourth suffix letter?)
call0=call1(:i1-1)
- call packcall(call0,n1,text)
+ call packcall(call0(1:6),n1,text)
nadd=1
nc=ichar(call1(i1+1:i1+1))
if(nc.ge.48 .and. nc.le.57) then
@@ -623,7 +623,7 @@ subroutine packpfx(call1,n1,ng,nadd)
else if(call1(i1+3:i1+3).eq.' ') then
! Two-character numerical suffix, /10 to /99
call0=call1(:i1-1)
- call packcall(call0,n1,text)
+ call packcall(call0(1:6),n1,text)
nadd=1
n=10*(ichar(call1(i1+1:i1+1))-48) + ichar(call1(i1+2:i1+2)) - 48
nadd=1
@@ -634,7 +634,7 @@ subroutine packpfx(call1,n1,ng,nadd)
if(pfx(3:3).eq.' ') pfx=' '//pfx(1:2)
if(pfx(3:3).eq.' ') pfx=' '//pfx(1:2)
call0=call1(i1+1:)
- call packcall(call0,n1,text)
+ call packcall(call0(1:6),n1,text)
ng=0
do i=1,3
@@ -891,7 +891,7 @@ subroutine wqencode(msg,ntype,data0)
call1=msg(:i1-1)
if(i1.lt.3 .or. i1.gt.7 .or. i2.gt.0 .or. i3.gt.0) go to 10
grid4=msg(i1+1:i1+4)
- call packcall(call1,n1,lbad1)
+ call packcall(call1(1:6),n1,lbad1)
call packgrid(grid4,ng,lbad2)
if(lbad1 .or. lbad2) go to 10
ndbm=0
@@ -920,7 +920,7 @@ subroutine wqencode(msg,ntype,data0)
call hash(call1,i4-2,ih)
grid6=msg(i1+1:i1+6)
call2=grid6(2:6)//grid6(1:1)//' '
- call packcall(call2,n1,lbad1)
+ call packcall(call2(1:6),n1,lbad1)
ndbm=0
read(msg(i1+8:),*) ndbm
if(ndbm.lt.0) ndbm=0
diff --git a/lib/wsprd/Makefile b/lib/wsprd/Makefile
index c8e15723..cf8d5edb 100644
--- a/lib/wsprd/Makefile
+++ b/lib/wsprd/Makefile
@@ -20,17 +20,20 @@ LIBS = -lfftw3f -lm -lgfortran
all: wsprd wsprsim
-DEPS = wsprsim_utils.h wsprd_utils.h fano.h jelinek.h nhash.h
+DEPS = wsprsim_utils.h wsprd_utils.h fano.h jelinek.h nhash.h ../lookup3.h
+
+lookup3.o: ../lookup3.c ../lookup3.h
+ ${CC} ${CFLAGS} -c $< -o $@
indexx.o: ../indexx.f90
${FC} -o indexx.o ${FFLAGS} -c ../indexx.f90
-OBJS1 = wsprd.o wsprsim_utils.o wsprd_utils.o tab.o fano.o jelinek.o nhash.o indexx.o osdwspr.o
+OBJS1 = wsprd.o wsprsim_utils.o wsprd_utils.o tab.o fano.o jelinek.o nhash.o lookup3.o indexx.o osdwspr.o
wsprd: $(OBJS1)
$(CC) -o $@ $^ $(CFLAGS) $(LDFLAGS) $(LIBS)
-OBJS2 = wsprsim.o wsprsim_utils.o wsprd_utils.o tab.o fano.o nhash.o
+OBJS2 = wsprsim.o wsprsim_utils.o wsprd_utils.o tab.o fano.o nhash.o lookup3.o
wsprsim: $(OBJS2)
$(CC) -o $@ $^ $(CFLAGS) $(LDFLAGS) $(LIBS)
diff --git a/lib/wsprd/Makefile.MinGW b/lib/wsprd/Makefile.MinGW
index d9fd6b83..4ba8f87c 100644
--- a/lib/wsprd/Makefile.MinGW
+++ b/lib/wsprd/Makefile.MinGW
@@ -21,8 +21,12 @@ LIBS = c:/JTSDK/fftw3f/libfftw3-3.dll -lm
all: wsprd
-DEPS = fano.h
-OBJS1 = wsprd.o wsprd_utils.o fano.o tab.o nhash.o
+DEPS = fano.h nhash.h ../lookup3.h
+
+lookup3.o: ../lookup3.c ../lookup3.h
+ ${CC} ${CFLAGS} -c $< -o $@
+
+OBJS1 = wsprd.o wsprd_utils.o fano.o tab.o nhash.o lookup3.o
wsprd: $(OBJS1)
$(CC) -o $@ $^ $(CFLAGS) $(LDFLAGS) $(LIBS)
diff --git a/lib/wsprd/Makefile.win32 b/lib/wsprd/Makefile.win32
index 8d600d71..a9beb435 100644
--- a/lib/wsprd/Makefile.win32
+++ b/lib/wsprd/Makefile.win32
@@ -21,18 +21,21 @@ LIBS = c:/JTSDK/fftw3f/libfftw3-3.dll -lm
all: wsprd.exe wsprsim.exe wsprd_exp.exe
-DEPS = wsprsim_utils.h wsprd_utils.h fano.h jelinek.h nhash.h
+DEPS = wsprsim_utils.h wsprd_utils.h fano.h jelinek.h nhash.h ../lookup3.h
-OBJS1 = wsprd.o wsprsim_utils.o wsprd_utils.o tab.o fano.o jelinek.o nhash.o
+lookup3.o: ../lookup3.c ../lookup3.h
+ ${CC} ${CFLAGS} -c $< -o $@
+
+OBJS1 = wsprd.o wsprsim_utils.o wsprd_utils.o tab.o fano.o jelinek.o nhash.o lookup3.o
wsprd.exe: $(OBJS1)
$(CC) -o $@ $^ $(CFLAGS) $(LDFLAGS) $(LIBS)
-OBJS2 = wsprsim.o wsprsim_utils.o wsprd_utils.o tab.o fano.o nhash.o
+OBJS2 = wsprsim.o wsprsim_utils.o wsprd_utils.o tab.o fano.o nhash.o lookup3.o
wsprsim.exe: $(OBJS2)
$(CC) -o $@ $^ $(CFLAGS) $(LDFLAGS) $(LIBS)
OBJS3 = wsprd_exp.o wsprsim_utils.o wsprd_utils.o tab.o fano.o jelinek.o \
- nhash.o
+ nhash.o lookup3.o
wsprd_exp.exe: $(OBJS3)
$(CC) -o $@ $^ $(CFLAGS) $(LDFLAGS) $(LIBS)
diff --git a/lib/wsprd/nhash.c b/lib/wsprd/nhash.c
index 5bf6ce04..ca52f262 100644
--- a/lib/wsprd/nhash.c
+++ b/lib/wsprd/nhash.c
@@ -1,383 +1,10 @@
-/*
- This file is part of wsprd.
-
- File name: nhash.c
-
- *------------------------------------------------------------------------------
- *
- * This file is part of the WSPR application, Weak Signal Propogation Reporter
- *
- * File Name: nhash.c
- * Description: Functions to produce 32-bit hashes for hash table lookup
- *
- * Copyright (C) 2008-2014 Joseph Taylor, K1JT
- * License: GNU GPL v3+
- *
- * 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 3 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., 51 Franklin
- * Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * Files: lookup3.c
- * Copyright: Copyright (C) 2006 Bob Jenkins <bob_jenkins@burtleburtle.net>
- * License: public-domain
- * You may use this code any way you wish, private, educational, or commercial.
- * It's free.
- *
- *-------------------------------------------------------------------------------
-*/
-
-/*
-These are functions for producing 32-bit hashes for hash table lookup.
-hashword(), hashlittle(), hashlittle2(), hashbig(), mix(), and final()
-are externally useful functions. Routines to test the hash are included
-if SELF_TEST is defined. You can use this free for any purpose. It's in
-the public domain. It has no warranty.
-
-You probably want to use hashlittle(). hashlittle() and hashbig()
-hash byte arrays. hashlittle() is is faster than hashbig() on
-little-endian machines. Intel and AMD are little-endian machines.
-On second thought, you probably want hashlittle2(), which is identical to
-hashlittle() except it returns two 32-bit hashes for the price of one.
-You could implement hashbig2() if you wanted but I haven't bothered here.
-
-If you want to find a hash of, say, exactly 7 integers, do
- a = i1; b = i2; c = i3;
- mix(a,b,c);
- a += i4; b += i5; c += i6;
- mix(a,b,c);
- a += i7;
- final(a,b,c);
-then use c as the hash value. If you have a variable length array of
-4-byte integers to hash, use hashword(). If you have a byte array (like
-a character string), use hashlittle(). If you have several byte arrays, or
-a mix of things, see the comments above hashlittle().
-
-Why is this so big? I read 12 bytes at a time into 3 4-byte integers,
-then mix those integers. This is fast (you can do a lot more thorough
-mixing with 12*3 instructions on 3 integers than you can with 3 instructions
-on 1 byte), but shoehorning those bytes into integers efficiently is messy.
-*/
-
-#define SELF_TEST 1
-
-#include <stdio.h> /* defines printf for tests */
-#include <time.h> /* defines time_t for timings in the test */
#include "nhash.h"
-//#include <sys/param.h> /* attempt to define endianness */
-//#ifdef linux
-//# include <endian.h> /* attempt to define endianness */
-//#endif
-
-#define HASH_LITTLE_ENDIAN 1
-
-#define hashsize(n) ((uint32_t)1<<(n))
-#define hashmask(n) (hashsize(n)-1)
-#define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
-
-/*
--------------------------------------------------------------------------------
-mix -- mix 3 32-bit values reversibly.
-
-This is reversible, so any information in (a,b,c) before mix() is
-still in (a,b,c) after mix().
-
-If four pairs of (a,b,c) inputs are run through mix(), or through
-mix() in reverse, there are at least 32 bits of the output that
-are sometimes the same for one pair and different for another pair.
-This was tested for:
-* pairs that differed by one bit, by two bits, in any combination
- of top bits of (a,b,c), or in any combination of bottom bits of
- (a,b,c).
-* "differ" is defined as +, -, ^, or ~^. For + and -, I transformed
- the output delta to a Gray code (a^(a>>1)) so a string of 1's (as
- is commonly produced by subtraction) look like a single 1-bit
- difference.
-* the base values were pseudorandom, all zero but one bit set, or
- all zero plus a counter that starts at zero.
-
-Some k values for my "a-=c; a^=rot(c,k); c+=b;" arrangement that
-satisfy this are
- 4 6 8 16 19 4
- 9 15 3 18 27 15
- 14 9 3 7 17 3
-Well, "9 15 3 18 27 15" didn't quite get 32 bits diffing
-for "differ" defined as + with a one-bit base and a two-bit delta. I
-used http://burtleburtle.net/bob/hash/avalanche.html to choose
-the operations, constants, and arrangements of the variables.
-
-This does not achieve avalanche. There are input bits of (a,b,c)
-that fail to affect some output bits of (a,b,c), especially of a. The
-most thoroughly mixed value is c, but it doesn't really even achieve
-avalanche in c.
-
-This allows some parallelism. Read-after-writes are good at doubling
-the number of bits affected, so the goal of mixing pulls in the opposite
-direction as the goal of parallelism. I did what I could. Rotates
-seem to cost as much as shifts on every machine I could lay my hands
-on, and rotates are much kinder to the top and bottom bits, so I used
-rotates.
--------------------------------------------------------------------------------
-*/
-#define mix(a,b,c) \
-{ \
- a -= c; a ^= rot(c, 4); c += b; \
- b -= a; b ^= rot(a, 6); a += c; \
- c -= b; c ^= rot(b, 8); b += a; \
- a -= c; a ^= rot(c,16); c += b; \
- b -= a; b ^= rot(a,19); a += c; \
- c -= b; c ^= rot(b, 4); b += a; \
-}
-
-/*
--------------------------------------------------------------------------------
-final -- final mixing of 3 32-bit values (a,b,c) into c
-
-Pairs of (a,b,c) values differing in only a few bits will usually
-produce values of c that look totally different. This was tested for
-* pairs that differed by one bit, by two bits, in any combination
- of top bits of (a,b,c), or in any combination of bottom bits of
- (a,b,c).
-* "differ" is defined as +, -, ^, or ~^. For + and -, I transformed
- the output delta to a Gray code (a^(a>>1)) so a string of 1's (as
- is commonly produced by subtraction) look like a single 1-bit
- difference.
-* the base values were pseudorandom, all zero but one bit set, or
- all zero plus a counter that starts at zero.
-
-These constants passed:
- 14 11 25 16 4 14 24
- 12 14 25 16 4 14 24
-and these came close:
- 4 8 15 26 3 22 24
- 10 8 15 26 3 22 24
- 11 8 15 26 3 22 24
--------------------------------------------------------------------------------
-*/
-#define final(a,b,c) \
-{ \
- c ^= b; c -= rot(b,14); \
- a ^= c; a -= rot(c,11); \
- b ^= a; b -= rot(a,25); \
- c ^= b; c -= rot(b,16); \
- a ^= c; a -= rot(c,4); \
- b ^= a; b -= rot(a,14); \
- c ^= b; c -= rot(b,24); \
-}
-/*
--------------------------------------------------------------------------------
-hashlittle() -- hash a variable-length key into a 32-bit value
- k : the key (the unaligned variable-length array of bytes)
- length : the length of the key, counting by bytes
- initval : can be any 4-byte value
-Returns a 32-bit value. Every bit of the key affects every bit of
-the return value. Two keys differing by one or two bits will have
-totally different hash values.
+#include "../lookup3.h"
-The best hash table sizes are powers of 2. There is no need to do
-mod a prime (mod is sooo slow!). If you need less than 32 bits,
-use a bitmask. For example, if you need only 10 bits, do
- h = (h & hashmask(10));
-In which case, the hash table should have hashsize(10) elements.
-
-If you are hashing n strings (uint8_t **)k, do it like this:
- for (i=0, h=0; i<n; ++i) h = hashlittle( k[i], len[i], h);
-
-By Bob Jenkins, 2006. bob_jenkins@burtleburtle.net. You may use this
-code any way you wish, private, educational, or commercial. It's free.
-
-Use for hash table lookup, or anything where one collision in 2^^32 is
-acceptable. Do NOT use for cryptographic purposes.
--------------------------------------------------------------------------------
-*/
-
-uint32_t nhash( const void *key, size_t length, uint32_t initval)
+uint32_t nhash(const void *key, size_t length, uint32_t initval)
{
- uint32_t a,b,c; /* internal state */
- union { const void *ptr; size_t i; } u; /* needed for Mac Powerbook G4 */
-
- /* Set up the internal state */
- a = b = c = 0xdeadbeef + ((uint32_t)length) + initval;
-
- u.ptr = key;
- if (HASH_LITTLE_ENDIAN && ((u.i & 0x3) == 0)) {
- const uint32_t *k = (const uint32_t *)key; /* read 32-bit chunks */
-
- /*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */
- while (length > 12)
- {
- a += k[0];
- b += k[1];
- c += k[2];
- mix(a,b,c);
- length -= 12;
- k += 3;
- }
-
- /*----------------------------- handle the last (probably partial) block */
- /*
- * "k[2]&0xffffff" actually reads beyond the end of the string, but
- * then masks off the part it's not allowed to read. Because the
- * string is aligned, the masked-off tail is in the same word as the
- * rest of the string. Every machine with memory protection I've seen
- * does it on word boundaries, so is OK with this. But VALGRIND will
- * still catch it and complain. The masking trick does make the hash
- * noticably faster for short strings (like English words).
- */
-#ifndef VALGRIND
-
- switch(length)
- {
- case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
- case 11: c+=k[2]&0xffffff; b+=k[1]; a+=k[0]; break;
- case 10: c+=k[2]&0xffff; b+=k[1]; a+=k[0]; break;
- case 9 : c+=k[2]&0xff; b+=k[1]; a+=k[0]; break;
- case 8 : b+=k[1]; a+=k[0]; break;
- case 7 : b+=k[1]&0xffffff; a+=k[0]; break;
- case 6 : b+=k[1]&0xffff; a+=k[0]; break;
- case 5 : b+=k[1]&0xff; a+=k[0]; break;
- case 4 : a+=k[0]; break;
- case 3 : a+=k[0]&0xffffff; break;
- case 2 : a+=k[0]&0xffff; break;
- case 1 : a+=k[0]&0xff; break;
- case 0 : return c; /* zero length strings require no mixing */
- }
-
-#else /* make valgrind happy */
-
- k8 = (const uint8_t *)k;
- switch(length)
- {
- case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
- case 11: c+=((uint32_t)k8[10])<<16; /* fall through */
- case 10: c+=((uint32_t)k8[9])<<8; /* fall through */
- case 9 : c+=k8[8]; /* fall through */
- case 8 : b+=k[1]; a+=k[0]; break;
- case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */
- case 6 : b+=((uint32_t)k8[5])<<8; /* fall through */
- case 5 : b+=k8[4]; /* fall through */
- case 4 : a+=k[0]; break;
- case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */
- case 2 : a+=((uint32_t)k8[1])<<8; /* fall through */
- case 1 : a+=k8[0]; break;
- case 0 : return c;
- }
-
-#endif /* !valgrind */
-
- } else if (HASH_LITTLE_ENDIAN && ((u.i & 0x1) == 0)) {
- const uint16_t *k = (const uint16_t *)key; /* read 16-bit chunks */
- const uint8_t *k8;
-
- /*--------------- all but last block: aligned reads and different mixing */
- while (length > 12)
- {
- a += k[0] + (((uint32_t)k[1])<<16);
- b += k[2] + (((uint32_t)k[3])<<16);
- c += k[4] + (((uint32_t)k[5])<<16);
- mix(a,b,c);
- length -= 12;
- k += 6;
- }
-
- /*----------------------------- handle the last (probably partial) block */
- k8 = (const uint8_t *)k;
- switch(length)
- {
- case 12: c+=k[4]+(((uint32_t)k[5])<<16);
- b+=k[2]+(((uint32_t)k[3])<<16);
- a+=k[0]+(((uint32_t)k[1])<<16);
- break;
- case 11: c+=((uint32_t)k8[10])<<16; /* fall through */
- case 10: c+=k[4];
- b+=k[2]+(((uint32_t)k[3])<<16);
- a+=k[0]+(((uint32_t)k[1])<<16);
- break;
- case 9 : c+=k8[8]; /* fall through */
- case 8 : b+=k[2]+(((uint32_t)k[3])<<16);
- a+=k[0]+(((uint32_t)k[1])<<16);
- break;
- case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */
- case 6 : b+=k[2];
- a+=k[0]+(((uint32_t)k[1])<<16);
- break;
- case 5 : b+=k8[4]; /* fall through */
- case 4 : a+=k[0]+(((uint32_t)k[1])<<16);
- break;
- case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */
- case 2 : a+=k[0];
- break;
- case 1 : a+=k8[0];
- break;
- case 0 : return c; /* zero length requires no mixing */
- }
-
- } else { /* need to read the key one byte at a time */
- const uint8_t *k = (const uint8_t *)key;
-
- /*--------------- all but the last block: affect some 32 bits of (a,b,c) */
- while (length > 12)
- {
- a += k[0];
- a += ((uint32_t)k[1])<<8;
- a += ((uint32_t)k[2])<<16;
- a += ((uint32_t)k[3])<<24;
- b += k[4];
- b += ((uint32_t)k[5])<<8;
- b += ((uint32_t)k[6])<<16;
- b += ((uint32_t)k[7])<<24;
- c += k[8];
- c += ((uint32_t)k[9])<<8;
- c += ((uint32_t)k[10])<<16;
- c += ((uint32_t)k[11])<<24;
- mix(a,b,c);
- length -= 12;
- k += 12;
- }
-
- /*-------------------------------- last block: affect all 32 bits of (c) */
- switch(length) /* all the case statements fall through */
- {
- case 12: c+=((uint32_t)k[11])<<24;
- /* fall through */
- case 11: c+=((uint32_t)k[10])<<16;
- /* fall through */
- case 10: c+=((uint32_t)k[9])<<8;
- /* fall through */
- case 9 : c+=k[8];
- /* fall through */
- case 8 : b+=((uint32_t)k[7])<<24;
- /* fall through */
- case 7 : b+=((uint32_t)k[6])<<16;
- /* fall through */
- case 6 : b+=((uint32_t)k[5])<<8;
- /* fall through */
- case 5 : b+=k[4];
- /* fall through */
- case 4 : a+=((uint32_t)k[3])<<24;
- /* fall through */
- case 3 : a+=((uint32_t)k[2])<<16;
- /* fall through */
- case 2 : a+=((uint32_t)k[1])<<8;
- /* fall through */
- case 1 : a+=k[0];
- break;
- case 0 : return c;
- }
- }
-
- final(a,b,c);
- c=(32767&c);
-
- return c;
+ /* WSPR table indices use 15 bits; empty keys historically bypass the mask. */
+ uint32_t hash = wsjt_hashlittle(key, length, initval);
+ return length == 0 ? hash : hash & (uint32_t)0x7fff;
}
diff --git a/lib/wsprd/osdwspr.f90 b/lib/wsprd/osdwspr.f90
index 2a2d712d..31ece6a0 100644
--- a/lib/wsprd/osdwspr.f90
+++ b/lib/wsprd/osdwspr.f90
@@ -133,6 +133,8 @@ elseif(ndeep.eq.5) then
nt=66
ntheta=22
ntau=16
+else
+ goto 998
endif
do iorder=1,nord
diff --git a/lib/wsprd/wsprd.c b/lib/wsprd/wsprd.c
index 13f8d8b3..d442c70b 100644
--- a/lib/wsprd/wsprd.c
+++ b/lib/wsprd/wsprd.c
@@ -42,6 +42,7 @@
#include "nhash.h"
#include "wsprd_utils.h"
#include "wsprsim_utils.h"
+#include "wsprd_stream.h"
#define max(x,y) ((x) > (y) ? (x) : (y))
@@ -727,6 +728,23 @@ void usage(void)
printf(" -v verbose mode (shows dupes)\n");
printf(" -w wideband mode - decode signals within +/- 150 Hz of center\n");
printf(" -z x (x is fano metric table bias, default is 0.45)\n");
+ printf(" -0 streaming mode: read PCM audio from stdin per the\n");
+ printf(" streaming framing protocol; emit decodes as NDJSON\n");
+ printf(" on stdout. Replaces the positional\n");
+ printf(" input file argument.\n");
+}
+
+static int build_data_path(char *destination, size_t capacity,
+ const char *data_dir, const char *filename)
+{
+ const char *base = data_dir ? data_dir : ".";
+ int written = snprintf(destination, capacity, "%s/%s", base, filename);
+ if (written < 0 || (size_t)written >= capacity) {
+ fprintf(stderr, "Error: data path for '%s' exceeds %zu bytes\n",
+ filename, capacity - 1);
+ return -1;
+ }
+ return 0;
}
//***************************************************************************
@@ -740,13 +758,15 @@ int main(int argc, char *argv[])
unsigned char *symbols, *decdata, *channel_symbols, *apmask, *cw;
signed char message[]={-9,13,-35,123,57,-39,64,0,0,0,0};
char *callsign, *grid, *call_loc_pow;
- char *ptr_to_infile,*ptr_to_infile_suffix;
+ char *ptr_to_infile = NULL, *ptr_to_infile_suffix = NULL;
char *data_dir=".";
char wisdom_fname[200],all_fname[200],spots_fname[200];
char timer_fname[200],hash_fname[200];
char uttime[5],date[7];
int c,delta,maxpts=65536,verbose=0,quickmode=0,more_candidates=0, stackdecoder=0;
int usehashtable=1,wspr_type=2, ipass, nblocksize;
+ int stream_mode = 0;
+ struct wsprd_stream_config stream_cfg = {0};
int nhardmin,ihash;
int writec2=0,maxdrift;
int shift1, lagmin, lagmax, lagstep, ifmin, ifmax, not_decoded;
@@ -777,10 +797,9 @@ int main(int argc, char *argv[])
struct result decodes[50];
char *hashtab;
- hashtab=calloc(32768*13,sizeof(char));
+ hashtab=calloc(WSPRD_HASH_COUNT*WSPRD_CALLSIGN_SIZE,sizeof(char));
char *loctab;
- loctab=calloc(32768*5,sizeof(char));
- int nh;
+ loctab=calloc(WSPRD_HASH_COUNT*WSPRD_GRID4_SIZE,sizeof(char));
symbols=calloc(nbits*2,sizeof(unsigned char));
apmask=calloc(162,sizeof(unsigned char));
cw=calloc(162,sizeof(unsigned char));
@@ -818,8 +837,26 @@ int main(int argc, char *argv[])
idat=calloc(maxpts,sizeof(float));
qdat=calloc(maxpts,sizeof(float));
+ if (!hashtab || !loctab || !symbols || !apmask || !cw || !decdata ||
+ !channel_symbols || !callsign || !grid || !call_loc_pow ||
+ !idat || !qdat) {
+ fprintf(stderr, "Error: unable to allocate wsprd decoder buffers\n");
+ free(hashtab);
+ free(loctab);
+ free(symbols);
+ free(apmask);
+ free(cw);
+ free(decdata);
+ free(channel_symbols);
+ free(callsign);
+ free(grid);
+ free(call_loc_pow);
+ free(idat);
+ free(qdat);
+ return EXIT_FAILURE;
+ }
- while ( (c = getopt(argc, argv, "a:BcC:de:f:HJmo:qstwvz:")) !=-1 ) {
+ while ( (c = getopt(argc, argv, "a:BcC:de:f:HJmo:qstwvz:0")) !=-1 ) {
switch (c) {
case 'a':
data_dir = optarg;
@@ -872,6 +909,9 @@ int main(int argc, char *argv[])
case 'z':
bias=strtod(optarg,NULL); //fano metric bias (default is 0.45)
break;
+ case '0': // --stream (long-name parity with jt9 --stream)
+ stream_mode = 1;
+ break;
case '?':
usage();
return 1;
@@ -884,15 +924,19 @@ int main(int argc, char *argv[])
return EXIT_FAILURE;
}
- if( optind+1 > argc) {
+ if( !stream_mode && optind+1 > argc) {
usage();
return 1;
- } else {
+ } else if (!stream_mode) {
ptr_to_infile=argv[optind];
}
if( stackdecoder ) {
stack=calloc(stacksize,sizeof(struct snode));
+ if (!stack) {
+ fprintf(stderr, "Error: unable to allocate wsprd stack decoder\n");
+ return EXIT_FAILURE;
+ }
}
// setup metric table
@@ -902,23 +946,18 @@ int main(int argc, char *argv[])
}
FILE *fp_fftwf_wisdom_file, *fall_wspr, *fwsprd, *fhash, *ftimer;
- strcpy(wisdom_fname,".");
- strcpy(all_fname,".");
- strcpy(spots_fname,".");
- strcpy(timer_fname,".");
- strcpy(hash_fname,".");
- if(data_dir != NULL) {
- strncpy(wisdom_fname,data_dir, sizeof wisdom_fname);
- strncpy(all_fname,data_dir, sizeof all_fname);
- strncpy(spots_fname,data_dir, sizeof spots_fname);
- strncpy(timer_fname,data_dir, sizeof timer_fname);
- strncpy(hash_fname,data_dir, sizeof hash_fname);
+ if (build_data_path(wisdom_fname, sizeof wisdom_fname, data_dir,
+ "wspr_wisdom.dat") != 0 ||
+ build_data_path(all_fname, sizeof all_fname, data_dir,
+ "ALL_WSPR.TXT") != 0 ||
+ build_data_path(spots_fname, sizeof spots_fname, data_dir,
+ "wspr_spots.txt") != 0 ||
+ build_data_path(timer_fname, sizeof timer_fname, data_dir,
+ "wspr_timer.out") != 0 ||
+ build_data_path(hash_fname, sizeof hash_fname, data_dir,
+ "hashtable.txt") != 0) {
+ return EXIT_FAILURE;
}
- strncat(wisdom_fname,"/wspr_wisdom.dat",20);
- strncat(all_fname,"/ALL_WSPR.TXT",20);
- strncat(spots_fname,"/wspr_spots.txt",20);
- strncat(timer_fname,"/wspr_timer.out",20);
- strncat(hash_fname,"/hashtable.txt",20);
if ((fp_fftwf_wisdom_file = fopen(wisdom_fname, "r"))) { //Open FFTW wisdom
fftwf_import_wisdom_from_file(fp_fftwf_wisdom_file);
fclose(fp_fftwf_wisdom_file);
@@ -938,17 +977,35 @@ int main(int argc, char *argv[])
}
ftimer=fopen(timer_fname,"w");
- if( strstr(ptr_to_infile,".wav") ) {
+ if (stream_mode) {
+ // Read PCM from stdin per the streaming protocol. Configure frame
+ // supplies date/time/dialfreq/wspr_type; audio frames carry int16
+ // PCM @ 12 kHz mono.
+ wsprd_stream_emit_ready();
+ t0 = clock();
+ npoints = wsprd_stream_read(&stream_cfg, idat, qdat);
+ treadwav += (float)(clock()-t0)/CLOCKS_PER_SEC;
+ if (npoints == 1) return 1;
+ wspr_type = stream_cfg.wspr_type;
+ dialfreq = stream_cfg.dialfreq - (dialfreq_error * 1.0e-06);
+ strncpy(date, stream_cfg.date, 6); date[6] = '\0';
+ strncpy(uttime, stream_cfg.uttime, 4); uttime[4] = '\0';
+ } else if( strstr(ptr_to_infile,".wav") ) {
ptr_to_infile_suffix=strstr(ptr_to_infile,".wav");
-
+
t0 = clock();
npoints=readwavfile(ptr_to_infile, wspr_type, idat, qdat);
treadwav += (float)(clock()-t0)/CLOCKS_PER_SEC;
-
+
if( npoints == 1 ) {
return 1;
}
dialfreq=dialfreq_cmdline - (dialfreq_error*1.0e-06);
+ // Parse date and time from given filename
+ strncpy(date,ptr_to_infile_suffix-11,6);
+ strncpy(uttime,ptr_to_infile_suffix-4,4);
+ date[6]='\0';
+ uttime[4]='\0';
} else if ( strstr(ptr_to_infile,".c2") !=0 ) {
ptr_to_infile_suffix=strstr(ptr_to_infile,".c2");
npoints=readc2file(ptr_to_infile, idat, qdat, &dialfreq, &wspr_type);
@@ -956,23 +1013,34 @@ int main(int argc, char *argv[])
return 1;
}
dialfreq -= (dialfreq_error*1.0e-06);
+ // Parse date and time from given filename
+ strncpy(date,ptr_to_infile_suffix-11,6);
+ strncpy(uttime,ptr_to_infile_suffix-4,4);
+ date[6]='\0';
+ uttime[4]='\0';
} else {
printf("Error: Failed to open %s\n",ptr_to_infile);
printf("WSPR file must have suffix .wav or .c2\n");
return 1;
}
- // Parse date and time from given filename
- strncpy(date,ptr_to_infile_suffix-11,6);
- strncpy(uttime,ptr_to_infile_suffix-4,4);
- date[6]='\0';
- uttime[4]='\0';
-
// Do windowed ffts over 2 symbols, stepped by half symbols
int nffts=4*floor(npoints/512)-1;
fftin=(fftwf_complex*) fftwf_malloc(sizeof(fftwf_complex)*512);
fftout=(fftwf_complex*) fftwf_malloc(sizeof(fftwf_complex)*512);
+ if (!fftin || !fftout) {
+ fprintf(stderr, "Error: unable to allocate wsprd FFT buffers\n");
+ if (fftin) fftwf_free(fftin);
+ if (fftout) fftwf_free(fftout);
+ return EXIT_FAILURE;
+ }
PLAN3 = fftwf_plan_dft_1d(512, fftin, fftout, FFTW_FORWARD, PATIENCE);
+ if (!PLAN3) {
+ fprintf(stderr, "Error: unable to create wsprd FFT plan\n");
+ fftwf_free(fftin);
+ fftwf_free(fftout);
+ return EXIT_FAILURE;
+ }
float ps[512][nffts];
float w[512];
@@ -981,13 +1049,10 @@ int main(int argc, char *argv[])
}
if( usehashtable ) {
- char line[80], hcall[13], hgrid[5];
+ char line[80];
if( (fhash=fopen(hash_fname,"r+")) ) {
while (fgets(line, sizeof(line), fhash) != NULL) {
- hgrid[0]='\0';
- sscanf(line,"%d %s %s",&nh,hcall,hgrid);
- strcpy(hashtab+nh*13,hcall);
- if(strlen(hgrid)>0) strcpy(loctab+nh*5,hgrid);
+ wsprd_load_hash_line(line, hashtab, loctab);
}
} else {
fhash=fopen(hash_fname,"w+");
@@ -1003,7 +1068,7 @@ int main(int argc, char *argv[])
maxdrift=4;
minsync2=0.12;
}
- if(ipass == 2 ) {
+ else {
nblocksize=4; // try 3 blocksizes plus bitbybit normalization
maxdrift=0; // no drift for smaller frequency estimator variance
minsync2=0.10;
@@ -1444,7 +1509,8 @@ int main(int argc, char *argv[])
if(!strcmp(callsign,allcalls[i]) &&
(fabs(f1-allfreqs[i]) <4.0)) dupe=1;
}
- if( (verbose || !dupe) && !noprint) {
+ if( (verbose || !dupe) && !noprint &&
+ uniques < (int)(sizeof decodes / sizeof decodes[0]) ) {
strcpy(allcalls[uniques],callsign);
allfreqs[uniques]=f1;
uniques++;
@@ -1502,9 +1568,16 @@ int main(int argc, char *argv[])
}
for (i=0; i<uniques; i++) {
- printf("%4s %3.0f %4.1f %10.6f %2d %-s \n",
- decodes[i].time, decodes[i].snr,decodes[i].dt, decodes[i].freq,
- (int)decodes[i].drift, decodes[i].message);
+ if (stream_mode) {
+ wsprd_stream_emit_decode(date, decodes[i].time,
+ decodes[i].snr, decodes[i].dt,
+ decodes[i].freq, (int)decodes[i].drift,
+ decodes[i].message);
+ } else {
+ printf("%4s %3.0f %4.1f %10.6f %2d %-s \n",
+ decodes[i].time, decodes[i].snr,decodes[i].dt, decodes[i].freq,
+ (int)decodes[i].drift, decodes[i].message);
+ }
fprintf(fall_wspr,
"%6s %4s %3.0f %5.2f %11.7f %-22s %2d %5.2f %2d %2d %4d %2d %3d %5u %5d\n",
decodes[i].date, decodes[i].time, decodes[i].snr,
@@ -1521,7 +1594,11 @@ int main(int argc, char *argv[])
decodes[i].jitter);
}
- printf("<DecodeFinished>\n");
+ if (stream_mode) {
+ wsprd_stream_emit_decode_finished(date, uttime);
+ } else {
+ printf("<DecodeFinished>\n");
+ }
fftwf_free(fftin);
fftwf_free(fftout);
@@ -1553,15 +1630,17 @@ int main(int argc, char *argv[])
fclose(fwsprd);
// fclose(fdiag);
fclose(ftimer);
- fftwf_destroy_plan(PLAN1);
- fftwf_destroy_plan(PLAN2);
- fftwf_destroy_plan(PLAN3);
+ if (PLAN1) fftwf_destroy_plan(PLAN1);
+ if (PLAN2) fftwf_destroy_plan(PLAN2);
+ if (PLAN3) fftwf_destroy_plan(PLAN3);
if( usehashtable ) {
fhash=fopen(hash_fname,"w");
- for (i=0; i<32768; i++) {
- if( strncmp(hashtab+i*13,"\0",1) != 0 ) {
- fprintf(fhash,"%5d %s %s\n",i,hashtab+i*13,loctab+i*5);
+ for (i=0; i<WSPRD_HASH_COUNT; i++) {
+ if( strncmp(hashtab+i*WSPRD_CALLSIGN_SIZE,"\0",1) != 0 ) {
+ fprintf(fhash,"%5d %s %s\n",i,
+ hashtab+i*WSPRD_CALLSIGN_SIZE,
+ loctab+i*WSPRD_GRID4_SIZE);
}
}
fclose(fhash);
@@ -1570,9 +1649,12 @@ int main(int argc, char *argv[])
free(hashtab);
free(loctab);
free(symbols);
+ free(apmask);
+ free(cw);
free(decdata);
free(channel_symbols);
free(callsign);
+ free(grid);
free(call_loc_pow);
free(idat);
free(qdat);
diff --git a/lib/wsprd/wsprd_stream.c b/lib/wsprd/wsprd_stream.c
new file mode 100644
index 00000000..8d4628a2
--- /dev/null
+++ b/lib/wsprd/wsprd_stream.c
@@ -0,0 +1,571 @@
+/*
+ * wsprd streaming layer.
+ *
+ * Adds `wsprd --stream` mode: read PCM audio from stdin (per the
+ * streaming framing) instead of from a .wav/.c2 file, run the
+ * standard wsprd decode pipeline, and emit decodes as NDJSON on stdout
+ * (matching the jt9 --stream protocol).
+ *
+ * Streaming protocol summary:
+ * 1. WSJT session header (8 bytes): magic 'WSJT' + fmt + ch + rate_kHz
+ * LE u16. fmt=0x00 = int16 PCM (same as jt9). For wsprd, audio is
+ * always 12 kHz mono int16.
+ * 2. Frames: [type:1][len:4 LE][body:len]
+ * type 0x01 = audio chunk (int16 PCM samples)
+ * type 0x02 = control JSON (configure / halt)
+ * 3. Configure frame schema (subset of jt9):
+ * {"t":"configure","date":"YYMMDD","time":"HHMM",
+ * "dialfreq":14.0956,"wspr_type":2,
+ * "mycall":"K1JT","mygrid":"FN20"}
+ * The configure frame must arrive before enough audio for one period.
+ * 4. Halt frame: {"t":"halt"} — drains current period if data buffered,
+ * emits decode_finished, exits clean.
+ *
+ * NDJSON schema (v=1, mirrors jt9):
+ * {"v":1,"t":"ready","modes":["WSPR"],"protocol":1}
+ * {"v":1,"t":"decode","mode":"WSPR","date":"YYMMDD","time":"HHMM",
+ * "snr":-12,"dt":0.6,"freq":14.097103,"drift":0,"message":"K1JT FN20 33"}
+ * {"v":1,"t":"decode_finished","date":"YYMMDD","time":"HHMM"}
+ * {"v":1,"t":"error","msg":"..."}
+ *
+ * Scope:
+ * - One period per session. Halt after the first period's decode.
+ * Multi-period (continuous) is a refinement.
+ * - PCM input only (fmt=0x00). C2 baseband (fmt=0x02) is a refinement.
+ * - Hand-rolled JSON parsing (strstr-based). Acceptable for the closed
+ * configure schema.
+ * - All diagnostics go to stderr (consumers MUST drain).
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdint.h>
+#include <errno.h>
+#include <limits.h>
+#include <math.h>
+#include <fftw3.h>
+#ifdef _WIN32
+#include <fcntl.h>
+#include <io.h>
+#endif
+
+#include "wsprd_stream.h"
+
+#define WSJT_MAGIC "WSJT"
+#define WSJT_FMT_PCM 0x00
+#define FRAME_AUDIO 0x01
+#define FRAME_CONTROL 0x02
+
+// Buffer the producer's audio chunks. Sized for WSPR-15 worst case
+// (8 * 114 * 12000 = 10,944,000 samples). WSPR-2 needs only 1,368,000.
+#define MAX_PCM_SAMPLES (8 * 114 * 12000)
+#define MAX_CONTROL_FRAME 1024U
+
+// ============================================================
+// JSON parsing for the flat, ASCII streaming control schema.
+// ============================================================
+
+static const char *skip_space(const char *p) {
+ while (*p == ' ' || *p == '\t' || *p == '\r' || *p == '\n') p++;
+ return p;
+}
+
+static const char *skip_json_string(const char *p) {
+ if (*p != '"') return NULL;
+ for (p++; *p; p++) {
+ if (*p == '\\' && p[1]) {
+ p++;
+ } else if (*p == '"') {
+ return p + 1;
+ }
+ }
+ return NULL;
+}
+
+static const char *json_find_key(const char *json, const char *key) {
+ const size_t key_len = strlen(key);
+ const char *p = skip_space(json);
+ if (*p != '{') return NULL;
+ p++;
+
+ for (;;) {
+ p = skip_space(p);
+ if (*p == ',') {
+ p = skip_space(p + 1);
+ }
+ if (*p == '}') return NULL;
+ if (*p != '"') return NULL;
+
+ const char *name = p + 1;
+ const char *after_name = skip_json_string(p);
+ if (!after_name) return NULL;
+ const size_t name_len = (size_t)(after_name - name - 1);
+ p = skip_space(after_name);
+ if (*p != ':') return NULL;
+ const char *value = skip_space(p + 1);
+ if (name_len == key_len && memcmp(name, key, key_len) == 0) {
+ return *value ? value : NULL;
+ }
+
+ if (*value == '"') {
+ p = skip_json_string(value);
+ if (!p) return NULL;
+ } else {
+ p = value;
+ while (*p && *p != ',' && *p != '}') p++;
+ }
+ if (*p == '}') return NULL;
+ }
+}
+
+static int json_get_string(const char *json, const char *key,
+ char *out, size_t out_size) {
+ const char *p = json_find_key(json, key);
+ if (!p || *p != '"') return -1;
+ p++;
+ size_t i = 0;
+ while (*p && *p != '"' && i + 1 < out_size) {
+ out[i++] = *p++;
+ }
+ out[i] = '\0';
+ return (*p == '"') ? 0 : -1;
+}
+
+static int json_get_int(const char *json, const char *key, int *out) {
+ const char *p = json_find_key(json, key);
+ if (!p) return -1;
+ char *end = NULL;
+ errno = 0;
+ long v = strtol(p, &end, 10);
+ if (end == p || errno == ERANGE || v < INT_MIN || v > INT_MAX) return -1;
+ end = (char *)skip_space(end);
+ if (*end != ',' && *end != '}') return -1;
+ *out = (int) v;
+ return 0;
+}
+
+static int json_get_double(const char *json, const char *key, double *out) {
+ const char *p = json_find_key(json, key);
+ if (!p) return -1;
+ char *end = NULL;
+ double v = strtod(p, &end);
+ if (end == p) return -1;
+ *out = v;
+ return 0;
+}
+
+// ============================================================
+// Frame I/O.
+// ============================================================
+
+static void set_stdin_binary(void) {
+#ifdef _WIN32
+ _setmode(_fileno(stdin), _O_BINARY);
+#endif
+}
+
+static int wsjt_header_read(FILE *fp) {
+ unsigned char hdr[8];
+ if (fread(hdr, 1, 8, fp) != 8) {
+ fprintf(stderr, "wsprd --stream: short read on WSJT header\n");
+ return -1;
+ }
+ if (memcmp(hdr, WSJT_MAGIC, 4) != 0) {
+ fprintf(stderr, "wsprd --stream: bad magic; expected 'WSJT'\n");
+ return -1;
+ }
+ unsigned char fmt = hdr[4];
+ unsigned char ch = hdr[5];
+ uint16_t rate_khz = (uint16_t)hdr[6] | ((uint16_t)hdr[7] << 8);
+ if (fmt != WSJT_FMT_PCM) {
+ fprintf(stderr,
+ "wsprd --stream: unsupported fmt=0x%02x (only 0x00 PCM today)\n",
+ fmt);
+ return -1;
+ }
+ if (ch != 1) {
+ fprintf(stderr,
+ "wsprd --stream: unsupported channels=%u (only mono supported)\n",
+ ch);
+ return -1;
+ }
+ if (rate_khz != 12) {
+ fprintf(stderr,
+ "wsprd --stream: unsupported rate=%u kHz (only 12 kHz supported)\n",
+ rate_khz);
+ return -1;
+ }
+ fprintf(stderr,
+ "wsprd --stream: header ok (fmt=%u ch=%u rate=%u kHz)\n",
+ fmt, ch, rate_khz);
+ return 0;
+}
+
+// Reads one frame envelope. *body is malloc'd on success; caller frees.
+// Returns 0 ok, -1 err, +1 EOF (clean producer-disconnect).
+static int frame_read(FILE *fp, unsigned char *type, void **body, uint32_t *len) {
+ unsigned char hdr[5];
+ size_t nr = fread(hdr, 1, 5, fp);
+ if (nr == 0) return 1; // clean EOF
+ if (nr != 5) {
+ fprintf(stderr, "wsprd --stream: short read on frame header\n");
+ return -1;
+ }
+ *type = hdr[0];
+ *len = (uint32_t)hdr[1] | ((uint32_t)hdr[2] << 8) |
+ ((uint32_t)hdr[3] << 16) | ((uint32_t)hdr[4] << 24);
+ const uint32_t max_len = *type == FRAME_CONTROL
+ ? MAX_CONTROL_FRAME
+ : (uint32_t)(MAX_PCM_SAMPLES * sizeof(int16_t));
+ if (*len > max_len) {
+ char detail[160];
+ snprintf(detail, sizeof detail,
+ "frame length %u exceeds type capacity %u", *len, max_len);
+ wsprd_stream_emit_error_code("frame_too_large", detail);
+ fprintf(stderr, "wsprd --stream: %s\n", detail);
+ return -1;
+ }
+ if (*len == 0) {
+ *body = NULL;
+ return 0;
+ }
+ *body = malloc(*len);
+ if (!*body) {
+ fprintf(stderr, "wsprd --stream: alloc %u bytes failed\n", *len);
+ wsprd_stream_emit_error_code("allocation_failed",
+ "unable to allocate frame body");
+ return -1;
+ }
+ if (fread(*body, 1, *len, fp) != *len) {
+ fprintf(stderr, "wsprd --stream: short read on frame body (%u bytes)\n",
+ *len);
+ free(*body);
+ *body = NULL;
+ wsprd_stream_emit_error_code("frame_read_error",
+ "short read on frame body");
+ return -1;
+ }
+ return 0;
+}
+
+// ============================================================
+// PCM → I/Q FFT/extract/IFFT (mirrors readwavfile lines 155-188).
+// ============================================================
+
+static unsigned long pcm_to_iq(int16_t *pcm, size_t npcm, int ntrmin,
+ float *idat, float *qdat) {
+ int nfft1, nfft2 = 46080, nh2 = nfft2 / 2, i0;
+ double df;
+ size_t expected_npcm;
+ float *realin = NULL;
+ fftwf_complex *fftout = NULL;
+ fftwf_complex *fftin = NULL;
+ fftwf_complex *fftout2 = NULL;
+ fftwf_plan plan_fwd = NULL;
+ fftwf_plan plan_inv = NULL;
+ unsigned long result = 1;
+
+ if (ntrmin == 2) {
+ nfft1 = nfft2 * 32;
+ df = 12000.0 / nfft1;
+ i0 = 1500.0 / df + 0.5;
+ expected_npcm = 114 * 12000;
+ } else if (ntrmin == 15) {
+ nfft1 = nfft2 * 8 * 32;
+ df = 12000.0 / nfft1;
+ i0 = (1500.0 + 112.5) / df + 0.5;
+ expected_npcm = 8 * 114 * 12000;
+ } else {
+ fprintf(stderr, "wsprd --stream: invalid wspr_type=%d\n", ntrmin);
+ wsprd_stream_emit_error_code("invalid_wspr_type",
+ "wspr_type must be 2 or 15");
+ return 1;
+ }
+
+ if (npcm < expected_npcm) {
+ fprintf(stderr,
+ "wsprd --stream: short PCM (got %zu, expected %zu for WSPR-%d)\n",
+ npcm, expected_npcm, ntrmin);
+ wsprd_stream_emit_error_code("insufficient_audio",
+ "not enough PCM samples for the configured WSPR type");
+ return 1;
+ }
+
+ realin = fftwf_malloc(sizeof(float) * (size_t)nfft1);
+ fftout = fftwf_malloc(sizeof(fftwf_complex) * ((size_t)nfft1 / 2 + 1));
+ if (!realin || !fftout) {
+ wsprd_stream_emit_error_code("allocation_failed",
+ "unable to allocate streaming FFT buffers");
+ goto cleanup;
+ }
+ plan_fwd = fftwf_plan_dft_r2c_1d(nfft1, realin, fftout, FFTW_ESTIMATE);
+ if (!plan_fwd) {
+ wsprd_stream_emit_error_code("allocation_failed",
+ "unable to create streaming forward FFT plan");
+ goto cleanup;
+ }
+
+ for (size_t i = 0; i < expected_npcm; i++) realin[i] = pcm[i] / 32768.0f;
+ for (size_t i = expected_npcm; i < (size_t)nfft1; i++) realin[i] = 0.0f;
+
+ fftwf_execute(plan_fwd);
+ fftwf_destroy_plan(plan_fwd);
+ plan_fwd = NULL;
+ fftwf_free(realin);
+ realin = NULL;
+
+ fftin = fftwf_malloc(sizeof(fftwf_complex) * (size_t)nfft2);
+ if (!fftin) {
+ wsprd_stream_emit_error_code("allocation_failed",
+ "unable to allocate streaming inverse FFT input");
+ goto cleanup;
+ }
+ for (size_t i = 0; i < (size_t)nfft2; i++) {
+ size_t j = i0 + i;
+ if (i > (size_t)nh2) j = j - nfft2;
+ fftin[i][0] = fftout[j][0];
+ fftin[i][1] = fftout[j][1];
+ }
+ fftwf_free(fftout);
+ fftout = NULL;
+
+ fftout2 = fftwf_malloc(sizeof(fftwf_complex) * (size_t)nfft2);
+ if (!fftout2) {
+ wsprd_stream_emit_error_code("allocation_failed",
+ "unable to allocate streaming inverse FFT output");
+ goto cleanup;
+ }
+ plan_inv = fftwf_plan_dft_1d(nfft2, fftin, fftout2, FFTW_BACKWARD,
+ FFTW_ESTIMATE);
+ if (!plan_inv) {
+ wsprd_stream_emit_error_code("allocation_failed",
+ "unable to create streaming inverse FFT plan");
+ goto cleanup;
+ }
+ fftwf_execute(plan_inv);
+ fftwf_destroy_plan(plan_inv);
+ plan_inv = NULL;
+
+ for (size_t i = 0; i < (size_t)nfft2; i++) {
+ idat[i] = fftout2[i][0] / 1000.0f;
+ qdat[i] = fftout2[i][1] / 1000.0f;
+ }
+ result = (unsigned long)nfft2;
+
+cleanup:
+ if (plan_fwd) fftwf_destroy_plan(plan_fwd);
+ if (plan_inv) fftwf_destroy_plan(plan_inv);
+ if (realin) fftwf_free(realin);
+ if (fftout) fftwf_free(fftout);
+ if (fftin) fftwf_free(fftin);
+ if (fftout2) fftwf_free(fftout2);
+ return result;
+}
+
+// ============================================================
+// Public API (declared in wsprd_stream.h).
+// ============================================================
+
+void wsprd_stream_emit_ready(void) {
+ fputs("{\"v\":1,\"t\":\"ready\",\"modes\":[\"WSPR\"],\"protocol\":1}\n",
+ stdout);
+ fflush(stdout);
+}
+
+// JSON-escape a string into out. Best-effort: handles ASCII printable
+// and the must-escape control chars per RFC 8259.
+static void json_escape_into(const char *src, char *out, size_t out_size) {
+ size_t o = 0;
+ for (const char *p = src; *p && o + 6 < out_size; p++) {
+ unsigned char c = (unsigned char) *p;
+ if (c == '"' || c == '\\') {
+ if (o + 2 < out_size) { out[o++] = '\\'; out[o++] = c; }
+ } else if (c < 0x20) {
+ o += snprintf(out + o, out_size - o, "\\u%04x", c);
+ } else {
+ out[o++] = c;
+ }
+ }
+ out[o] = '\0';
+}
+
+void wsprd_stream_emit_decode(const char *date, const char *uttime,
+ float snr, float dt, double freq,
+ int drift, const char *message) {
+ char esc_msg[80];
+ json_escape_into(message ? message : "", esc_msg, sizeof esc_msg);
+ fprintf(stdout,
+ "{\"v\":1,\"t\":\"decode\",\"mode\":\"WSPR\","
+ "\"date\":\"%s\",\"time\":\"%s\","
+ "\"snr\":%.0f,\"dt\":%.1f,\"freq\":%.6f,"
+ "\"drift\":%d,\"message\":\"%s\"}\n",
+ date ? date : "",
+ uttime ? uttime : "",
+ snr, dt, freq, drift, esc_msg);
+ fflush(stdout);
+}
+
+void wsprd_stream_emit_decode_finished(const char *date, const char *uttime) {
+ fprintf(stdout,
+ "{\"v\":1,\"t\":\"decode_finished\","
+ "\"date\":\"%s\",\"time\":\"%s\"}\n",
+ date ? date : "",
+ uttime ? uttime : "");
+ fflush(stdout);
+}
+
+void wsprd_stream_emit_error(const char *msg) {
+ char esc[256];
+ json_escape_into(msg ? msg : "", esc, sizeof esc);
+ fprintf(stdout, "{\"v\":1,\"t\":\"error\",\"msg\":\"%s\"}\n", esc);
+ fflush(stdout);
+}
+
+void wsprd_stream_emit_error_code(const char *code, const char *detail) {
+ char esc_code[80];
+ char esc_detail[256];
+ json_escape_into(code ? code : "", esc_code, sizeof esc_code);
+ json_escape_into(detail ? detail : "", esc_detail, sizeof esc_detail);
+ fprintf(stdout,
+ "{\"v\":1,\"t\":\"error\",\"code\":\"%s\",\"detail\":\"%s\"}\n",
+ esc_code, esc_detail);
+ fflush(stdout);
+}
+
+// Read header + frames from stdin until configure + enough audio + halt
+// (or audio-exhaustion + EOF) are received. Populates *cfg and the
+// supplied I/Q buffers via FFT/extract/IFFT. Returns nfft2 (number of
+// complex samples populated) on success; 1 on protocol error.
+unsigned long wsprd_stream_read(struct wsprd_stream_config *cfg,
+ float *idat, float *qdat) {
+ set_stdin_binary();
+ if (wsjt_header_read(stdin) != 0) return 1;
+
+ int16_t *pcm = calloc(MAX_PCM_SAMPLES, sizeof(int16_t));
+ if (!pcm) {
+ wsprd_stream_emit_error_code("allocation_failed",
+ "unable to allocate PCM accumulation buffer");
+ return 1;
+ }
+
+ memset(cfg, 0, sizeof *cfg);
+ cfg->wspr_type = 2;
+ int have_date = 0;
+ int have_time = 0;
+ int have_dialfreq = 0;
+ int halted = 0;
+ int wspr_type_value = 0;
+ size_t pcm_n = 0;
+
+ while (!halted) {
+ unsigned char type;
+ void *body = NULL;
+ uint32_t len = 0;
+ int rc = frame_read(stdin, &type, &body, &len);
+ if (rc < 0) {
+ free(pcm);
+ return 1;
+ }
+ if (rc > 0) break; // EOF without halt — treat as drain-and-decode
+
+ if (type == FRAME_CONTROL) {
+ char *json = malloc((size_t)len + 1);
+ if (!json) {
+ free(body);
+ free(pcm);
+ wsprd_stream_emit_error_code("allocation_failed",
+ "unable to allocate control JSON buffer");
+ return 1;
+ }
+ if (len != 0) {
+ memcpy(json, body, len);
+ }
+ json[len] = '\0';
+ free(body);
+
+ char event_type[16];
+ if (json_get_string(json, "t", event_type, sizeof event_type) != 0) {
+ free(json);
+ wsprd_stream_emit_error_code("control_parse_error",
+ "control frame is missing a string t field");
+ continue;
+ }
+ if (strcmp(event_type, "halt") == 0) {
+ halted = 1;
+ free(json);
+ continue;
+ }
+ if (strcmp(event_type, "configure") == 0) {
+ if (json_get_string(json, "date", cfg->date,
+ sizeof cfg->date) == 0) {
+ have_date = 1;
+ }
+ if (json_get_string(json, "time", cfg->uttime,
+ sizeof cfg->uttime) == 0) {
+ have_time = 1;
+ }
+ if (json_get_double(json, "dialfreq", &cfg->dialfreq) == 0) {
+ have_dialfreq = 1;
+ }
+ if (json_find_key(json, "wspr_type")) {
+ if (json_get_int(json, "wspr_type", &wspr_type_value) != 0 ||
+ (wspr_type_value != 2 && wspr_type_value != 15)) {
+ free(json);
+ free(pcm);
+ wsprd_stream_emit_error_code("invalid_wspr_type",
+ "wspr_type must be 2 or 15");
+ return 1;
+ }
+ cfg->wspr_type = wspr_type_value;
+ }
+ json_get_string(json, "mycall", cfg->mycall, sizeof cfg->mycall);
+ json_get_string(json, "mygrid", cfg->mygrid, sizeof cfg->mygrid);
+ cfg->configure_received = 1;
+ }
+ free(json);
+ continue;
+ }
+
+ if (type == FRAME_AUDIO) {
+ // body is raw int16 LE PCM. len must be even (whole samples).
+ if (len % sizeof(int16_t) != 0) {
+ free(body);
+ wsprd_stream_emit_error_code("odd_audio_frame",
+ "audio frame length must contain whole int16 samples");
+ free(pcm);
+ return 1;
+ }
+ size_t nsamples = len / sizeof(int16_t);
+ if (pcm_n + nsamples > MAX_PCM_SAMPLES) {
+ nsamples = MAX_PCM_SAMPLES - pcm_n;
+ }
+ if (nsamples != 0) {
+ memcpy(pcm + pcm_n, body, nsamples * sizeof(int16_t));
+ }
+ pcm_n += nsamples;
+ free(body);
+ continue;
+ }
+
+ // Unknown frame type — ignore (forward-compat).
+ free(body);
+ }
+
+ if (!cfg->configure_received) {
+ free(pcm);
+ wsprd_stream_emit_error_code("missing_configure",
+ "no configure frame received before halt or EOF");
+ return 1;
+ }
+ if (!have_date || !have_time || !have_dialfreq) {
+ free(pcm);
+ wsprd_stream_emit_error_code("incomplete_configure",
+ "configure frame missing date, time, or dialfreq");
+ return 1;
+ }
+
+ unsigned long npoints = pcm_to_iq(pcm, pcm_n, cfg->wspr_type, idat, qdat);
+ free(pcm);
+ return npoints;
+}
diff --git a/lib/wsprd/wsprd_stream.h b/lib/wsprd/wsprd_stream.h
new file mode 100644
index 00000000..0eed120e
--- /dev/null
+++ b/lib/wsprd/wsprd_stream.h
@@ -0,0 +1,33 @@
+/*
+ * wsprd streaming layer — public API consumed by wsprd.c.
+ * See wsprd_stream.c for protocol + scope notes.
+ */
+#ifndef WSPRD_STREAM_H
+#define WSPRD_STREAM_H
+
+struct wsprd_stream_config {
+ char date[7]; // YYMMDD\0
+ char uttime[5]; // HHMM\0
+ double dialfreq; // MHz
+ int wspr_type; // 2 or 15
+ char mycall[13]; // up to 12-char callsign + NUL
+ char mygrid[7]; // up to 6-char grid + NUL
+ int configure_received;
+};
+
+void wsprd_stream_emit_ready(void);
+void wsprd_stream_emit_decode(const char *date, const char *uttime,
+ float snr, float dt, double freq,
+ int drift, const char *message);
+void wsprd_stream_emit_decode_finished(const char *date, const char *uttime);
+void wsprd_stream_emit_error(const char *msg);
+void wsprd_stream_emit_error_code(const char *code, const char *detail);
+
+// Reads WSJT header + frames from stdin until halt or EOF. On success,
+// populates *cfg and the supplied I/Q buffers (idat/qdat must hold
+// at least 46080 floats each). Returns the number of complex samples
+// populated (nfft2 = 46080), or 1 on protocol error.
+unsigned long wsprd_stream_read(struct wsprd_stream_config *cfg,
+ float *idat, float *qdat);
+
+#endif
diff --git a/lib/wsprd/wsprd_utils.c b/lib/wsprd/wsprd_utils.c
index 64e809f8..bd17890d 100644
--- a/lib/wsprd/wsprd_utils.c
+++ b/lib/wsprd/wsprd_utils.c
@@ -27,11 +27,96 @@
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "wsprd_utils.h"
+#include <errno.h>
+#include <stdarg.h>
#ifndef int32_t
#define int32_t int
#endif
+static int format_checked(char *dest, size_t dest_size, char const *format, ...)
+{
+ va_list args;
+ va_start(args, format);
+ int nwritten = vsnprintf(dest, dest_size, format, args);
+ va_end(args);
+ return nwritten >= 0 && (size_t)nwritten < dest_size;
+}
+
+static int read_bounded_token(char const **cursor, char *dest,
+ size_t dest_size, int required)
+{
+ char const *p = *cursor;
+ while( isspace((unsigned char)*p) ) p++;
+
+ if( *p == '\0' ) {
+ if( required ) return 0;
+ dest[0] = '\0';
+ *cursor = p;
+ return 1;
+ }
+
+ char const *start = p;
+ while( *p != '\0' && !isspace((unsigned char)*p) ) p++;
+
+ size_t len = (size_t)(p - start);
+ if( len >= dest_size ) return 0;
+
+ memcpy(dest, start, len);
+ dest[len] = '\0';
+ *cursor = p;
+ return 1;
+}
+
+static int store_hash_call(int ihash, char const *callsign, char *hashtab)
+{
+ if( ihash < 0 || ihash >= WSPRD_HASH_COUNT ) return 0;
+ if( strlen(callsign) >= WSPRD_CALLSIGN_SIZE ) return 0;
+ if( !format_checked(hashtab + ihash * WSPRD_CALLSIGN_SIZE,
+ WSPRD_CALLSIGN_SIZE, "%s", callsign) ) return 0;
+ return 1;
+}
+
+static int store_hash_grid(int ihash, char const *grid, char *loctab)
+{
+ if( ihash < 0 || ihash >= WSPRD_HASH_COUNT ) return 0;
+ if( strlen(grid) >= WSPRD_GRID4_SIZE ) return 0;
+ if( !format_checked(loctab + ihash * WSPRD_GRID4_SIZE,
+ WSPRD_GRID4_SIZE, "%s", grid) ) return 0;
+ return 1;
+}
+
+static int store_hash_entry(int ihash, char const *callsign, char const *grid,
+ char *hashtab, char *loctab)
+{
+ if( !store_hash_call(ihash, callsign, hashtab) ) return 0;
+ if( !store_hash_grid(ihash, grid, loctab) ) return 0;
+ return 1;
+}
+
+int wsprd_load_hash_line(char const *line, char *hashtab, char *loctab)
+{
+ char const *p = line;
+ errno = 0;
+ char *end = NULL;
+ long ihash = strtol(p, &end, 10);
+ if( p == end || errno == ERANGE ||
+ ihash < 0 || ihash >= WSPRD_HASH_COUNT ) return 0;
+ if( !isspace((unsigned char)*end) ) return 0;
+
+ char callsign[WSPRD_CALLSIGN_SIZE];
+ char grid[WSPRD_GRID4_SIZE];
+ p = end;
+ if( !read_bounded_token(&p, callsign, sizeof callsign, 1) ) return 0;
+ if( !read_bounded_token(&p, grid, sizeof grid, 0) ) return 0;
+
+ if( !store_hash_call((int)ihash, callsign, hashtab) ) return 0;
+ /* Legacy loader semantics: missing grid preserves the existing locator. */
+ if( grid[0] != '\0' &&
+ !store_hash_grid((int)ihash, grid, loctab) ) return 0;
+ return 1;
+}
+
void unpack50( signed char *dat, int32_t *n1, int32_t *n2 )
{
int32_t i,i4;
@@ -153,7 +238,7 @@ int unpackpfx( int32_t nprefix, char *call)
int i;
int32_t n;
- strcpy(tmpcall,call);
+ if( !format_checked(tmpcall, sizeof tmpcall, "%s", call) ) return 0;
if( nprefix < 60000 ) {
// add a prefix of 1 to 3 characters
n=nprefix;
@@ -172,31 +257,27 @@ int unpackpfx( int32_t nprefix, char *call)
}
char * p = strrchr(pfx,' ');
- strcpy(call, p ? p + 1 : pfx);
- strncat(call,"/",1);
- strncat(call,tmpcall,strlen(tmpcall));
+ if( !format_checked(call, WSPRD_CALLSIGN_SIZE, "%s/%s",
+ p ? p + 1 : pfx, tmpcall) ) return 0;
} else {
// add a suffix of 1 or 2 characters
nc=nprefix-60000;
if( (nc >= 0) & (nc <= 9) ) {
pfx[0]=nc+48;
- strcpy(call,tmpcall);
- strncat(call,"/",1);
- strncat(call,pfx,1);
+ if( !format_checked(call, WSPRD_CALLSIGN_SIZE, "%s/%.1s",
+ tmpcall, pfx) ) return 0;
}
else if( (nc >= 10) & (nc <= 35) ) {
pfx[0]=nc+55;
- strcpy(call,tmpcall);
- strncat(call,"/",1);
- strncat(call,pfx,1);
+ if( !format_checked(call, WSPRD_CALLSIGN_SIZE, "%s/%.1s",
+ tmpcall, pfx) ) return 0;
}
else if( (nc >= 36) & (nc <= 125) ) {
pfx[0]=(nc-26)/10+48;
pfx[1]=(nc-26)%10+48;
- strcpy(call,tmpcall);
- strncat(call,"/",1);
- strncat(call,pfx,2);
+ if( !format_checked(call, WSPRD_CALLSIGN_SIZE, "%s/%.2s",
+ tmpcall, pfx) ) return 0;
}
else {
return 0;
@@ -243,13 +324,13 @@ int floatcomp(const void* elem1, const void* elem2)
int unpk_(signed char *message, char *hashtab, char *loctab, char *call_loc_pow, char *callsign)
{
int n1,n2,n3,ndbm,ihash,nadd,noprint=0;
- char grid[5],grid6[7],cdbm[4];
+ char grid[WSPRD_GRID4_SIZE],grid6[WSPRD_GRID6_SIZE];
unpack50(message,&n1,&n2);
if( !unpackcall(n1,callsign) ) return 1;
if( !unpackgrid(n2, grid) ) return 1;
int ntype = (n2&127) - 64;
- callsign[12]=0;
+ callsign[WSPRD_CALLSIGN_SIZE - 1]=0;
grid[4]=0;
/*
@@ -269,17 +350,10 @@ int unpk_(signed char *message, char *hashtab, char *loctab, char *call_loc_pow,
int nu=ntype%10;
if( nu == 0 || nu == 3 || nu == 7 ) {
ndbm=ntype;
- memset(call_loc_pow,0,sizeof(char)*23);
- sprintf(cdbm,"%2d",ndbm);
- strncat(call_loc_pow,callsign,strlen(callsign));
- strncat(call_loc_pow," ",1);
- strncat(call_loc_pow,grid,4);
- strncat(call_loc_pow," ",1);
- strncat(call_loc_pow,cdbm,2);
- strncat(call_loc_pow,"\0",1);
+ if( !format_checked(call_loc_pow, WSPRD_MESSAGE_SIZE, "%s %.4s %2d",
+ callsign, grid, ndbm) ) return 1;
ihash=nhash(callsign,strlen(callsign),(uint32_t)146);
- strcpy(hashtab+ihash*13,callsign);
- strcpy(loctab+ihash*5,grid);
+ if( !store_hash_entry(ihash, callsign, grid, hashtab, loctab) ) return 1;
} else {
nadd=nu;
if( nu > 3 ) nadd=nu-3;
@@ -287,25 +361,21 @@ int unpk_(signed char *message, char *hashtab, char *loctab, char *call_loc_pow,
n3=n2/128+32768*(nadd-1);
if( !unpackpfx(n3,callsign) ) return 1;
ndbm=ntype-nadd;
- memset(call_loc_pow,0,sizeof(char)*23);
- sprintf(cdbm,"%2d",ndbm);
- strncat(call_loc_pow,callsign,strlen(callsign));
- strncat(call_loc_pow," ",1);
- strncat(call_loc_pow,cdbm,2);
- strncat(call_loc_pow,"\0",1);
+ if( !format_checked(call_loc_pow, WSPRD_MESSAGE_SIZE, "%s %2d",
+ callsign, ndbm) ) return 1;
int nu=ndbm%10;
if( nu == 0 || nu == 3 || nu == 7 || nu == 10 ) { //make sure power is OK
ihash=nhash(callsign,strlen(callsign),(uint32_t)146);
- strcpy(hashtab+ihash*13,callsign);
+ if( !store_hash_call(ihash, callsign, hashtab) ) return 1;
} else noprint=1;
}
} else if ( ntype < 0 ) {
ndbm=-(ntype+1);
- memset(grid6,0,sizeof(char)*7);
+ memset(grid6,0,sizeof grid6);
// size_t len=strlen(callsign);
size_t len=6;
- strncat(grid6,callsign+len-1,1);
- strncat(grid6,callsign,len-1);
+ if( !format_checked(grid6, sizeof grid6, "%.1s%.*s",
+ callsign+len-1, (int)(len-1), callsign) ) return 1;
int nu=ndbm%10;
if ((nu != 0 && nu != 3 && nu != 7 && nu != 10) ||
!isalpha(grid6[0]) || !isalpha(grid6[1]) ||
@@ -318,19 +388,15 @@ int unpk_(signed char *message, char *hashtab, char *loctab, char *call_loc_pow,
ihash=(n2-ntype-64)/128;
if( strncmp(hashtab+ihash*13,"\0",1) != 0 ) {
- sprintf(callsign,"<%s>",hashtab+ihash*13);
+ if( !format_checked(callsign, WSPRD_CALLSIGN_SIZE, "<%s>",
+ hashtab+ihash*13) ) return 1;
} else {
- sprintf(callsign,"%5s","<...>");
+ if( !format_checked(callsign, WSPRD_CALLSIGN_SIZE, "%5s",
+ "<...>") ) return 1;
}
- memset(call_loc_pow,0,sizeof(char)*23);
- sprintf(cdbm,"%2d",ndbm);
- strncat(call_loc_pow,callsign,strlen(callsign));
- strncat(call_loc_pow," ",1);
- strncat(call_loc_pow,grid6,strlen(grid6));
- strncat(call_loc_pow," ",1);
- strncat(call_loc_pow,cdbm,2);
- strncat(call_loc_pow,"\0",1);
+ if( !format_checked(call_loc_pow, WSPRD_MESSAGE_SIZE, "%s %s %2d",
+ callsign, grid6, ndbm) ) return 1;
// I don't know what to do with these... They show up as "A000AA" grids.
diff --git a/lib/wsprd/wsprd_utils.h b/lib/wsprd/wsprd_utils.h
index db6ba946..62c653e8 100644
--- a/lib/wsprd/wsprd_utils.h
+++ b/lib/wsprd/wsprd_utils.h
@@ -10,6 +10,14 @@
#include <time.h>
#include "nhash.h"
+enum {
+ WSPRD_CALLSIGN_SIZE = 13,
+ WSPRD_GRID4_SIZE = 5,
+ WSPRD_GRID6_SIZE = 7,
+ WSPRD_MESSAGE_SIZE = 23,
+ WSPRD_HASH_COUNT = 32768
+};
+
void unpack50( signed char *dat, int32_t *n1, int32_t *n2 );
int unpackcall( int32_t ncall, char *call );
@@ -26,4 +34,6 @@ int floatcomp(const void* elem1, const void* elem2);
int unpk_( signed char *message, char* hashtab, char* loctab, char *call_loc_pow, char *callsign);
+int wsprd_load_hash_line(char const *line, char *hashtab, char *loctab);
+
#endif
diff --git a/lib/wsprd/wsprsimf.f90 b/lib/wsprd/wsprsimf.f90
index d6ee25d4..8fb2a0d7 100644
--- a/lib/wsprd/wsprsimf.f90
+++ b/lib/wsprd/wsprsimf.f90
@@ -89,7 +89,7 @@ program wsprsim
endif
write(fname14,1100) ifile
1100 format('000000_',i4.4,'.c2')
- open(10,file=fname14,status='unknown',access='stream')
+ open(10,file=fname14,status='replace',access='stream')
fMHz=10.1387d0
nmin=2
write(10) fname14,nmin,fMHz,c !Save to *.c2 file
@@ -102,7 +102,7 @@ program wsprsim
hwav=default_header(12000,NMAX)
write(fname15,1102) ifile
1102 format('000000_',i4.4,'.wav')
- open(10,file=fname15,status='unknown',access='stream')
+ open(10,file=fname15,status='replace',access='stream')
write(10) hwav,iwave !Save to *.wav file
close(10)
write(*,1110) ifile,xdt,f0,snrdb,fname15
diff --git a/lib/xcor.f90 b/lib/xcor.f90
index 83937736..84273b85 100644
--- a/lib/xcor.f90
+++ b/lib/xcor.f90
@@ -13,7 +13,6 @@ subroutine xcor(ipk,nsteps,nsym,lag1,lag2,ccf,ccf0,lagpk,flip,fdot,nrobust)
real a(NSMAX)
! real ccf(-44:118)
real ccf(lag1:lag2)
- data lagmin/0/ !Silence g77 warning
! save
common/sync/ss
@@ -43,6 +42,8 @@ subroutine xcor(ipk,nsteps,nsym,lag1,lag2,ccf,ccf0,lagpk,flip,fdot,nrobust)
ccfmax=0.
ccfmin=0.
+ lagpk=lag1
+ lagmin=lag1
do lag=lag1,lag2
x=0.
do i=1,nsym