!MS3-RC-Workout.f95
!2025.01.25.1440cst JMS- Sequence->Emulator->Results
!                      - Generates a lookup table
!              Computer- "T4"/HP-800-G4-Mini/i7-8700T/IntelUHD630/Win10Pro-22H2
!                         ^name  ^Mfgr.Id    ^chipset ^graphics   ^OS
!                            /AbsoftProFortran 21.0.2/OpenGL+Glut3.6
!                             ^compiler               ^Fortran graphics
!
!Table of Contents - ToC:
!Subroutine MinStepSolver(iP)                      -Lookup tables generator
!                                                  -opens many files
!Subroutine BitLog(ModeF1R2,n8,nNewout,iP)         -Results (huge) indexer
!Subroutine ReadYourNml(EnvNml,Ur,Us,Ut,cOutFile)  -opens 'MS3.ini' & EnvNml
!                                       ...called by MS1Launch at the outset.
!Subroutine ImportEin(iP)                          -internalizes .nml data
!                                       ...and branches to apps via %iType.
!Subroutine PrintErec(Ein,iP,Label)                -view Emulator setup
!Subroutine PrintSRrec(SortL,iP,Label)             -view a Sequence-or-Result
!---------------------------------------------------------------------------7 9

Subroutine MinStepSolver(iP)
!2025.01.19.0925cst JMS- the Minimum Step Solver for Rubik's Cubes,
!                        exercising: EmulatorRC() & IndexerRC() 
!--Globals
 use MS1Def   ,only: Ur,Us,Ut,Uread1,Uwrite1,Uwrite2,Urdwr,RunSecs                                !i/o units
 use MS2RCDef ,only: cTitle,RubSize,iType,cFileOut,cLuTOut,EnvNml  & !housekeep
                    ,Mmax,Ctot,C,nS8,Vtot,V,Vtotshow,VA,cVAtest    & !Sequences
                    ,H8 ,nRaccum8,Rtot8,SRrec,resetSR,Srseed,RV    & !& Results
                    ,Sr1,Srn,Srbase,Srtry,Stried8,Sfound8,RVbase   &
                    ,nSeqs,nSeqPrev,nSeqPres                       &
                    ,Ein                                           & !inputs
                    ,Csymbol,Asymbol                                 !symbology

!use RuBbMod !,only: _______    !:use/modify module variables    JMS 2023.07.14
!--End Globals
 implicit none
 !--Arguments
  integer(4)::iP          !Write enable>5: write(iP,...)
 !--Internals
 type(SRrec)::Srtest      !Ein is transcribed to SrTest
  integer(4)::Init
  integer(4)::i,iii,n
 !integer(4)::iAlloc      !Array allocation flag =0:success
  integer(4)::nSe
  character(22)::Datime22L
  integer(4)::nin         !Recursion Level index- `called by level
  integer(8)::H8a,Indexer
  integer(4)::nNew        !=1:new, =-1:not new
  integer(8)::nMprev
  integer(4)::nC
  integer(4)::valid       !=0:invalid; =nCin:valid
  integer(8)::n8,n8fnd,nS8H8 ,nBeam8
  integer(4)::Vtotl
  character(42)::cLabel42 

  real(8)   ::rRate1,rRate2,rTime1,rTime2
  real(8)   ::RunSecs01,RunSecs10,RSecs0010(2,-1:40)
  integer(1)::Zero1  = 0
  integer(1)::Minus1 = -1
  integer(4)::nZ
  !--EndDefs-----------------------------------------------

   if(Init==0) then

     write(Us,"('ReadYourNml(): reading ',:,79a1)") &
                             (EnvNml(i:i),i=1,len_trim(EnvNml))
     do i = 1,8; Ein%cVAtest(i:i) = char(Asymbol(Ein%VA(i))); enddo!i                                                                                                             
       call PrintErec(Ein,Us,'MinStepSolver: Ein% inputs')
     if(iP>5) then
       call PrintErec(Ein,iP,'MinStepSolver: Ein% inputs')

      !--Internalize the variables in the Ein record:
       cTitle    = Ein%cTitle
       cFileOut  = Ein%cSummaryOut
       cLuTOut   = Ein%cRrAsciiOut
       iType     = Ein%iType
       RubSize   = Ein%RubSize
       Vtot      = Ein%Vtot      !Voters - total
       V         = 0
       cVAtest   = Ein%cVAtest
       V(1:Vtot) = Ein%V(1:Vtot) !Voter(s) | cells          in use
       Ctot      = Ein%Ctot      !Choices- total
       C         = 0
       C(1:Ctot) = Ein%C(1:Ctot) !Choices  | face rotations in use
       Mmax      = Ein%Mmax
       Vtotshow  = Ein%Vtotshow
         !--Define Srtest
       Srtest = resetSR  !clears the Srtest record
       Srtest%nS8      =       0_8 
       Srtest%H8       =       0_8 !undefined

       Srtest%Mused    = Ein%Mtotvis
       Srtest%MC(1:30) = Ein%MCvis(1:30)
       Srtest%Vtot     = Ein%Vtot
              Vtotl    = Ein%Vtot 
       Srtest%cVAsymb(1:VtotL)  = Ein%cVAtest(1:VtotL) 
       Srtest%VA(     1:VtotL)  = Ein%VA(     1:VtotL)

      !--Zero the Sequences and Results counters;
       H8  = 0_8 
     endif!(iP>5)
     call SaveOutFile
     Init = 1
   endif!(Init==0)

  !Seed the Min-Steps Generator:
             nSeqPrev  =    0
   nSeqs(1:4,nSeqPrev) = (/ 0, 1, 1, 1 /) !(nSeq|n1st|nLast|count,Sequence#)

     Srseed                = resetSr
     Srseed%nS8            = 1_8
     Srseed%Vtot           = Vtot
     Srseed%VA             =-1
     Srseed%cVAsymb        = ' '
   do i = 1,Vtot
     Srseed%VA(i)          = 1
     Srseed%cVAsymb(i:i)   = char(Asymbol(1))  !='a'
   enddo!i
     Srseed%Mused          = 0
     Srseed%MC(1:30)       = (/ 0, (-1,iii=1,29) /) !-1:undefined
            Stried8        = 1_8
            Sfound8        = 1_8
     Srseed%H8             = 1_8

     Srseed%MC(2:(Srseed%Vtot+1)) = V(1:Vtot)
     Srseed%MC(   29            ) = Ctot

                 nin = 0
   H8a  = Indexer(nin,Srseed,iP) !,iP)  <- print Indexer()'s setup here

   if(iP>5) then
     write(iP,"(' n, RVbase(n)%nAloc(1:24):')")
     write(iP,"( 5x,'a  b  c  d  e  f  g  h  i  j  k  l  m  n  o  p  q  r',\)")
     write(iP,"(  '  s  t  u  v  w  x')")
     do n = 1,Ein%Vtot
       write(iP,"(i2,': ',i2, 23(',',i2) )")  &
                         n,   (RVbase(n)%nAloc(i),i=1,24)
     enddo!n
     write(iP,*)
   endif!(iP>5)

                            Srseed%H8    = H8    != H8a too
                                   Rtot8 = nRaccum8
   if(iP>5) call PrintSRrec(Srseed,iP,'MinStepSolver: Srseed% results @L146:')
   if(iP>6) call SaveOutFile

                             nNew = 0   !------------------
  !call BitLog(ModeF1R2,n8        ,nNew,iP) !F1R2:1=Find,2=Report,3=dealloc.
   call BitLog(       1,Srseed%H8 ,nNew, 0)
   if(iP>5) write(iP,*)
   call PrintSRrec(     Srseed,iP,'MinStepSolver @L153: Srseed%')
   nS8 = 1_8
                 nin = 0
   H8a  = Indexer(nin,Srseed, 0)   ! |||||||||||||||||||||||
   call SaveOutFile

  !--Set up Sr() as a direct access file:      2024.08.22
    !To screen:                          
     write( 6,"(/'Set up Sr as a direct access file:  Unit=',i2)") Urdwr
     call nRunSec(-10,RunSecs10, 6)
     write( 6,"('nRaccum8         =',i25         )") nRaccum8 
     write( 6,"('c_sizeof(Srtry)  =',i25         )")          c_sizeof(Srtry)
     write( 6,"('Sr.bim filesize <=',i26         )") nRaccum8*c_sizeof(Srtry)
   if(iP>6) then
    !To file:
     write(iP,"(/'Set up Sr as a direct access file:  Unit=',i2)") Urdwr
     call nRunSec(-10,RunSecs10,iP)
     write(iP,"('nRaccum8         =',i25         )") nRaccum8 
     write(iP,"('c_sizeof(Srtry)  =',i25         )")          c_sizeof(Srtry)
     write(iP,"('Sr.bim filesize <=',i25         )") nRaccum8*c_sizeof(Srtry)
     if(nRaccum8*c_sizeof(Srtry)<0) then
       write(iP,"(/'Sr.bim filesize <0: is unopenable, @L174, Will halt.')")
       call SaveOutFile
     endif!(nRaccum8*c_sizeof(Srtry)<0)  
   endif!(iP>6)
   if(nRaccum8*c_sizeof(Srtry)<0) stop 'Sr.bim is unopenable when <0, @L178.'

   open(Urdwr, file=Ein%cSrBinary, action='readwrite' &   !-> 88 bytes/record
              , access='direct'    , recl  = C_SIZEOF(Srtry), status='replace')

   Sr1       = Srseed
   write(Urdwr,rec = 1_8) Sr1 

   Srbase    = resetSr
   Srn       = resetSr

  !Initialize the clocks:   
   RSecs0010 = 0.d0
   call nRunSec( -1,RunSecs01, 0); RSecs0010(1,-1) = RunSecs01
   rRate1 = 30000.d0
   rRate2 = 30000.d0

   if(iP>5) write(iP, &
    "(/17x,'***** MinStepSolver() @L196: commencing loop... *****'/)") !~~~~~~

  !--Top of the Min-Step Solver loop:
10 continue
   nSeqPres = nSeqPrev+1
  !Update the clocks
          call nRunSec( +1,RunSecs01, 0) 
   RSecs0010(1,nSeqPrev) = RunSecs01
   RSecs0010(2,nSeqPrev) = RSecs0010(1,nSeqPrev)-RSecs0010(1,nSeqPrev-1)

   if(nSeqPrev>1) then
    !Update the rate & time approximations:
    !Cumulative performance:
     if((     nSeqs(3,nSeqPrev  )>0_8).and.(   Rsecs0010(1,nSeqPrev)>0.d0)) &
     rRate1 = nSeqs(3,nSeqPrev  )       /      Rsecs0010(1,nSeqPrev)
     rTime1 = nRaccum8                  /      rRate1
    !nSeq = _ performance:
     if((     nSeqs(4,nSeqPrev-1)>0_8).and.(   Rsecs0010(2,nSeqPrev)>0.d0)) &
     rRate2 = nSeqs(4,nSeqPrev-1)       /      Rsecs0010(2,nSeqPrev) 
     rTime2 = nSeqs(4,nSeqPrev  )       /      rRate2

  !--Output to screen:
     write( 6, &
   "(/' nSeq,      n1st,      nLast,      count',14x,'Level    <sec>      Run')")
     do nSe = 0,nSeqPrev
                        write(6,"(i4,3i12,2f19.3)")      &
                         nSeqs(1:4,nSe),Rsecs0010(2,nSe) &
                                       ,Rsecs0010(1,nSe) &
                                      - Rsecs0010(1,  0)
     enddo!nSe
     write( 6,"(/i4,6x,i18,f16.3,'/sec      est.=',f19.3)")  &
          nSeqPrev+1, nSeqs(4,nSeqPrev),rRate2,rTime2
     write( 6,"( 7x,'if real:',i13,f16.3,'/sec      est.=',f19.3)")  &
                      nRaccum8         ,rRate1,rTime1
       call jdate22(DaTime22L)
       write( 6,"(56x,a22)") DaTime22L

     if(iP>6) then
      !--Output to file:
       write(iP, &
   "(/'nSeq,       n1st,      nLast,      count',14x,'Level    <sec>     Run')")
       do nSe = 0,nSeqPrev
                           write(iP,"(i4,3i12,2f19.3)")     &
                            nSeqs(1:4,nSe),Rsecs0010(2,nSe) &
                                          ,Rsecs0010(1,nSe) &
                                         - Rsecs0010(1,  0)
       enddo!nSe              
       write(iP,"(/i4,6x,i18,f16.3,'/sec      est.=',f19.3)")  &
            nSeqPrev+1, nSeqs(4,nSeqPrev),rRate2,rTime2
       write(iP,"( 7x,'if real:',i13,f16.3,'/sec      est.=',f19.3)")  &
                            nRaccum8,rRate1,                 rTime1              
       write(iP,"(56x,a22)") DaTime22L
       call SaveOutFile
     endif!(iP>6)
   endif!(nSeqPrev>1)

   if(nSeqPres>Ein%Mmax) then
     if(iP>6) write(iP,"(/'@L253: Exceeded Ein%Mmax. Reporting results...')")
     goto 90
   endif!(nSeqPres>Ein%Mmax)

   if(nSeqs(4,nSeqPrev)== 0) goto 90

  !--Time the next level
   call nRunSec(-10,RunSecs10, 0)
   call jdate22(DaTime22L)

  !--The outer loop of the core process: 
  !  Testing each previously valid Sr()'s:
   do nMprev = nSeqs(2,nSeqPrev),nSeqs(3,nSeqPrev)

    !if(nSeqPrev>6) then
     if(nSeqs(4,nSeqPrev)>80) then
                   nBeam8 = nMprev+1_8-nSeqs(2,nSeqPrev)
       if(mod(     nBeam8,nSeqs(4,nSeqPrev)/80)==1_8) &
       call Beamer(nBeam8,nSeqs(4,nSeqPrev))
     endif!(nSeqPrev>5)
     read(Urdwr,rec = nMprev) Srbase

    !--The inner loop of the core process: 
    !  Evaluate SrBase using all possible move Choices:   
     do nC = 1,Ctot
      !--Excercise the system:
       call EmulatorRC(Srbase,nC,Srtry,valid, 0) !iP)
       Stried8 = Stried8 +1_8
                   nin = 0
      !--Compute H8  (the index#) for the resulting set of Attitudes:
       H8a  = Indexer(nin,Srtry, 0)      

      !--Determine if Srtry%H8  is novel or known:
       call BitLog(     1  ,Srtry%H8 ,nNew, 0) !,iP)

      !--If Srtry is new- append it to the list of Sr()'s 
       if(nNew==1) then 
               Sfound8  = Sfound8+1_8
         Srtry%nS8      = Sfound8 
        !Sr(   Sfound8) = Srtry
         write(Urdwr,rec = Sfound8) Srtry 
         call PrintSRrec(Srtry, 0,'MinStepSolver@L294: saved:')
        else
         call PrintSRrec(SRtry, 0,'MinStepSolver@L296: discarded:')
       endif!(nNew==1)
     enddo!nC  
   enddo!nMprev

  !--Update the sequence table:
   call SaveOutFile
   if(Sfound8>nSeqs(3,nSeqPrev)) then
     nSeqs(1,nSeqPres) = nSeqPres
     nSeqs(2,nSeqPres) = nSeqs(3,nSeqPrev)+1
     nSeqs(3,nSeqPres) = Sfound8
     nSeqs(4,nSeqPres) = Sfound8-nSeqs(3,nSeqPrev)
     nSeqPrev = nSeqPres
     goto 10     !This is the bottom of the MinStepSolver loop.
   endif!(nSortsTot>nSeqs(3,nSeqPrev))

   write( 6,"(/'@L312: Novel Results exhausted; drop through.')")

 !-------------------------------------

 !--The search for novel Sr()'s is done, and Sr()%H8  values are defined.
90 continue

   write( 6,"('90 @L320:: will deallocate BitLog...')")
   call BitLog(       3,1000002_8,nNew,iP)  !Close BitLog
   close(Urdwr) !This saves all of Ein%cSrBinary to disk

  !--Complete Ein Zone update and export Ein as a binary file:
   Ein%Einsize           = sizeof(Ein)
   Ein%Zonebimsize       = nRaccum8
   Ein%ZoneFound         = Sfound8
       nZ                = Ein%nZ
   if( nZ>0) then
     Ein%cZrFilename(nZ) = Ein%cRrtoDisBinary
     Ein%Vsizez          = 0
     do n=1,VtotL
       Ein%Vsizez(n)     = RV(n)%nAavail        
     enddo!n
   endif!nZ>0
   Ein%Mtot              = nSeqPrev

   call PrintErec(Ein,iP,'MinStepSolver @L340: Ein% output')

   write( 6,"('Export the -Ein.bim file:')")
   if(iP>6) &
   write(iP,"('Export the -Ein.bim file:')")
   open(Uwrite1, file=Ein%cEinBinary, action='write'              &
               , access='direct'       , recl = sizeof(Ein)   , status='replace' )
       write(Uwrite1,rec=1 ) Ein
   close(Uwrite1)
   if(iP>6) then
     write(iP,"('Population of -Ein.bim:    completed.')")
     call nRunSec(+10,RunSecs10,iP)
     call nRunSec(  0,RunSecs  ,iP)
     call SaveOutFile
   endif!(iP>6)

   open(Urdwr, file=Ein%cSrBinary, action='read' &   !-> 88 bytes/record
              , access='direct'    , recl  = C_SIZEOF(Srtry), status='old')
  !--Export the results in various ways
   write(6,"(/'The first three Sr() records are:')")
   do n8 = 1_8,3_8
     write(cLabel42,"('MinStepSolver @L362: Sr(',i1,'):')") n8
     read(Urdwr,rec = n8) Srn 
     call PrintSRrec(Srn, 6,cLabel42) ;write(6,*)
     if(iP>6) then
       call PrintSRrec(Srn,iP,cLabel42)
       call SaveOutFile
       write(iP,*)
     endif!(iP>6)
   enddo!n8
   write(6,"(/'The last three Sr() records are:')")
   do n8 = Sfound8-2_8,Sfound8
     write(cLabel42,"('MinStepSolver @L373: Sr(',i15,'):')") n8
     read(Urdwr,rec = n8,err=91) Srn 
     call PrintSRrec(Srn, 6,cLabel42) ;write(6,*)
     if(iP>6) then
       call PrintSRrec(Srn,iP,cLabel42)
       call SaveOutFile
       write(iP,*)
     endif!(iP>6)
   enddo!n8

   goto 92                                             !cLabel42 was too short.
91 pause 'Error MS3-RC-Workout.f95@L384: Exporting the last 3 records.'
92 continue

  !--Export the Rr Binary Cross Reference to Sr:
   if(iP>5) then
     write(iP,"(/'Export the -RrtoSr.bim file:')")
     call nRunSec(-10,RunSecs10,iP)
     write(iP,"('nRaccum8  (clear)     =',i12)") nRaccum8
     write(iP,"('    if @78654.469/sec =',f16.3,' sec')") nRaccum8/78654.469_8
     write(iP,"('Sfound8   (write)     =',i12)") Sfound8 
     write(iP,"('    if @72208.006/sec =',f16.3,' sec')") Sfound8/72208.006_8
     write(iP,"(' ^ sum                =',f16.3,' sec')") &
                                     nRaccum8/78654.469_8+Sfound8/72208.006_8
     write(iP,"('Rr-to-Sr.bim filesize =',i12,' bytes')") nRaccum8*8_8 
     call SaveOutFile
   endif!(iP>5)                          
     write( 6,"(/'Export the -RrtoSr.bim file:')")
     call nRunSec(-10,RunSecs10, 6)
     write( 6,"('nRaccum8  (clear)     =',i12)") nRaccum8
     write( 6,"('    if @78654.469/sec =',f16.3,' sec')") nRaccum8/78654.469_8
     write( 6,"('Sfound8   (write)     =',i12)") Sfound8 
     write( 6,"('    if @72208.006/sec =',f16.3,' sec')") Sfound8/72208.006_8
     write( 6,"(' ^ sum                =',f16.3,' sec')") &
                                     nRaccum8/78654.469_8+Sfound8/72208.006_8

  !Open & initialize the file:
   write( 6,"('Clear the -RrtoSr.bim file:')")
   if(iP>6) &
   write(iP,"('Clear the -RrtoSr.bim file:')")
   open(Uwrite1, file=Ein%cRrtoSrBinary, action='write'                  &
               , access='direct'       , recl = 8      , status='replace' )
          ! write(12,rec= 1) 1
     do n8 = 1,nRaccum8
       if(mod(n8,5000_8)==1_8) call Beamer(n8,nRaccum8)
       write(Uwrite1,rec=n8) 0_8
     enddo!n8
     write(6,*)
   close(Uwrite1)
            call nRunSec(+10,RunSecs10,06)
            call nRunSec(  0,RunSecs  ,06)
   if(iP>5 )write(iP,"('Initializing Rr-to-Sr.bim:     completed')")
   if(iP>5) call nRunSec(+10,RunSecs10,iP)
   call SaveOutFile

  !Reopen & write the file:
   write( 6,"('Populate the -RrtoSr.bim file:')")
   if(iP>6) &
   write(iP,"('Populate the -RrtoSr.bim file:')")
   open(Uwrite1, file=Ein%cRrtoSrBinary, action='readwrite'              &
               , access='direct'       , recl = 8          , status='old' )
     do n8 = 1,Sfound8
       if(mod(n8,5000_8)==1_8) call Beamer(n8,Sfound8)
       read(Urdwr,rec = n8) Srn
       write(Uwrite1,rec=Srn%H8 ) Srn%nS8
     enddo!n8
     write(6,*)
   close(Uwrite1)
   if(iP>6) then
     write(iP,"('Population of Rr-to-Sr.bim:    completed.')")
     call nRunSec(+10,RunSecs10,iP)
     call nRunSec(  0,RunSecs  ,iP)
     call SaveOutFile
   endif!(iP>6)
   call nRunSec(+10,RunSecs10, 6)
   call nRunSec(  0,RunSecs  , 6)

  !--Export Sr as Text :
     write( 6, &
      "(/'Export Rr(1:Sfound8) (founds only) as -RrAscii.txt (<= 4.e6)')")
     write( 6,"('& Export the -RrToDis.bim file:')")
     write( 6,"('-RrToDis.bim filesize  =',i12,' bytes')") nRaccum8
     call nRunSec(-10,RunSecs10, 6)
   if(iP>6) then
     write(iP, &
      "(/'Export Rr(1:Sfound8) (founds only) as -RrAscii.txt (<= 4.e6)')")
     write(iP,"('& Export the -RrToDis.bim file:')")
     write(iP,"('-RrToDis.bim filesize  =',i12,' bytes')") nRaccum8
     call nRunSec(-10,RunSecs10,iP)
     call SaveOutFile
   endif!(iP>6)

  !--Export the -RrtoSr.bim & -RrtoDis.bim file:

   open(Uread1   , file=Ein%cRrtoSrBinary , action='read'   &
                 , access='direct'        , recl = 8      , status='old'  )

     open(UWrite1, file=Ein%cRrAsciiOut   , action='write', status='replace')

     open(UWrite2, file=Ein%cRrtoDisBinary, action='write'  & 
                 , access= 'direct'       , recl = 1      , status='replace')

                 n8fnd = 0_8 
      !Write the file header:
       write(UWrite1,"(:,79a1)") &
            (Ein%cRrAsciiOut(i:i),i=1,len_trim(Ein%cRrAsciiOut))
       write(UWrite1,"(2i3,'    ',\)") &
           RubSize,Vtot
       do i = 1,Vtot
         write(UWrite1,"(i3,\)") V(i)
       enddo!i
       write(UWrite1,"('  RubSize, Vtot, V(1:Vtot)')")
       write(UWrite1,"(i11,i21,i3,'  Rtot,Stot,Mtot')") &
                       nRaccum8,Sfound8,nSeqPrev
      !------------------------------
           n8fnd = 0_8 
       do n8 = 1,nRaccum8
         if(mod(n8,5000_8)==1_8) call Beamer(n8,nRaccum8)
         read(Uread1,rec=n8) nS8H8 
         if(nS8H8 ==0_8) then
           write(Uwrite2,rec = n8        ) Minus1 ! -RrToDis.bim
          else                                    !   = -1 implies undefined -&-
           n8fnd = n8fnd +1_8                     !   =  0 implies solved
           read( Urdwr  ,rec = nS8H8 ) Srn

           if(n8<10_8) then
             write(cLabel42,"('MinStepSolver @L502: Sr(',i10,'):')") nS8H8
             call PrintSRrec(Srn,iP,cLabel42)
             write(iP,*)
           endif!(n8<10_8)

           write(Uwrite2,rec = n8 ) Srn%Mused !-RrToDis.bim  2024.11.21

           if(n8fnd>4000000_8) cycle  !Supports 2by:3674160 
           write(UWrite1,"(i11,1x,a12,1x,i11,1x,i2,1x,:,22(1x,a1))") &
                             Srn%H8                                  &
                            ,Srn%cVAsymb                & ! Up to 12 print out.
                            ,Srn%nS8                    &
                            ,Srn%Mused                  &
                   ,(Csymbol(Srn%MC(i)),i=1,Srn%Mused)    ! first 20 fit inside
         endif!(nS8H8 ==0_8)                              ! 80-column printout.
       enddo!n8
       call SaveOutFile

       write(6,*)
      !------------------------------
       write(Uwrite1, &
   "(/'nSeq,      n1st,     nLast,     count',15x,'Level    <sec>       Run')")
       do nSe = 0,nSeqPrev
         write(Uwrite1,"(i4,3i11,2f20.3)")      &
         nSeqs(1:4,nSe),  Rsecs0010(2,nSe) &
                       ,  Rsecs0010(1,nSe) &
                        - Rsecs0010(1,  0)
       enddo!nSe
       Write(Uwrite1, &
       "('     Allocated:',i11,'   ...Rr()`s address space size')") nRaccum8
       write(Uwrite1, &
       "(/'Export Rr(1:Sfound8) (founds only), in found order, completed.')")
       call nRunSec(+10,RunSecs10,UWrite1)
       call nRunSec(  0,RunSecs  ,UWrite1)
       call jdate22(DaTime22L)
       write(UWrite1,"(a22)") DaTime22L
     close(Uwrite1) !-RrASCII.txt
     close(Uwrite2) !-RrToDis.bim
   close(Uread1)    !-RrtoSr.bim

   close(Urdwr)     !-Sr.bim

     write( 6,"('Export Rr(1:Sfound8) & RrToDis completed.  iP =',i3)") iP
     call nRunSec(+10,RunSecs10, 6)
     call nRunSec(  0,RunSecs  , 6)
   if(iP>6) then
     write(iP,"('Export Rr(1:Sfound8) & RrToDis completed.  iP =',i3)") iP
     call nRunSec(+10,RunSecs10,iP)
     call nRunSec(  0,RunSecs  ,iP)
     call SaveOutFile
   endif!(IP>6)
                                                                         return
End Subroutine MinStepSolver
!---------------------------------------------------------------------------7 9

Subroutine BitLog(ModeF1R2,n8,nNewout,iP)
!2024.08.22.0920cdt JMS- Using bits to track "used`s". <= 30 billion
!--Globals 
!--End Globals
 implicit none
 !--Arguments
  integer(4)  ::ModeF1R2 !=1:fill, =2:read; Any other values deallocate & reset
  integer(8)  ::n8       !number to evaluate
  integer(4)  ::nNewout  !=1:new, =-1:not new
  integer(4)  ::iP       !Write enable>5: write(iP,...)
 !--Internals
  integer(8),allocatable  ::nArray8(:) !( 500000000_8)  !use 60 of the <-63 bits
                     !=   500,000,000  =   ~4 billion bytes (~8 bits/byte)
                     !                     &  60 bytes per integer(8)
                     != 30,000,000,000  = 30 billion indices 
  integer(8)  ::n8max = 30000000000_8
                     != 
                     != 30,000,000,000 != 30 billion indices
  integer(4)  ::Init,nNew
  integer(8)  ::i8,j8,Bit8,nSum8
  !--EndDefs-----------------------------------------------
   if(Init==0) then
     allocate(nArray8(500000000_8))  
        !allocation avoids an 80,000,000 bytes compiler limit.
     nArray8 = 0_8
     nSum8   = 0_8
     Init    = 1
   endif!(Init==0)

   if((n8<1).or.(n8>n8max)) then
     call SaveOutFile
     if(n8<   1_8) pause 'BitLog @L588: n8< 1, will halt.' 
     if(n8<   1_8) stop 
     if(n8>=n8max) pause 'BitLog @L590: n8>=n8max, will halt.' 
     if(n8>=n8max) stop 
   endif!((n8<1).or.(nL>n8max))

  !--Check for previous use:
   i8   = ( n8 - 1_8 ) / 60_8 + 1_8
   Bit8 = n8 - ( i8 - 1_8 ) * 60_8
   j8   = nArray8(i8)
                      nNew    =  1                
   if(Btest(j8,Bit8)) nNew    = -1
                      nNewout = nNew
   select case(ModeF1R2)
    case(1) !Fill
     if(nNew==1) then; j8 = iBset(j8,Bit8) 
       nArray8(i8) =   j8
       nSum8 = nSum8+1_8
       if(iP<6)                                                          return
       if(nSum8==1_8) &
       write(iP,"(/'BitLog:                    Count   nNew')")
       write(iP,"('n8=',i12,' --> ',i12,i6,'  bit set')") n8,nSum8,nNew
      else
       if(iP>5) & 
       write(iP,"('n8=',i12,' old',13x,i6)") n8,nNew
     endif!(nNew==1)
    case(2) !Read
     if(iP<6)                                                            return
     if(nNew==1) then
       write(iP,"('n8=',i12,' free',12x,i6)") n8,nNew
      else 
       write(iP,"('n8=',i12,' used',12x,i6)") n8,nNew
     endif!(nNew==1)
    case default !Deallocate, reset, and un-initialize:
     if(iP>5) write(iP,"( 'BitLog: nSum8     = ',i12,'  clearing...')") nSum8
     if(allocated(nArray8)) then
       if(iP>5) write(iP,"('        deallocating nArray8.')")
       deallocate(narray8)
     endif!(allocated(nArray8))     
     nSum8   = 0_8
     Init    = 0             
   end select!(ModeF1R2)
                                                                         return
End Subroutine BitLog
!Example usage: 2024.07.24.1636
!    call BitLog(1,1000001_8,nNew,iP)   !<-Find
!    call BitLog(1,1000001_8,nNew,iP)   !<-Find
!    call BitLog(2,1000001_8,nNew,iP)   !<-Report
!    call BitLog(2,1000002_8,nNew,iP)   !<-Report
!    call BitLog(3,1000002_8,nNew,iP)   !<-Deallocate nArray8(:)
!--------
!BitLog:                    Count
!n8=     1000001 -->            1
!n8=     1000001 old
!n8=     1000001 used
!n8=     1000002 free
!BitLog: nSum8     =            1     Reset:
!       deallocating nArray8. 
!---------------------------------------------------------------------------7 9

Subroutine ReadYourNml(EnvNml,Ur,Us,Ut,cOutFile)
!2025.01.19.0835cdt JMS- Reading "MS3.ini" to identify & read  *.nml 
!--Globals
 use MS2RCDef, only: Ein               
!--End Globals
 implicit none
 !--Arguments          !These variables are in MS1Def:
  character*79::EnvNml !  but are not "used" herein.
  integer(4)  ::Ur 
  integer(4)  ::Us 
  integer(4)  ::Ut
  character*79::cOutFile
 !--Internals
  integer(4)::i
  logical   ::LExists         !File existence flag
  integer(4)::Utin

 NAMELIST / NnNml /  Utin,Ein

   !--EndDefs-----------------------------------------------
!  Modifying key variables at runtime using NameList file `Sn.nml`:
!  Initial defaults are set here:
   EnvNml   = 'MS-RC-R3-Scrambler.nml' !which specifies "NmNml"
   Ut       =   6                      !Output unit#: Set to 6 or 13
   cOutFile = '.\R3-Scrambler-Summary.txt'

   write(Us,"('ReadYourNml(): reading `MS3.ini` file to ID the *.nml file')")
   inquire(file = 'MS3.ini', exist = LExists)
   if(LExists)then
     open( unit=Ur, file  ='MS3.ini'   , action='read'      &
                  , access='sequential', status='old' ,err=4 )
       read(Ur,*,err=4) EnvNml
     close(Ur); goto 5
4    pause "Error reading `MS3.ini` file. Press enter to continue."
     close(Ur)
    else
     write(Us,"('ReadYourNml(): Didn`t find `MS3.ini` @L680.')")
   endif!LExists
5  continue

  write(uS,*) EnvNml

  !Sn.nml Ein record listing: SER-Rubik-Def.f95 @L690+.
   write(Us,"('ReadYourNml(): reading ',:,79a1)") &
                           (EnvNml(i:i),i=1,len_trim(EnvNml))
   inquire(file=EnvNml,exist=LExists)
   if(LExists)then
     open( unit=Ur, file=EnvNml        , action='read'    &
                  , access='sequential', status='old' ,err=9)
       read(Ur,nml=NnNml,err=8)        !<--Defined above
     close(Ur); goto 10
8    pause "Error reading  NnNml @L699. Press enter to continue."
     close(Ur); goto 10     
9    pause "Error opening `NnNml.nml` file @L701. Press enter to continue."
     close(Ur)
    else
     write(Us,"('ReadYourNml(): Didn`t find `EnvNml` @L704.')")
   endif!LExists
10 continue
   Ein%cSummaryOut   = Ein%NameRoot(1:len_trim(Ein%NameRoot))//"-Summary.txt"
   
   Ein%cRrAsciiOut   =Ein%NameRoot(1:len_trim(Ein%NameRoot))//"-RrAscii.txt"
   Ein%cSrBinary     =Ein%NameRoot(1:len_trim(Ein%NameRoot))//"-Sr.bim"
   Ein%cRrtoSrBinary =Ein%NameRoot(1:len_trim(Ein%NameRoot))//"-RrtoSr.bim"
   Ein%cEinBinary    =Ein%NameRoot(1:len_trim(Ein%NameRoot))//"-Ein.bim"
   Ein%cRrtoDisBinary=Ein%NameRoot(1:len_trim(Ein%NameRoot))//"-RrToDis.bim"

   Ut       = UtIn
   cOutFile = Ein%cSummaryOut
   write(Us,"(/'ReadYourNml() - done. ',10('|'))")
                                                                        ;return
End Subroutine ReadYourNml
!---------------------------------------------------------------------------7 9

Subroutine ImportEin(iP)
!2025.01.10.1830cst JMS- Generates an Sr record based on:
!                        Ein %MtotVis,%mCvis(0:__), & %Vtotshow
!--Globals
 use MS1Def   ,only: Ur,Us,Ut
 use MS2RCDef ,only: cTitle,RubSize,iType,cFileOut,cLuTOut,EnvNml  & !housekeep
                    ,Mmax,Mtot,Ctot,C,nS8                          & !Moves
                    ,Stried8,Sfound8,Vtot,V,Vtotshow,VA,cVAtest    & !Voters
                    ,H8 ,nRaccum8,Rtot8,SRrec,resetSR,Srseed       & !Sequences
                    ,Sr1,Srtry,Srbase,Srn,SrTestIn,RVbase          & !& Results
                    ,nSeqs,nSeqPrev,nSeqPres                       &
                    ,Ein                                           & !input
                    ,Csymbol,Asymbol                                 !symbology
!--End Globals
 implicit none
 !--Arguments
  integer(4)::iP         !Write enable>5: write(iP,...)
 !--Internals
  integer(4)::Vtotl
  !--EndDefs-----------------------------------------------
   if(iP>5) write(iP,"(/'Import Ein:     MS3-RC-Workout@L742'/)")
  !--Internalize the variables in the Ein record:
   cTitle    = Ein%cTitle
   cFileOut  = Ein%cSummaryOut
   cLuTOut   = Ein%cRrAsciiOut
   iType     = Ein%iType
   RubSize   = Ein%RubSize
   Vtot      = Ein%Vtot      !Voters - total
   V         = 0
   cVAtest   = Ein%cVAtest
   V(1:Vtot) = Ein%V(1:Vtot) !Voter(s) | cells          in use
   Ctot      = Ein%Ctot      !Choices- total
   C         = 0
   C(1:Ctot) = Ein%C(1:Ctot) !Choices   | face rotations in use
   Mmax      = Ein%Mmax
   Mtot      = Ein%Mtotvis
   Vtotshow  = Ein%Vtotshow
  !--Define Srtest
   SrTestIn = resetSR  !clears the SrTestIn record
   SrTestIn%nS8      =       0_8 
   SrTestIn%H8       =       0_8 !undefined

   SrTestIn%Mused    = Ein%Mtotvis
   SrTestIn%MC(1:30) = Ein%MCvis(1:30)
   SrTestIn%Vtot     = Ein%Vtot
            Vtotl    = Ein%Vtot 
   SrTestIn%cVAsymb(1:VtotL)  = Ein%cVAtest(1:VtotL) 
   SrTestIn%VA(     1:VtotL)  = Ein%VA(     1:VtotL)

   call PrintErec(Ein,iP,'ImportEin done.  @L762')

   if(Ein%iType==1) call GenScramble(  Ut)  !in MS6--RC-Solve.f95
   if(Ein%iType==4) call SolveScramble(Ut)  !in MS6--RC-Solve.f95
   if(Ein%iType==5) call MinStepSolver(Ut)  !in MS3-Workout.f95
                    call SaveOutFile

   if(iP>5) write(iP,"('ImportEin done @L769'))")
                                                                         return
End Subroutine ImportEin
!---------------------------------------------------------------------------7 9

Subroutine PrintErec(Ein,iP,Label)
!2025.01.25.1440cst JMS- Compactly reports the content of type(Erec)'s.
!--Globals
 use MS2RCDef, only: Erec,Asymbol,Csymbol !,Rtot8 
!--End Globals
 implicit none
 !--Arguments
 type(Erec)::Ein              !SRin input record. Label as an "Sr" or "Rr"
  integer(4)  ::iP              !Write enable>5: write(iP,...)
  character,optional::Label*(*) !Label length is arbitrary
 !--Internals
  integer(4)  ::i,j,nZ
  !--EndDefs-----------------------------------------------
   if(iP>5) then
   write(iP,"(60('-'))")
   write(iP,"( 'PrintErec: Ein% inputs:    ',\)")
   if(present(Label))  then
     write(iP,"('     ""',\)")
     do i=1,len_trim(Label); write(iP,"(a1,\)") Label(i:i); enddo!i
     write(iP,"('""')")
    else; write(iP,*)
   endif!(present(Label))
   write(iP,"('    Ein          =',i4,' bytes at runtime')") sizeof(Ein)
   write(iP,"('   %Einsize      =',i4,'       as written')")Ein%Einsize
   write(iP,"('   %Zonebimsize  =',i40             )")Ein%Zonebimsize
   write(iP,"('   %ZoneFound    =',i40             )")Ein%ZoneFound
   write(iP,"('Ein%cTitle        = ',60a1)") &
              (Ein%cTitle(i:i)  ,i=1,        len_trim(Ein%cTitle)  )
   write(iP,"('   %NameRoot      = ',60a1)") &
              (Ein%NameRoot(i:i),i=1,        len_trim(Ein%NameRoot))
   write(iP,"('   %cSummaryOut   = ',60a1)") &
              (Ein%cSummaryOut(i:i),i=1,     len_trim(Ein%cSummaryOut))

   if(Ein%iType/=5) goto 20
   write(iP,"('   %cRrAsciiOut   = ',60a1)") &
              (Ein%cRrAsciiOut(i:i),i=1,     len_trim(Ein%cRrAsciiOut))
   write(iP,"('   %cSrBinary     = ',60a1)") &
              (Ein%cSrBinary(i:i),i=1,       len_trim(Ein%cSrBinary))
   write(iP,"('   %cRrtoSrBinary = ',60a1)") &
              (Ein%cRrtoSrBinary(i:i),i=1,   len_trim(Ein%cRrtoSrBinary))
   write(iP,"('   %cEinBinary    = ',60a1)") &
              (Ein%cEinBinary(i:i),i=1,      len_trim(Ein%cEinBinary))
   write(iP,"('   %cRrtoDisBinary= ',60a1)") &
              (Ein%cRrtoDisBinary(i:i),i=1,  len_trim(Ein%cRrtoDisBinary))
20 continue

   write(iP,"('   %iType        =',i4)")                   Ein%iType
   write(iP,"('   %RubSize      =',i4)")                   Ein%RubSize
   write(iP,"('   %Vtot         =',i4,' :Cells')")         Ein%Vtot
 
   write(iP,"('   %V(1:Vtot)    =  ',:,i2,9(',',i2),2(/19x,10(',',i2)))") &
                                                           Ein%V

   write(iP,"('   %cVAtest      = ""',27a1,'""')") &
              (Ein%cVAtest(i:i),i=1,        len_trim(Ein%cVAtest))
   write(iP,"('   %VA(1:Vtot)   =  ',:,i2,9(',',i2),2(/19x,10(',',i2)))") &
                                                           Ein%VA
   do i = 1,20; Ein%cVAtest(i:i) = char(Asymbol(Ein%VA(i))); enddo!i                                                                                                             
   write(iP,"('   %cVAtest      = ""',27a1,'"" -from %VA' )") &
              (Ein%cVAtest(i:i),i=1,Ein%Vtot)

   write(iP,"('   %Ctot         =',i4,' :face rotations')")Ein%Ctot
   write(iP,"('   %C(1:Ctot)    =   ',:,a1,17(',',a1),'   hex')")  &
                                            Csymbol(Ein%C(1:Ein%Ctot))
   write(iP,"('   %Mmax         =',i4)")                   Ein%Mmax
   write(iP,"('   %Mtotvis      =',i4)")                   Ein%Mtotvis

   write(iP,"('   %MCvis(1:',i2,')  =   ',\)") Ein%Mtotvis
   do i = 1,Ein%Mtotvis
     if(mod(i,20)/=0) then
       write(iP,"(a1,      ',',\)") Csymbol(Ein%MCvis(i))
      else
      !write(iP,"(a1,i8/,23x,',',\,'***')") Csymbol(Ein%MCvis(i)),i
       write(iP,"(a1,i8/,20x,',',\      )") Csymbol(Ein%MCvis(i)),i
     endif!(mod(i,20)/=0)                                       
   enddo!i
     write(iP,*)
   write(iP,"('   %Vtotshow     =',i4)")                   Ein%Vtotshow
  !-- Zones of Wisdom:
   write(iP,"(/'   %Ztot         =',i4,' :Wisdom Zones')")Ein%Ztot
   write(iP,"( '   %Z(1:Ztot)    =  ',:,20i2           )")Ein%Z(1:Ein%Ztot)
   do i=1,Ein%Ztot; nZ = Ein%Z(i)
     write(iP,"('   %cZrFilename(',i1,')= ""',:,60a1,'""')") &
             nZ,(Ein%cZrFilename(nZ)(j:j),j=1        &
       ,len_trim(Ein%cZrFilename(nZ)) )
   enddo!nZ
   write(iP,"('   %nZ           =',i4,' :Zone in use' )")Ein%nZ
   if(Ein%nZ>0) then
     write(iP,"('   %ZMaskNeed    =',20i2               )")Ein%ZMaskNeed
     write(iP,"('   %ZMaskfora    =',20i2               )")Ein%ZMaskfora
     write(iP,"(' %Vsizez(1:Vtot) = ',20i3              )")Ein%Vsizez
     write(iP,"('   %Mtot         =',i4,' :Moves'       )")Ein%Mtot
   endif!nZ>0
   endif!(iP>5)
   write(iP,"(60('-'))")                                              ;return
End Subroutine PrintErec
!---------------------------------------------------------------------------7 9

Subroutine PrintSRrec(SRin,iP,Label)
!2024.08.24.1140cdt JMS- Compactly reports the content of type(SRrec)'s.
!--Globals
 use MS2RCDef, only: SRrec,Rtot8,Ein,Csymbol 
!--End Globals
 implicit none
 !--Arguments
 type(SRrec)::SRin              !SRin input record. Label as an "Sr" or "Rr"
  integer(4)  ::iP              !Write enable>5: write(iP,...)
  character,optional::Label*(*) !Label length is arbitrary ~ <= 50 characters
 !--Internals
  integer(4)  ::i
  !--EndDefs-----------------------------------------------
   if(iP<6)                                                              return
   write(iP,"(60('-'))")
   write(iP,"('%nS8    =',i25,'   SRrec: ',\)") Srin%nS8
   if(present(Label))  then
     write(iP,"('""',\)")
     do i=1,len_trim(Label); write(iP,"(a1,\)") Label(i:i); enddo!i
     write(iP,"('""')")
    else; write(iP,*)
   endif!(present(Label))
   write(iP,"('%H8     =',i25,'   Rtot8  =',i25)") SRin%H8 ,Rtot8
   write(iP,"('%Mused  = ',i2,2x,'%MC(1:',i2,') =',:,30a2)") &
                  SRin%Mused,SRin%Mused, char(Csymbol(SRin%Mc(1:SRin%Mused)))
   write(iP,"('%Vtot   =',i3,'  %cVAsymb  = ',:,20a1)") &
                     Srin%Vtot, (SRin%cVAsymb(i:i),i=1,SRin%Vtot)
   write(iP,"('%VA(  ) =',:,20i3)")  SRin%VA(1:SRin%Vtot)
   if(SRin%nS8==1_8) then
     write(iP,"('***** %nS8==1 special case: *****')") 
     write(iP,"('SRin%nS8  == 1 has V(1:Vtot) hidden in %MC(2:Vtot+1):')")
     write(iP, &
      "('SRin%MC(1       ) =  0, so the record may be used as-is.')")
     write(iP, &
      "('SRin%MC(2:Vtot+1) =',:,20i3)") SRin%MC(2:SRin%Vtot+1)
     write(iP, &
      "('Ein%V()           =',:,20i3)")  Ein%V( 1:Srin%Vtot  )
     write(iP, &
      "('Hence the ""-Sr.bim"" file can stand alone.')")
     write(iP, &
      "('SRin%MC(29) =Ctot =',i3)") SRin%MC(29)
    else
     write(iP,"('Ein%V() =',:,20i3)")  Ein%V(1:Srin%Vtot)
   endif!(SRin%nS8==1_8)
   write(iP,"(60('-'))");                                                return
End Subroutine PrintSRrec 
!%nS8    =              1   SRrec: "MinStepSolver: Srseed% results @L929:"
!%H8     =              1   Rtot8  =       11022480
!%Mused  =  0            %MC(1: 0) =
!%Vtot   =  7            %cVAsymb  = aaaaaaa
!%VA(  ) =  1  1  1  1  1  1  1
!*** SRin%nS8  == 1 has V(1:Vtot) hidden in %MC(2:Vtot+1):
!    SRin%MC(1       ) =  0, so the record may be used as-is.
!    SRin%MC(2:Vtot+1) =  1  2  3  4  5  6  7
!    Ein%V()           =  1  2  3  4  5  6  7
!    Hence the "-Sr.bim" file can stand alone.
!    SRin%MC(29)= Ctot =  9
!---------------------------------------------------------------------------7 9

