!
!-------------------------------------------------------------------------------
!
! <DOCUMENTATION name="modulePakoOtfMap">
!   <VERSION>
!                Id: modulePakoOtfMap.f90,v 1.2.4  2015-06-17 Hans Ungerechts
!                Id: modulePakoOtfMap.f90,v 1.2.3  2014-12-15 Hans Ungerechts
!                Id: modulePakoOtfMap.f90,v 1.2.3  2014-10-27 Hans Ungerechts
!                Id: modulePakoOtfMap.f90,v 1.2.3  2013-10-17 Hans Ungerechts
!                Id: modulePakoOtfMap.f90,v 1.2.3  2013-09-29 Hans Ungerechts
!                Id: modulePakoOtfMap.f90,v 1.2.3  2013-09-23 Hans Ungerechts
!                                           1.2.3  2013-08-28 Hans Ungerechts
!                                           1.2.3  2013-07-18 Hans Ungerechts
!                                           1.2.3  2013-07-11 Hans Ungerechts
!                                           1.2.3  2013-06-18 Hans Ungerechts
!                                           1.2.3  2013-05-29 Hans Ungerechts
!                                           1.2.1  2013-04-10 Hans Ungerechts
!                    review against pako           2012-11-30
!                    modulePakoOtfMap.f90,v 1.1.12 2012-03-28
!
!                !!  1.2.1 review wrt pako 1.1.14 2012-11-30; modulePakoOtfMap.f90,v 1.1.12 2012-03-28          
!                !!        diff -W 200 -y -b -B modulePakoOtfMap.f90 ~/Pako/pako-2012-11-30/lib/                         
!
!                Id: modulePakoOtfMap.f90,v 1.2.0  2012-08-16 Hans Ungerechts
!
!   </VERSION>
!   <PROGRAM>
!                Pako
!   </PROGRAM>
!   <FAMILY>
!                Observing Modes
!   </FAMILY>
!   <SIBLINGS>
!                Calibrate
!                Focus
!                OnOff
!                OtfMap
!                Pointing
!                Tip
!                Track
!                VLBI
!   </SIBLINGS>        
!
!   Pako module for command: OTFMAP
!
! </DOCUMENTATION> <!-- name="modulePakoOtfMap" -->
!
!-------------------------------------------------------------------------------
!
Module modulePakoOtfmap
  !
  Use modulePakoTypes
  Use modulePakoMessages
  Use modulePakoGlobalParameters
  Use modulePakoLimits
  Use modulePakoXML
  Use modulePakoUtilities
  Use modulePakoPlots
  Use modulePakoDisplayText
  Use modulePakoGlobalVariables
  Use modulePakoSubscanList
  Use modulePakoReceiver
  Use modulePakoBackend
  Use modulePakoSource
  Use modulePakoSwBeam
  Use modulePakoSwFrequency
  Use modulePakoSwWobbler
  Use modulePakoSwTotalPower
  Use modulePakoDIYlist
  !
  Use gbl_message
  !
  Implicit None
  Save
  Private
  Public :: otfMap, displayOtfMap, saveOtfMap, startOtfMap
  !     
  ! *** Variables for otfmap ***
  Include 'inc/variables/variablesOtfMap.inc'
!!!   
!!!   
Contains
!!!
!!!
  Subroutine OTFMAP(programName,line,command,error)
    !
    ! *** Arguments ***
    Include 'inc/variables/headerForCommandHandler.inc'
    !
    ! *** standard working variables ***
    Include 'inc/variables/standardWorkingVariables.inc'
    !
!!OLD      Integer              ::  iMatch = 0 , nMatch = 0
!!OLD      Character (len=128)  ::  errorCode = 'none'
!!OLD      Logical              ::  errorM = .False.
    !
    ! *** special working variables:   ***
    Logical               :: optionSpeedIsPresent, optionTotfIsPresent
    Logical, Dimension(3) :: alternative
    Real                  :: vIn, vStdMin, vStdMax, vLimitMin, vLimitMax
    !
    Real                  :: vMaxX,   vMaxY
    Real                  :: vLimit, vLimitAz, vLimitEl
    Real                  :: vMaxXel, vMaxYel, MaxEl
    !
    Logical               :: isConnected   = .False.
    Real                  :: mapRotation   = 0.0
    !
    Character (len=lenCh) ::  bolometerName
    !
    Logical               :: errorCount
    Integer               :: nSubscansCal, nSubscansReference
    Integer               :: nSubscansOTF, nSubscansTotal
    !
    Type(conditionMinMax)  ::  condElevation                                     &
         &                     = conditionMinMax("elevation",                    &
         &                                        0.0, Pi/2.0,                   &
         &                                       "rad",                          &
         &                                       .False.         )               ! 
    !
    optionSpeedIsPresent = .False.
    optionTotfIsPresent  = .False.
    alternative          = .False.
    !
    errorCount           = .False.
    nSubscansCal         = 0
    nSubscansReference   = 0
    nSubscansOTF         = 0
    nSubscansTotal       = 0
    !
    !     TBD: the following shall be replaced by a SR reading from XML:
    Include 'inc/ranges/rangesOtfMap.inc'
    !
    ERROR = .False.
    !
    Call pako_message(seve%t,programName,                                        &
         &  " module OtfMap, v 1.2.3 2013-07-11---> SR: OtfMap ")                ! trace execution
    !
    ! *** initialize:   ***
    If (.Not.isInitialized) Then
       Include 'inc/variables/setDefaults.inc'
       isInitialized = .True.
    Endif
    !
    ! *** set In-values = previous Values ***
    If (.Not.ERROR) Then
       vars(iIn) = vars(iValue)
    End If
    !
    ! *** check N of Parameters: 0, n --> at  most n allowed  ***
    Call checkNofParameters(command,                                             &
         &     0, 4,                                                             &
         &     nArguments,                                                       &
         &     errorNumber)                                                      !
    ERROR = ERROR .Or. errorNumber
    !
    ! *** check for alternative Options   ***
    If (.Not. ERROR) Then
       Include 'inc/options/alternativeSpeedTotf.inc'
    End If
    !
    ! *** read Parameters, Options (to detect errors)            
    !     and check for validity and ranges                      
    If (.Not. ERROR) Then
       Call pakoMessageSwitch (setOn = .True.)
       Include 'inc/parameters/parametersStartEnd.inc'
       Include 'inc/parameters/parametersLengthOtf.inc'
       Include 'inc/options/readOptionsOtfMap.inc'
    End If
    !
    ! *** set defaults   ***
    If (.Not. ERROR) Then
       option = 'DEFAULTS'
       Call indexCommmandOption                                                  &
            &        (command,option,commandFull,optionFull,                     &
            &        commandIndex,optionIndex,iCommand,iOption,                  &
            &        errorNotFound,errorNotUnique)                               !
       setDefaults = SIC_PRESENT(iOption,0)
       If (setDefaults) Then
          Include 'inc/variables/setDefaults.inc'
       Endif
    Endif
    !
    ! *** Read Parameters, Options (again, after defaults!)   ***
    ! *** and check for validity and ranges                   ***
    If (.Not. ERROR) Then
       Call pakoMessageSwitch (setOff = .True.)
       Include 'inc/parameters/parametersStartEnd.inc'
       Include 'inc/parameters/parametersLengthOtf.inc'
       Include 'inc/options/readOptionsOtfMap.inc'
       Include 'inc/options/alternativeSpeedTotfSet.inc'
    End If
    Call pakoMessageSwitch (setOn = .True.)
    !
    ! *** check consistency and                           ***
    ! *** store into temporary (intermediate) variables   ***
    If (.Not.ERROR) Then    !!   check consistency
       !
       errorInconsistent = .False.
       !
       Include 'inc/options/checkConsistentLengthOtfSpeedTotf.inc'
       !
       If (.Not. errorInconsistent) Then
          Include 'inc/options/checkConsistentNresumeNotf.inc'
       End If
       !
       !D       Write (6,*) "      vars(iIn)%tOtf:   ", vars(iIn)%tOtf
       !D       Write (6,*) "      GV%tRecord:       ", GV%tRecord
       If (vars(iIn)%tOtf .Lt. 5*GV%tRecord) Then
          If (vars(iIn)%tOtf .Lt. 3*GV%tRecord) Then
             errorInconsistent = .True.
             Write (messageText,*)    "must be at least 3 times "                &
                  &                // "tRecord = tPhase*nPhases*nCycles = "      &
                  &                 ,  GV%tRecord                                &
                  &                 , "of switching mode "//GV%switchingMode     !
             Call pakoMessage(priorityE,severityE,                               &
                  &           command(1:l)//"/"//"tOtf",messageText)             !
          Else
             Write (messageText,*)    "should be at least 5 times "              &
                  &                // "tRecord = tPhase*nPhases*nCycles = "      &
                  &                 ,  GV%tRecord                                &
                  &                 , "of switching mode "//GV%switchingMode     !
             Call pakoMessage(priorityW,severityW,                               &
                  &           command(1:l)//"/"//"tOtf",messageText)             !
          End If
       End If
       !
       If (vars(iIn)%doReference                                                 &
            &  .And.   vars(iIn)%tReference .Lt. 5*GV%tRecord) Then              !
          If (vars(iIn)%tReference .Lt. 3*GV%tRecord) Then
             errorInconsistent = .True.
             Write (messageText,*)    "must be at least 3 times "                &
                  &                // "tRecord = tPhase*nPhases*nCycles = "      &
                  &                 ,  GV%tRecord                                &
                  &                 , "of switching mode "//GV%switchingMode     !
             Call pakoMessage(priorityE,severityE,                               &
                  &           command(1:l)//"/"//"tReference",messageText)       !
          Else
             Write (messageText,*)    "should be at least 5 times "              &
                  &                // "tRecord = tPhase*nPhases*nCycles = "      &
                  &                 ,  GV%tRecord                                &
                  &                 , "of switching mode "//GV%switchingMode     !
             Call pakoMessage(priorityW,severityW,                               &
                  &           command(1:l)//"/"//"tReference",messageText)       !
          End If
       End If
       !
       If (vars(iIn)%doReference                                                 &
            &  .And. vars(iIn)%systemNameRef.Ne.vars(iIn)%systemName) Then       !
          errorInconsistent = .True.
          GV%notReadyOtfMap = .True.
          Write (messageText,*) "different values for /SYSTEM ",                 &  
               &  "and /REFERENCE are not yet allowed "                          !
          Call pakoMessage(priorityE,severityE,                                  &
               &           command//"/"//"REFERENCE",messageText)                !
       End If
       !
       If (    .Not. (GV%privilege.Eq.setPrivilege%staff                         &
            &  .Or.   GV%privilege.Eq.setPrivilege%ncsTeam)) Then                !
          If (GV%switchingMode.Eq.swMode%Beam) Then
             errorInconsistent = .True.
             GV%notReadyOtfMap = .True.
             Write (messageText,*)  "not compatible with with switching mode ",  &
                  &                 swModePako%Beam                              !
             Call PakoMessage(priorityE,severityE,command,messageText)
          End If
       End If
       !

!!$!! possible new code to consider as replacement (2014-10-17)
!!$       !D        Write (6,*) "      GV%switchingMode:   ", GV%switchingMode
!!$       !D        Write (6,*) "      GV%privilege:       ", GV%privilege
!!$       !D        Write (6,*) "      GV%iPrivilege:       ", GV%iPrivilege
!!$       !D        Write (6,*) "      GV%userLevel:       ", GV%userLevel
!!$       !D        Write (6,*) "      GV%iUserLevel:      ", GV%iUserLevel
!!$       !
!!$       If (           GV%switchingMode.Eq.swMode%Beam                            &
!!$            &  .And. .Not.(      GV%iUserLevel.Ge.iexperienced                   &
!!$            &               .Or. GV%privilege.Eq.setPrivilege%ncsTeam            &
!!$            &             )                                                      &
!!$            & ) Then                                                             !
!!$          !
!!$          errorInconsistent = .True.
!!$          Write (messageText,*)  "not compatible with with switching mode ",  &
!!$               &                 swModePako%Beam                              !
!!$          !
!!$       End If

       !
       If (        vars(iIn)%doReference .And. GV%switchingMode.Eq.swMode%Freq   &
            & .Or. vars(iIn)%doReference .And. GV%switchingMode.Eq.swMode%Wobb ) &
            & Then                                                               !
          errorInconsistent = .True.
          GV%notReadyOtfMap = .True.
          Write (messageText,*)  "will not work with switching mode ",           &
               &                 GV%switchingMode                                !
          Call PakoMessage(priorityE,severityE,command//" /reference",           &
               &                 messageText)                                    !
          Write (messageText,*)  "consider to use: /reference no" 
          Call PakoMessage(priorityI,severityI,command,                          &
               &                 messageText)                                    !
       End If
       !
       Call queryReceiver(rec%bolo, isConnected)
       !D       Write (6,*) "vars(iIn)%systemName : ", vars(iIn)%systemName
       !D       Write (6,*) "offsPako%tru :         ", offsPako%tru
       If (isConnected .And. GV%switchingMode.Eq.swMode%Wobb                     &
            &          .And. vars(iIn)%systemName .Eq. offsPako%tru) Then        !
          !D          Write (6,*) "GV%secondaryRotation:", GV%secondaryRotation
          !D          Write (6,*) "vars(iIn)%pStart:    ", vars(iIn)%pStart
          !D          Write (6,*) "vars(iIn)%pEnd:      ", vars(iIn)%pEnd
          !D          Write (6,*) "rotation angle of OTF map: ",         &
          !D               &       vars(iIn)%pEnd%y,vars(iIn)%pStart%y,  &
          !D               &       vars(iIn)%pEnd%x,vars(iIn)%pStart%x
          mapRotation =                                                          &
               & -atan((vars(iIn)%pEnd%y-vars(iIn)%pStart%y)                     &
               &      /(vars(iIn)%pEnd%x-vars(iIn)%pStart%x))/deg                !
          !D          Write (6,*) "rotation angle of OTF map: ",         &
          !D               & mapRotation
          If (Abs(GV%secondaryRotation-mapRotation).GT.0.005) Then
             errorInconsistent = .True.
             GV%notReadyOtfMap = .True.
             Write (messageText,*)      "map rotation ", mapRotation,            &
                  &   " inconsistent with 2ndRotation ", GV%secondaryRotation    !
             Call PakoMessage(priorityE,severityE,command,messageText)      
          End If
       End If
       !
       Call countSubscansOtfMap                                                  &
            &   ( nSubscansCal, nSubscansReference, nSubscansOTF, nSubscansTotal,&
            &     errorCount )                                                   !
       !
       If (               errorCount                                             &
            &  .And. .Not.GV%privilege.Eq.setPrivilege%ncsTeam ) Then            ! allow "too many" subscans
          !                                                                      ! (only for tests of antMD)
          errorInconsistent = .True.
          Write (messageText,*)     " too many subscans. OTF: ",                 &
               &                      vars(iIn)%nOtf,                            &
               &                    " + Reference: ",                            &
               &                      nSubscansReference                         !
          Call PakoMessage(priorityE,severityE,command,messageText)      
          Write (messageText,*)     " maximum OTF + Reference: ",                &
               &                      vars(iLimit2)%nOtf                         !
          Call PakoMessage(priorityE,severityW,command,messageText)      
       End If
       !
       If (.Not. errorInconsistent) Then
          vars(iTemp) = vars(iIn)
       End If
       !
    End If   !!   check consistency
    !
    !D     Write (6,*) "       errorInconsistent:  ", errorInconsistent
    !
    ERROR = ERROR .Or. errorInconsistent
    !
    ! *** conclude alternative options   ***
    If (.Not.error) Then
       Include 'inc/options/alternativeSpeedTotfEnd.inc'
    End If
    !
    ERROR = ERROR .Or. errorInconsistent
    !
    If (.Not.error) Then     !!    speed limit and elevation condition
       !
       vMaxX  =   max(vars(iTemp)%speedStart, vars(iTemp)%speedEnd)
       vMaxY  =   max(vars(iTemp)%speedStart, vars(iTemp)%speedEnd)
       !
       !! TBD: (2012-03-17) more sophisticated criterium
       !! --> 2012-03-25:
       !
       If (         vars(iTemp)%systemName.Eq.offsPako%tru                       &
            &  .Or. vars(iTemp)%systemName.Eq.offsPako%hor) Then                 !
          !
          vMaxX  =   Abs(vars(iTemp)%pEnd%x-vars(iTemp)%pStart%x)                &
               &        /vars(iTemp)%tOtf                                        !
          vMaxY  =   Abs(vars(iTemp)%pEnd%y-vars(iTemp)%pStart%y)                &
               &        /vars(iTemp)%tOtf                                        !
          !
       Else
          vMaxX  =   max(vars(iTemp)%speedStart, vars(iTemp)%speedEnd)
          vMaxY  =   max(vars(iTemp)%speedStart, vars(iTemp)%speedEnd)
       End If
       !
       !! TBD: use same code (ectract!) as in POINTING (see!). note added 2012-05-30
       !! TBD: long-term: ramp-up!
       !
       !                        !!  speed limit az. axis, el. axis
       vLimit   = 200.0         !!  based on tests 2012-03-15 to -20
       !                                 
       !
       If      (     GV%privilege.Eq.setPrivilege%ncsTeam                        &
            &  .Or.  GV%userLevel.Eq.setUserLevel%experienced                    &
            &  ) Then                                                            !
          If (GV%limitCheck.Eq.setLimitCheck%loose)   vLimit = 300.0 
          If (GV%limitCheck.Eq.setLimitCheck%relaxed) vLimit = 220.0
       End If
       !
       vLimitAz = vLimit        !!  speed limit az axis
       vLimitEl = vLimit        !!  speed limit el axis
       !
       !! aLimit = 108.0*arcsec
       !
       If (GV%doDebugMessages) Then
          Write (6,*) " vMaxX:     ", vMaxX
          Write (6,*) " vMaxY:     ", vMaxY
          Write (6,*) " vLimit:    ", vLimit
          Write (6,*) " vLimitAz:  ", vLimitAz
          Write (6,*) " vLimitEl:  ", vLimitEl
       End If
       !
       If (         vars(iTemp)%systemName.Eq.offsPako%tru                       &
            &  .Or. vars(iTemp)%systemName.Eq.offsPako%hor) Then                 !
          !
          If (vMaxX.Le.vLimitAz) Then
             vMaxXel = Acos(vMaxX/(vLimitAz))
          Else
             errorInconsistent = .true.
             Write (messageText,*) "Azimuth speed ", vMaxX,                      &
                  &                " too large for safe tracking"                !
             Call PakoMessage(priorityE,severityE,command,messageText)
          End If
          !
          If (vMaxY.Le.vLimitEl) Then
             vMaxYel = 90.0*deg
          Else
             errorInconsistent = .true.
             Write (messageText,*) "Elevation speed ", vMaxY,                    &
                  &                " too large for safe tracking"                !
             Call PakoMessage(priorityE,severityE,command,messageText)
          End If
          !
       Else
          !
          If (vMaxX.Le.vLimit .And. vMaxY.Le.vLimit) Then
             vMaxXel = Acos(vMaxX/(vLimit))
             vMaxYel = Acos(vMaxY/(vLimit))
          Else
             errorInconsistent = .true.
             Write (messageText,*) "Speed ", max(vMaxX,vMaxY),                   &
                  &                " too large for safe tracking"                !
             Call PakoMessage(priorityE,severityE,command,messageText)
          End If
          !
       End If
       !
       If (GV%doDebugMessages) Then
          Write (6,*) " max el vMaxXel: ", vMaxXel/deg
          Write (6,*) " max el vMaxYel: ", vMaxYel/deg
       End If
       !
       !! <<-- 2012-03-25
       !
       !! aMaxXel = Acos(aMaxX/(2*aLimit))  ! <-- corrected aLimit on 2010-03-18 
       !! aMaxYel = Acos(aMaxY/(2*aLimit))  ! <-- corrected aLimit on 2010-03-18 
       !
       MaxEl   = min(vMaxXel,vMaxYel)
       !
       ! 2010-04-08 HU: force safe limit on maximum elevation
       !                for GISMO run, based on TT-NCS
       MaxEl = MaxEl-2.0*deg
       !
       !D        Write (6,*) " max el  MaxEl:  ", MaxEl/deg
       !
       MaxEl   = max(0.0*deg,MaxEl) 
       MaxEl   = min(MaxEl,85.0*deg)
       !
       !D        Write (6,*) " max el vMaxXel: ", vMaxXel/deg
       !D        Write (6,*) " max el vMaxYel: ", vMaxYel/deg
       !D        Write (6,*) " max el aMaxXel: ", aMaxXel/deg
       !D        Write (6,*) " max el aMaxYel: ", aMaxYel/deg
       !D        !
       !D        Write (6,*) " max el  MaxEl:  ", MaxEl/deg
       !
       !!             If (MaxEl.Ge.60.0*deg) Then
       !
       condElevation%isSet     = .True.
       condElevation%maximum   = MaxEl
       !
       If (GV%doDebugMessages) Then
          Write (6,*) " condElevation%isSet:   ", condElevation%isSet
          Write (6,*) " condElevation%maximum: ", condElevation%maximum/deg
       End If
       !
       Write (messageText, fmt =                                           &
            &  '("WARNING--CONDITION: Elevation must be less than ",       &
            &     F10.2,                                                   &
            &    " [deg] ")' )                                             &
            & condElevation%maximum/deg                                    !
       Call pakoMESSAGE(priorityW,severityW,"OTFMAP",messageText)
       !
    End If     !!    speed limit and elevation condition
    !
    ERROR = ERROR .Or. errorInconsistent
    !
    ! *** store from temporary into final variables ***
    If (.Not.ERROR) Then
       vars(iValue)  = vars(iTemp)
    End If
    !
    If (.Not.error) Then
       GV%observingMode     = OM%OtfMap
       GV%observingModePako = OMpako%OtfMap
       !D       Write (6,*) "   GV%observingMode: ", GV%observingMode
    End If
    !
    ! *** set "selected" observing mode & plot ***
    If (.Not.error) Then
       GV%observingMode     = OM%OtfMap
       GV%observingModePako = OMpako%OtfMap
       GV%omSystemName      = vars(iValue)%systemName 
       GV%condElevation     = condElevation
       If (GV%doDebugMessages) Then
          Write (6,*) "GV%condElevation: ", GV%condElevation
       End If
       !
       GV%notReadySWafterOM = .False.
       GV%notReadySecondaryRafterOM = .False.
       !D       Write (6,*) '      GV%notReadySecondaryRafterOM: ',                       &
       !D            &             GV%notReadySecondaryRafterOM
       GV%notReadyOtfMap    = .False.
       otfMapCommand        = line(1:lenc(line))
       Call analyzeOtfMap (errorA)
       Call plotOtfMap (errorP)
    End If
    !
    ! *** display values ***
    If (.Not. ERROR) Then
       Call displayOtfMap
       Call listDIYlist (error)
    End If
    !
    Return
  End Subroutine OTFMAP
!!!
!!!
  Subroutine displayOtfMap
    !
    Include 'inc/variables/standardWorkingVariables.inc'
    !
    Character(len=24)  :: command
    !
    Call pako_message(seve%t,"OTFMAP",                                           &
         &  " module OtfMap, v 1.2.0  --> SR: displayOtfMap ")                   ! trace execution
    !
    Include 'inc/display/commandDisplayOtfMap.inc'
    !
  End Subroutine displayOtfMap
!!!
!!!
  Subroutine countSubscansOtfMap                                                 &
       &   ( nSubscansCal, nSubscansReference, nSubscansOTF, nSubscansTotal,     &
       &     errorCount )                                                        !
    !
    Include 'inc/variables/standardWorkingVariables.inc'
    !
    Logical, Intent(OUT) :: errorCount
    Integer, Intent(OUT) :: nSubscansCal, nSubscansReference
    Integer, Intent(OUT) :: nSubscansOTF, nSubscansTotal
    !
    !! NOTE: the following counting of subscans must reflect analyzeOtfMap
    !
    Integer              :: iCRO          = 0       ! counts through CRO loop
    Integer              :: iCROnext      = 0       !        next iCRO
    Integer              :: iSS           = 0       ! counts subcans/segment
    Integer              :: iOTF          = 0       ! counts OTF subscans
    Integer              :: iREF          = 0       ! counts REF subscans
    Integer              :: iCAL          = 0       ! counts CAL subscans
    !
    Logical              :: lastIsCAL     = .False. ! tracks if last subscans
    !                                               !   added in loop is CAL
    Logical              :: lastIsOTF     = .False. ! tracks if last subscans
    !                                               !   added in loop is OTF
    Character (len=1)    :: cCroII        = ''      ! stores previous CRO code    
    !
    errorCount           = .False.
    nSubscansCal         = 0
    nSubscansReference   = 0
    nSubscansOTF         = 0
    nSubscansTotal       = 0
    !
    lastIsCAL            = .False.
    lastIsOTF            = .False.
    !
    If (GV%doDebugMessages) Then
       Write (6,*) "  "
       Write (6,*) "   ---> SR countSubscansOtfMap "
       Write (6,*) "  "
       Write (6,*) "      vars(iIn)%croCodeCount: ", vars(iIn)%croCodeCount
       Write (6,*) "      vars(iIn)%croCodeBites: ", vars(iIn)%croCodeBites
    End If
    !
    iCRO = 0
    iSS  = 0
    iOTF = 0
    iREF = 0
    iCAL = 0
    !
    cCroII = ''
    !
    Do While (iOTF .Lt. vars(iIn)%nOtf)
       !
       iCRO     = iCRO+1
       iCROnext = iCRO+1
       !
       iCRO = Modulo(iCRO,vars(iIn)%croCodeCount)
       If (iCRO.Eq.0) iCRO = vars(iIn)%croCodeCount
       iCROnext = Modulo(iCROnext,vars(iIn)%croCodeCount)
       If (iCROnext.Eq.0) iCROnext = vars(iIn)%croCodeCount
       !
       If (vars(iIn)%croCodeBites(iCRO:iCRO).Eq."C") Then
          !
          iSS  = iSS  +1            !! CAL SKY
          iCAL = iCAL +1
          iSS  = iSS  +1            !! CAL AMBIENT
          iCAL = iCAL +1
          iSS  = iSS  +1            !! CAL COLD
          iCAL = iCAL +1
          !
          lastIsCAL            = .True.
          lastIsOTF            = .False.
          !
          If (GV%doDebugMessages) Then
             Write (6,*) "      loop: added CAL "
             Write (6,*) "      iCRO: ", iCRO, " iSS: ", iSS, " iCAL: ", iCAL
          End If
          !
       End If
       !
       If (vars(iIn)%doReference .And.                            &
            &         vars(iIn)%croCodeBites(iCRO:iCRO).Eq."R") Then
          !
          iSS  = iSS  +1            !! REFERENCE
          iREF = iREF +1
          !
          cCroII = vars(iIn)%croCodeBites(iCRO:iCRO)
          !
          lastIsCAL            = .False.
          lastIsOTF            = .False.
          !
          If (GV%doDebugMessages) Then
             Write (6,*) "      loop: added REF "
             Write (6,*) "      iCRO: ", iCRO, " iSS: ", iSS, " iREF: ", iREF
          End If
          !
       End If
       !
       If (vars(iIn)%croCodeBites(iCRO:iCRO).Eq."O") Then
          !
          iSS  = iSS  +1            !! OTF
          iOTF = iOTF +1
          !
          cCroII = vars(iIn)%croCodeBites(iCRO:iCRO)
          !
          lastIsCAL            = .False.
          lastIsOTF            = .True.
          !
          If (GV%doDebugMessages) Then
             Write (6,*) "      loop: added OTF "
             Write (6,*) "      iCRO: ", iCRO, " iSS: ", iSS, " iOTF: ", iOTF
          End If
          !
       End If
       !
    End Do
    !
    nSegments = iSS
    !
    ii = vars(iIn)%croCodeCount
    If (vars(iIn)%doReference                                                    &
         &         .And.((vars(iIn)%croCodeBites(ii:ii).Eq."R"                   &      
         &                   .And. lastIsOTF)                                    &
         &               .Or.                                                    &
         &               (vars(iIn)%croCodeBites(ii-1:ii).Eq."RC"                &      
         &                   .And. lastIsOTF)                                    &
         &              )                                                        &
         &        ) Then                                                         !
       !
       iSS  = iSS  +1            !! add REFERENCE at end
       iREF = iREF +1
       !
       cCroII = vars(iIn)%croCodeBites(iCRO:iCRO)
       !
       If (GV%doDebugMessages) Then
          Write (6,*) "      end:  added REF "
          Write (6,*) "      iCRO: ", iCRO, " iSS: ", iSS, " iREF: ", iREF
       End If
       !
    End If
    !
    nSegments = iSS
    !
    ii = vars(iIn)%croCodeCount
    If ( vars(iIn)%croCodeBites(ii:ii).Eq."C"                                    &      
         &         .And. .Not. lastIsCal                                         &
         &        ) Then                                                         !
       !                         !! add CAL at end
       iSS  = iSS  +1            !! CAL SKY
       iCAL = iCAL +1
       iSS  = iSS  +1            !! CAL AMBIENT
       iCAL = iCAL +1
       iSS  = iSS  +1            !! CAL COLD
       iCAL = iCAL +1
       !
       If (GV%doDebugMessages) Then
          Write (6,*) "      end:  added CAL "
          Write (6,*) "      iCRO: ", iCRO, " iSS: ", iSS, " iCAL: ", iCAL
       End If
       !
    End If
    !
    nSegments = iSS
    !
!!$    Write (messageText,*)  "   number of Subscans/Segments: ", nSegments
!!$    Call pakoMessage(priorityI,severityI,                                        &
!!$         &           "OTFMAP "//" countSubscansOtfMap",messageText)              !
    !
    nSubscansCal        =  iCal
    nSubscansReference  =  iREF
    nSubscansOTF        =  iOTF
    nSubscansTotal      =  iSS
    !
    If (GV%doDebugMessages) Then
       Write (6,*) "  "
       !D        Write (6,*) "      vars(iIn)%croCodeCount: ", vars(iIn)%croCodeCount
       !D        Write (6,*) "      vars(iIn)%croCodeBites: ", vars(iIn)%croCodeBites
       Write (6,*) "      nSegments:              ", nSegments
       Write (6,*) "      nSubscansCal:           ", nSubscanscal
       Write (6,*) "      nSubscansReference:     ", nSubscansReference
       Write (6,*) "      nSubscansOTF:           ", nSubscansOTF
       Write (6,*) "      nSubscansTotal:         ", nSubscansTotal
       Write (6,*) "      vars(iLimit2)%nOtf:     ", vars(iLimit2)%nOtf
    End If
    !
    If (nSubscansTotal.Gt.vars(iLimit2)%nOtf ) Then
       errorCount = .True.
    End If
    !
    If (GV%doDebugMessages) Then
       Write (6,*) "  "
       Write (6,*) "   <--- SR countSubscansOtfMap "
       Write (6,*) "  "
    End If
    !
    Return
    !
  End Subroutine countSubscansOtfMap
!!!
!!!
  Subroutine analyzeOtfMap (errorA)
    !
    ! TBD:  support of several reference positions
    ! TBD:  support of /RESUME
    !
    ! <DOCUMENTATION name="analyzeOtfMap">
    !
    ! 
    ! The sequence of subscans is determined by 
    ! /croLoop /nOtf /reference /step /zigzag
    !
    ! TBD 2014: document /tune
    ! 
    ! /croLoop     sequence of 
    !              C Calibration
    !              R off-source Reference
    !              O on-source OTF
    ! /nOtf        number of OTF subscans
    ! /reference   off-source reference position
    ! /step        step in x and y between OTF subscans
    !              = translation of one OTF subscans to the next
    ! /zigzag      option to scan back-and-forth
    ! 
    ! The scan analysis loops through the letter codes in croLoop
    ! until nOtf OTF subscans have been generated, starting with 
    ! first letter in the croLoop.
    !    
    !    IF THE CROCODE LETTER IS "C":
    !    
    !    3 calibration subscans on cold load, ambient load, and sky
    !    are generated. The position of the (sky) calibration subscan is:
    !     - the (next) reference position if /reference is true, else:
    !       - if there is one calibration between 2 OTF subscans,
    !         the start position of the next OTF subscan
    !       - if there are two calibrations between 2 OTF subscans,
    !         the first (sky) calibration will be at the end 
    !         the end of the previous OTF subscan
    !    
    !    IF THE CROCODE LETTER IS "R" AND /REFERENCE IS TRUE:
    !    
    !    1 subscan tracking the fixed off-source reference position
    !    is generated
    !    
    !    IF THE CROCODE LETTER IS "O":
    !    
    !    1 linear OTF subscan is generated. 
    !    - The start and end positions of the first OTF subscan are:
    !      parameters xStart yStart xEnd yEnd of the OTFMAP command
    !    - For the second all following OTF subscans:
    !      xStart yStart xEnd yEnd of the previous OTF subscan are
    !      incremented by parameters dx and dy of option /step
    !      If /zigzag is true, xStart yStart and xEnd yEnd are
    !      interchanged
    !    
    ! Then the next letter code in the croLoop is considered
    ! in the same way.
    ! 
    ! If /reference is true,
    ! a croCode ending in "RC" or "R" will ensure that an off-source
    ! reference subscan follows the last OTF subscan.
    ! 
    ! A croCode ending in "C" will ensure that the subscan sequence
    ! ends with 3 calibration subscans on cold load, ambient load, and sky.
    ! - The position of the calibration sky subscan will be that of
    !   the last off-source reference position if /reference is true, else:
    ! - the end(!)  position of the last OTF subscan
    !
    ! </DOCUMENTATION> <!-- name="analyzeOtfMap" -->
    !
    Include 'inc/variables/standardWorkingVariables.inc'
    !
    Integer              :: nScan 
    Character (len=12)   :: aUnit, sUnit
    Integer              :: iCRO          = 0     ! counts through CRO loop
    Integer              :: iCROnext      = 0     !        next iCRO
    Integer              :: iSS           = 0     ! counts subcans/segment
    Integer              :: iOTF          = 0     ! counts OTF subscans
    !
    Character (len=1)    :: cCroII        = ''    ! stores previous CRO code    
    !
    Real                 :: tQuant, vQuant
    !
    errorA = .False.
    !
    Call pako_message(seve%t,"OTFMAP",                                           &
         &  " module OtfMap, v 1.2.4  2015-06-17 --> SR: analyzeOtfMap ")        ! trace execution
    !
    If (GV%doDebugMessages) Then
       !
       Write (6,*) "     "
       Write (6,*) "     vars(iValue)%tOtf:         ",  vars(iValue)%tOtf
       Write (6,*) "     vars(iValue)%lengthOtf     ",  vars(iValue)%lengthOtf
       Write (6,*) "     vars(iValue)%speedStart:   ",  vars(iValue)%speedStart
       Write (6,*) "     vars(iValue)%speedEnd:     ",  vars(iValue)%speedEnd
       Write (6,*) "     "
       !
    End If
       !
       tQuant  =  vars(iValue)%tOtf
       vQuant  =  vars(iValue)%speedStart 
       !
    If (GV%doDebugMessages) Then
       !
       Write (6,*) "     tQuant:                    ",  tQuant
       Write (6,*) "     vQuant:                    ",  vQuant
       Write (6,*) "     "
       !
    End If
       !  
    If ( Index(GV%testMode,"quant").Ge.1 ) Then                                                      !  
       !
       If (GV%doDebugMessages) Then
          Write (6,*) "      analyzeOtfMap: GV%testMode:   ", GV%testMode
          Write (6,*) "      --> will apply quantisation of OTF time, speed "
       End If
       !
       tQuant  =  tQuant - Mod(tQuant,0.125) !!  + 0.125   !! ??                 !  !!  TBD 2014: test
       !       
       If (GV%doDebugMessages) Then
          Write (6,*) "     tQuant:                    ",  tQuant
          Write (6,*) "     vQuant:                    ",  vQuant
          Write (6,*) "     "
       End If
       !
       tQuant  =  tQuant + 0.001
       !
       vQuant  =  vars(iValue)%lengthOtf  /  tQuant
       !
       If (GV%doDebugMessages) Then
          Write (6,*) "     tQuant:                    ",  tQuant
          Write (6,*) "     vQuant:                    ",  vQuant
          Write (6,*) "     "
       End If
       !
    End If
    !
    ! TBD:  proper scan numbers
    nScan     = 1111
    aUnit     = GV%angleUnitC
    sUnit     = GV%speedUnitC
    !
    Call countSubscans(value=0)
    Call countSegments(value=0)
    !
    iCRO = 0
    iSS  = 0
    iOTF = 0
    !
    cCroII = ''
    !
    If (vars(ivalue)%doTune) Then
       !
       If (GV%doDebugMessages) Then
          Write (6,*) "  --> Tune Subscan "
          Write (6,*) "      vars(iValue)%doTune : ", vars(iValue)%doTune
          Write (6,*) "      vars(iValue)%tTune :  ", vars(iValue)%tTune
       End If
       !
       Call countSubscans(ii)
       Call countSegments(jj)
       !            
       iSS = iSS+1
       !
       segList(iSS)            =  segDefault                    ! TUNE
       !
       segList(iSS)%newSubscan =  .True.
       segList(iSS)%scanNumber =  nScan
       segList(iSS)%ssNumber   =  iSS
       segList(iSS)%segNumber  =  1
       segList(iSS)%ssType     =  ss%tune
       segList(iSS)%segType    =  seg%track
       segList(iSS)%angleUnit  =  aUnit
       segList(iSS)%speedUnit  =  sUnit
       !
       segList(iSS)%flagOn     =  .True.
       segList(iSS)%flagRef    =  .False.
       !
       segList(iSS)%flagDropin =  .False.
       !
       segList(iSS)%flagTune   =  vars(iIn)%doTune
       !
!!$       If (vars(ivalue)%doReference) Then
!!$          segList(iSS)%pStart     =  vars(iValue)%offsetR
!!$       Else
!!$          segList(iSS)%pStart     =  vars(iValue)%pStart
!!$       End If
       !
       segList(iSS)%pStart     =  vars(iValue)%offsetTune
       !
       segList(iSS)%pEnd       =  segList(iSS)%pStart
       segList(iSS)%speedStart =  0.0
       segList(iSS)%speedEnd   =  0.0
       segList(iSS)%systemName =  vars(iValue)%systemName
       segList(iSS)%altOption  =  'tSegment'
       segList(iSS)%tSegment   =  vars(iValue)%tTune
       segList(iSS)%tRecord    =  0.1
       !
!!$          iQuery    = iPro
!!$          nameQuery = GPnone
!!$          Call  queryOffsets(iQuery,nameQuery,isSet,pointResult)
       !D          Write (6,*) "  SUBSCAN:  isSet = ", isSet
       !D          Write (6,*) "  SUBSCAN:  pointResult = ", pointResult
       !
       ! TBD: clever /proper handling of Doppler 
       segList(iSS)%upDateDoppler = .False.
       !
       If (GV%doDebugMessages) Then
          Write (messageText,*)  "  subscan #:   ", iSS, " ",                    &
               &             segList(iSS)%ssType, " ", segList(iSS)%pStart       !
!!$            &           " segList(iSS)%flagTune: ", segList(iSS)%flagTune        !
          Call pakoMessage(priorityI,severityI,"OTFMAP "//" Analyze",messageText)
          !
          Write (6,*) "  <-- Tune Subscan "
       End If
       !
    End If   !!   (vars(ivalue)%doTune)
    !
    Do While (iOTF .Lt. vars(iValue)%nOtf)
       !
       iCRO     = iCRO+1
       iCROnext = iCRO+1
       !
       !D           write (6,*) "   ++iCRO: ", iCRO
       !
       iCRO = Modulo(iCRO,vars(iValue)%croCodeCount)
       If (iCRO.Eq.0) iCRO = vars(iValue)%croCodeCount
       iCROnext = Modulo(iCROnext,vars(iValue)%croCodeCount)
       If (iCROnext.Eq.0) iCROnext = vars(iValue)%croCodeCount
       !
       !D           write (6,*) "     iCRO:     ", iCRO
       !D           write (6,*) "      CRO(",iCRO,"):   ->",                      &
       !D     &                 vars(iValue)%croCodeBites(iCRO:iCRO),"<-"
       !D           write (6,*) "     iCROnext: ", iCROnext
       !D           write (6,*) "      CRO(",iCROnext,"):   ->",                  &
       !D     &                 vars(iValue)%croCodeBites(iCROnext:iCROnext),"<-"
       !D
       !D           write (6,*) "     iSS:  ", iSS
       !D           write (6,*) "     iOTF: ", iOTF
       !D!
       !D           write (6,*) " is C? ", vars(iValue)%croCodeBites(iCRO:iCRO).eq."C"
       !D           write (6,*) " is c? ", vars(iValue)%croCodeBites(iCRO:iCRO).eq."c"
       !D           write (6,*) " is R? ", vars(iValue)%croCodeBites(iCRO:iCRO).eq."R"
       !D           write (6,*) " is r? ", vars(iValue)%croCodeBites(iCRO:iCRO).eq."r"
       !D           write (6,*) " is O? ", vars(iValue)%croCodeBites(iCRO:iCRO).eq."O"
       !D           write (6,*) " is o? ", vars(iValue)%croCodeBites(iCRO:iCRO).eq."o"
       !
       !D           write (6,*) '      cCroII: ', cCroII
       !
       If (vars(iValue)%croCodeBites(iCRO:iCRO).Eq."C") Then
          !
          iSS = iSS+1
          segList(iSS)            =  segDefault                    ! CAL COLD
          segList(iSS)%newSubscan =  .True.
          segList(iSS)%scanNumber =  nScan
          segList(iSS)%ssNumber   =  iSS
          segList(iSS)%segNumber  =  1
          segList(iSS)%ssType     =  ss%cc
          segList(iSS)%segType    =  seg%track
          segList(iSS)%angleUnit  =  aUnit
          segList(iSS)%speedUnit  =  sUnit
          segList(iSS)%flagOn     =  .False.
          segList(iSS)%flagRef    =  .False.
          If (vars(iValue)%doReference) Then
             segList(iSS)%pStart     =  vars(iValue)%offsetR
          Else If (iOTF.Eq.0) Then
             segList(iSS)%pStart     =  vars(iValue)%pStart
          Else If (vars(iValue)%croCodeBites(iCROnext:iCROnext).Eq."C") Then
             segList(iSS)%pStart%x   =  segOtfII%pEnd%x
             segList(iSS)%pStart%y   =  segOtfII%pEnd%y
          Else If (vars(iValue)%doZigzag) Then
             segList(iSS)%pStart%x   =  segOtfII%pEnd%x+vars(iValue)%delta%x
             segList(iSS)%pStart%y   =  segOtfII%pEnd%y+vars(iValue)%delta%y
          Else
             segList(iSS)%pStart%x   =  segOtfII%pStart%x+vars(iValue)%delta%x
             segList(iSS)%pStart%y   =  segOtfII%pStart%y+vars(iValue)%delta%y
          End If
          segList(iSS)%pEnd       =  segList(iSS)%pStart
          segList(iSS)%speedStart =  0.0
          segList(iSS)%speedEnd   =  0.0
          ! TBD: systemName in case of REF sysem .NE. OTF system
          segList(iSS)%systemName =  vars(iValue)%systemName
          segList(iSS)%altOption  =  'tSegment'
          ! TBD: time from CALIBRATE
          segList(iSS)%tSegment   =  5.0
          segList(iSS)%tRecord    =  vars(iValue)%tRecord
          Write (messageText,*)  "  subscan #:   ", iSS, " ",                    &
               &           segList(iSS)%ssType                                   !
          Call pakoMessage(priorityI,severityI,"OTFMAP "//" Analyze",messageText)
          !
          iSS = iSS+1
          segList(iSS)            =  segList(iSS-1)                ! CAL AMBIENT
          segList(iSS)%ssNumber   =  iSS
          segList(iSS)%ssType     =  ss%ca
          Write (messageText,*)  "  subscan #:   ", iSS, " ",                    &
               &           segList(iSS)%ssType                                   !
          Call pakoMessage(priorityI,severityI,"OTFMAP "//" Analyze",messageText)
          !
          iSS = iSS+1
          segList(iSS)            =  segList(iSS-1)                ! CAL SKY
          segList(iSS)%ssNumber   =  iSS
          segList(iSS)%ssType     =  ss%cs
          Write (messageText,*)  "  subscan #:   ", iSS, " ",                    &
               &           segList(iSS)%ssType, segList(iSS)%pStart              !
          Call pakoMessage(priorityI,severityI,"OTFMAP "//" Analyze",messageText)
          !
          cCroII = vars(iValue)%croCodeBites(iCRO:iCRO)
          !
       End If
       !
       If (vars(iValue)%doReference .And.                            &
            &         vars(iValue)%croCodeBites(iCRO:iCRO).Eq."R") Then
          !
          Call countSubscans(ii)
          Call countSegments(jj)
          !
          iSS = iSS+1
          segList(iSS)            =  segDefault                    ! REFERENCE
          segList(iSS)%newSubscan =  .True.
          segList(iSS)%scanNumber =  nScan
          segList(iSS)%ssNumber   =  iSS
          segList(iSS)%segNumber  =  1
          segList(iSS)%ssType     =  ss%ref
          segList(iSS)%segType    =  seg%track
          segList(iSS)%angleUnit  =  aUnit
          segList(iSS)%speedUnit  =  sUnit
          segList(iSS)%flagOn     =  .False.
          segList(iSS)%flagRef    =  .True.
          segList(iSS)%pStart     =  vars(iValue)%offsetR
          segList(iSS)%pEnd       =  vars(iValue)%offsetR
          ! TBD: system name for REF
          segList(iSS)%systemName =  vars(iValue)%systemName
          segList(iSS)%altOption  =  'tSegment'
          segList(iSS)%speedStart =  0.0
          segList(iSS)%speedEnd   =  0.0
          segList(iSS)%tSegment   =  vars(iValue)%tReference
          segList(iSS)%tRecord    =  vars(iValue)%tRecord
          !
          If (GV%doDebugMessages) Then
             Write (messageText,*)  " s #:   ", iSS, " ", segList(iSS)%ssType
             Call pakoMessage(priorityI,severityI,"OTFMAP - Analyze",messageText)
             Write (messageText,*)  "  ___ flagOn ",   segList(iSS)%flagOn,      &
                  &                        " flagRef ",  segList(iSS)%flagRef    !
             Call pakoMessage(priorityI,severityI,"OTFMAP - Analyze",messageText)
             Write (messageText,*)  "  ___ position [arcsec] ",                  &
                  &                             segList(iSS)%pStart              !
             Call pakoMessage(priorityI,severityI,"OTFMAP - Analyze",messageText)
             Write (messageText,*)  "  ___ tSegment [s]",                        &
                  &                                        segList(iSS)%tSegment !
             Call pakoMessage(priorityI,severityI,"OTFMAP - Analyze",messageText)
          End If
          !
          cCroII = vars(iValue)%croCodeBites(iCRO:iCRO)
          !
       End If
       !
       If (vars(iValue)%croCodeBites(iCRO:iCRO).Eq."O") Then
          !
!!$          Call countSubscans(ii)
!!$          Call countSegments(jj)
          !
          iSS  = iSS+1
          iOTF = iOTF+1
          If (iOTF.Eq.1) Then
             segOtfII            =  segDefault                    ! first OTF
             segList(iSS)%newSubscan =  .True.
             segOtfII%scanNumber =  nScan
             segOtfII%ssNumber   =  iSS
             segOtfII%segNumber  =  1
             segOtfII%ssType     =  ss%otf
             segOtfII%segType    =  seg%linear
             segOtfII%angleUnit  =  aUnit
             segOtfII%speedUnit  =  sUnit
             segOtfII%flagOn     =  .True.
             segOtfII%flagRef    =  .False.
             segOtfII%pStart     =  vars(iValue)%pStart  
             segOtfII%pEnd       =  vars(iValue)%pEnd  
             segOtfII%lengthOtf  =  vars(iValue)%lengthOtf
             segOtfII%systemName =  vars(iValue)%systemName
             segOtfII%altOption  =  vars(iValue)%altOption
             segOtfII%speedStart =  vQuant
             segOtfII%speedEnd   =  vQuant
             segOtfII%tSegment   =  tQuant
!!$             segOtfII%speedStart =  vars(iValue)%speedStart
!!$             segOtfII%speedEnd   =  vars(iValue)%speedEnd
!!$             segOtfII%tSegment   =  vars(iValue)%tOtf
             segOtfII%tRecord    =  vars(iValue)%tRecord
!!$             segList(iSS)        =  segOtfII
          Else                                                 ! More OTF
             segOtfII%ssNumber   =  iSS
             If (vars(iValue)%doZigzag) Then
                pII              =  segOtfII%pStart
                segOtfII%pStart  =  segOtfII%pEnd
                segOtfII%pEnd    =  pII
             End If
             segOtfII%pStart%x   =  segOtfII%pStart%x+vars(iValue)%delta%x
             segOtfII%pStart%y   =  segOtfII%pStart%y+vars(iValue)%delta%y
             segOtfII%pEnd%x     =  segOtfII%pEnd%x  +vars(iValue)%delta%x
             segOtfII%pEnd%y     =  segOtfII%pEnd%y  +vars(iValue)%delta%y
!!$             segList(iSS)        =  segOtfII
          End If
          !

          !    ** lead-in and ramps 2014-09                                      !  !! 
          !
          If ( Index(GV%testMode,"lead").Ge.1 ) Then                             !  !!    lead-in
             !
             If (GV%doDebugMessages) Then
                Write (6,*) "      analyzeOtfMap: GV%testMode:   ", GV%testMode
                Write (6,*) "      --> will prepare lead-in before OTF subscans "
             End If
             !
             pStart   = segOtfII%pStart
             vStart%x = vars(iValue)%speedStart                                  &
                  &        * (segOtfII%pEnd%x-segOtfII%pStart%x)                 &
                  &        / segOtfII%lengthOtf                                  !
             vStart%y = vars(iValue)%speedStart                                  &
                  &        * (segOtfII%pEnd%y-segOtfII%pStart%y)                 &
                  &        / segOtfII%lengthOtf                                  !
             vStart%speed = sqrt(vStart%x**2+vStart%y**2)
             !
             tLead  =  1.5                                                       !  !!  TBD: test /optimize
             !
             If ( tLead.Lt.1.0 ) Then
                tLead = 1.0
             End If
             !
             pLead %x = pStart%x -vstart%x*tLead
             pLead %y = pStart%y -vstart%y*tLead
             !
             lLead  = sqrt((pStart%x-pLead %x)**2 + (pStart%y-pLead %y)**2 )
             !
          Else
             !
             pStart   = segOtfII%pStart
             vStart%x = vars(iValue)%speedStart                                  &
                  &        * (segOtfII%pEnd%x-segOtfII%pStart%x)                 &
                  &        / segOtfII%lengthOtf                                  !
             vStart%y = vars(iValue)%speedStart                                  &
                  &        * (segOtfII%pEnd%y-segOtfII%pStart%y)                 &
                  &        / segOtfII%lengthOtf                                  !
             vStart%speed = sqrt(vStart%x**2+vStart%y**2)
             !
             tLead    =  0.0
             !
             pLead %x = pStart%x
             pLead %y = pStart%y
             !
             lLead    = 0.0
             !
          End If   !!   ( Index(GV%testMode,"lead").Ge.1 )
          !
          If (GV%doDebugMessages) Then
             Write (6,*) "            pStart    ", pStart
             Write (6,*) "            vStart    ", vStart
             Write (6,*) "            tLead     ", tLead
             Write (6,*) "            pLead     ", pLead 
             Write (6,*) "            lLead     ", lLead 
          End If
          !
          If ( Index(GV%testMode,"rampup").Ge.1 ) Then                           !  !!    
             !
             If (GV%doDebugMessages) Then
                Write (6,*) "      analyzeOtfMap: GV%testMode:   ", GV%testMode
                Write (6,*) "      --> will insert ramp up before OTF subscans "
             End If
             !
             pStart   = pLead
             vStart%x = vars(iValue)%speedStart                                  &
                  &        * (segOtfII%pEnd%x-segOtfII%pStart%x)                 &
                  &        / segOtfII%lengthOtf                                  !
             vStart%y = vars(iValue)%speedStart                                  &
                  &        * (segOtfII%pEnd%y-segOtfII%pStart%y)                 &
                  &        / segOtfII%lengthOtf                                  !
             vStart%speed = sqrt(vStart%x**2+vStart%y**2)
             !
             accelMax = 0.03*degree                                       !  maximum aceleration in [rad/s^2]
             tAccel   = Int(vStart%speed*GV%angleUnit/accelMax) + 1.0     !  TBD: use max accel. from globals
             !
             If ( tAccel.Lt.3.0 ) Then
                tAccel = 3.0
             End If
             !
             pAccel%x = pLead%x -0.5*vstart%x*tAccel
             pAccel%y = pLead%y -0.5*vstart%y*tAccel
             !
             lAccel = sqrt((pLead%x-pAccel%x)**2 + (pLead%y-pAccel%y)**2 )
             !
             If (GV%doDebugMessages) Then
                Write (6,*) "            pStart          ", pStart
                Write (6,*) "            vStart          ", vStart
                Write (6,*) "            vStart%speed    ", vStart%speed
                Write (6,*) "            tAccel          ", tAccel
                Write (6,*) "            pAccel          ", pAccel
                Write (6,*) "            lAccel          ", lAccel
             End If
             !
             Call countSubscans(ii)
             Call countSegments(jj)
             !
             segList(jj)              =  segOtfII
             segList(jj)%newSubscan   =  .True.
             !
             segList(jj)%pStart       =  pAccel 
             segList(jj)%pEnd         =  pLead
             segList(jj)%speedStart   =  0.0
             segList(jj)%speedEnd     =  vStart%speed   + 0.01                   !  !!  TBD 2014: experiment /test how much to add
             segList(jj)%tSegment     =  tAccel
             !
             segList(jj)%flagDropin   =  .True.
             segList(jj)%lengthOtf    =  lAccel
             !
          End If   !!   ( Index(GV%testMode,"rampup").Ge.1 )

          If ( Index(GV%testMode,"lead").Ge.1 ) Then                             !  !!    lead-in
             !
             If (GV%doDebugMessages) Then
                Write (6,*) "      analyzeOtfMap: GV%testMode:   ", GV%testMode
                Write (6,*) "      --> will insert lead-in before OTF subscans "
             End If
             !
             Call countSubscans(ii)
             Call countSegments(jj)
             !
             segList(jj)              =  segOtfII
             segList(jj)%newSubscan   =  .False.
             !
             segList(jj)%pEnd         =  segList(jj)%pStart
             segList(jj)%pStart       =  pLead  
             segList(jj)%speedEnd     =  segList(jj)%speedStart   + 0.01         !  !!  TBD 2014: experiment /test how much to add
             segList(jj)%speedStart   =  segList(jj)%speedEnd
             segList(jj)%tSegment     =  tLead
             segList(jj)%flagDropin   =  .True.
             !
             If ( Index(GV%testMode,"rampup").Ge.1 ) Then
                segList(jj)%newSubscan =  .False.
             Else
                segList(jj)%newSubscan =  .True.
             End If
             segList(jj)%lengthOtf    =  lLead 
             !
          End If

          !
          Call countSubscans(ii)
          Call countSegments(jj)
          !
          segList(jj)              =  segOtfII
          !
          If       (       Index(GV%testMode,"lead").Ge.1                        &
               &      .Or. Index(GV%testMode,"rampup").Ge.1                      &
               &   )  Then                                                       !
             segList(jj)%newSubscan =  .False.
          Else
             segList(jj)%newSubscan =  .True.
          End If
          !



!!OLD !!$          vStart%x = segOtfII%speedStart                                      &
!!OLD !!$          vStart%y = segOtfII%speedStart                                      &
!!OLD !!$             If ( tAccel.Lt.vars(ivalue)%tRampUp ) Then
!!OLD !!$                !D                 Write (6,*) "             tAccel:    ", tAccel,                  &
!!OLD !!$                !D                      &      " will be increased to ", vars(ivalue)%tRampUp       !
!!OLD !!$                tAccel = vars(ivalue)%tRampUp
!!OLD !!$             If (vars(ivalue)%doInternal) Then 
!!OLD !!$                pAccel%x = pStart%x +0.5*vstart%x*tAccel
!!OLD !!$                pAccel%y = pStart%y +0.5*vstart%y*tAccel
!!OLD !!$             Else
!!OLD !!$             End If
!!OLD !!$             !


!!$          If ( Index(GV%testMode,"lead").Ge.1 ) Then                             !  !!    
!!$             !
!!$             Write (6,*) "      analyzeOtfMap: GV%testMode:   ", GV%testMode
!!$             Write (6,*) "      --> will insert lead-in before OTF subscans "
!!$             !
!!$             pStart   = segOtfII%pStart
!!$!!OLD !!$          vStart%x = segOtfII%speedStart                                      &
!!$             vStart%x = vars(iValue)%speedStart                                  &
!!$                  &        * (segOtfII%pEnd%x-segOtfII%pStart%x)                 &
!!$                  &        / segOtfII%lengthOtf                                  !
!!$!!OLD !!$          vStart%y = segOtfII%speedStart                                      &
!!$             vStart%y = vars(iValue)%speedStart                                  &
!!$                  &        * (segOtfII%pEnd%y-segOtfII%pStart%y)                 &
!!$                  &        / segOtfII%lengthOtf                                  !
!!$             vStart%speed = sqrt(vStart%x**2+vStart%y**2)
!!$             !
!!$             Write (6,*) "            pStart    ", pStart
!!$             Write (6,*) "            vStart    ", vStart
!!$             !
!!$             tLead  =  1.5                                                       !  !!  TBD: test /investigate
!!$             !
!!$             If ( tLead.Lt.1.0 ) Then
!!$                tLead = 1.0
!!$             End If
!!$             !
!!$             pLead %x = pStart%x -vstart%x*tLead
!!$             pLead %y = pStart%y -vstart%y*tLead
!!$             !
!!$             Write (6,*) "            tLead     ", tLead
!!$             Write (6,*) "            pLead     ", pLead 
!!$             !
!!$             lLead  = sqrt((pStart%x-pLead %x)**2 + (pStart%y-pLead %y)**2 )
!!$             !
!!$             Write (6,*) "            lLead     ", lLead 
!!$             !
!!$             Call countSubscans(ii)
!!$             Call countSegments(jj)
!!$             !
!!$             segList(jj)              =  segOtfII
!!$             segList(jj)%newSubscan   =  .True.
!!$             !
!!$             segList(jj)%pEnd         =  segList(jj)%pStart
!!$             segList(jj)%pStart       =  pLead  
!!$             segList(jj)%speedEnd     =  segList(jj)%speedStart   + 0.01         !  !!  TBD 2014: experiment /test how much to add
!!$             segList(jj)%speedStart   =  segList(jj)%speedEnd
!!$             segList(jj)%tSegment     =  tLead
!!$             !
!!$             segList(jj)%flagDropin   =  .True.
!!$             segList(jj)%lengthOtf    =  lLead 
!!$             !
!!$          End If
!!$          !



!!$          If ( Index(GV%testMode,"rampup").Ge.1 ) Then                           !  !!    
!!$             !
!!$             Write (6,*) "      analyzeOtfMap: GV%testMode:   ", GV%testMode
!!$             Write (6,*) "      --> will insert ramp up before OTF subscans "
!!$             !
!!$             pStart   = segOtfII%pStart
!!$!!OLD !!$          vStart%x = segOtfII%speedStart                                      &
!!$             vStart%x = vars(iValue)%speedStart                                  &
!!$                  &        * (segOtfII%pEnd%x-segOtfII%pStart%x)                 &
!!$                  &        / segOtfII%lengthOtf                                  !
!!$!!OLD !!$          vStart%y = segOtfII%speedStart                                      &
!!$             vStart%y = vars(iValue)%speedStart                                  &
!!$                  &        * (segOtfII%pEnd%y-segOtfII%pStart%y)                 &
!!$                  &        / segOtfII%lengthOtf                                  !
!!$             vStart%speed = sqrt(vStart%x**2+vStart%y**2)
!!$             !
!!$             Write (6,*) "            pStart    ", pStart
!!$             Write (6,*) "            vStart    ", vStart
!!$             !
!!$             accelMax = 0.03*degree                                       !  maximum aceleration in [rad/s^2]
!!$             tAccel   = Int(vStart%speed*GV%angleUnit/accelMax) + 1.0     !  TBD: use max accel. from globals
!!$             !
!!$             If ( tAccel.Lt.3.0 ) Then
!!$!!OLD !!$             If ( tAccel.Lt.vars(ivalue)%tRampUp ) Then
!!$                !D                 Write (6,*) "             tAccel:    ", tAccel,                  &
!!$                !D                      &      " will be increased to ", vars(ivalue)%tRampUp       !
!!$                tAccel = 3.0
!!$!!OLD !!$                tAccel = vars(ivalue)%tRampUp
!!$             End If
!!$             !
!!$!!OLD !!$             If (vars(ivalue)%doInternal) Then 
!!$!!OLD !!$                pAccel%x = pStart%x +0.5*vstart%x*tAccel
!!$!!OLD !!$                pAccel%y = pStart%y +0.5*vstart%y*tAccel
!!$!!OLD !!$             Else
!!$             pAccel%x = pStart%x -0.5*vstart%x*tAccel
!!$             pAccel%y = pStart%y -0.5*vstart%y*tAccel
!!$!!OLD !!$             End If
!!$!!OLD !!$             !
!!$             Write (6,*) "            tAccel    ", tAccel
!!$             Write (6,*) "            pAccel    ", pAccel
!!$             !
!!$             lAccel = sqrt((pStart%x-pAccel%x)**2 + (pStart%y-pAccel%y)**2 )
!!$             !
!!$             Write (6,*) "            lAccel    ", lAccel
!!$             !
!!$             Call countSubscans(ii)
!!$             Call countSegments(jj)
!!$             !
!!$             segList(jj)              =  segOtfII
!!$             segList(jj)%newSubscan   =  .True.
!!$             !
!!$             segList(jj)%pEnd         =  segList(jj)%pStart
!!$             segList(jj)%pStart       =  pAccel 
!!$             segList(jj)%speedEnd     =  segList(jj)%speedStart   + 0.01         !  !!  TBD 2014: experiment /test how much to add
!!$             segList(jj)%speedStart   =  0.0
!!$             segList(jj)%tSegment     =  tAccel
!!$             !
!!$             segList(jj)%flagDropin   =  .True.
!!$             segList(jj)%lengthOtf    =  lAccel
!!$             !
!!$
!!$          End If   !!   ( Index(GV%testMode,"rampup").Ge.1 )



          
          If (GV%doDebugMessages) Then
             Write (messageText,*)  " s #:   ", iSS, " ", segList(iSS)%ssType
             Call pakoMessage(priorityI,severityI,"OTFMAP - Analyze",messageText)
             Write (messageText,*)  "  ___ position [arcsec] from ",             &
                  &                             segList(iSS)%pStart,             &
                  &                                           " to ",            &
                  &                             segList(iSS)%pEnd                !
             Call pakoMessage(priorityI,severityI,"OTFMAP - Analyze",messageText)
             Write (messageText,*)  "  ___ tSegment [s]",                        &
                  &                                        segList(iSS)%tSegment !
             Call pakoMessage(priorityI,severityI,"OTFMAP - Analyze",messageText)
             Write (messageText,*)  "  ___ speed [arcsec/s] from ",              &
                  &                             segList(iSS)%speedStart,         &
                  &                                           " to ",            &
                  &                             segList(iSS)%speedEnd            !
             Call pakoMessage(priorityI,severityI,"OTFMAP - Analyze",messageText)
          End If
          !
          cCroII = vars(iValue)%croCodeBites(iCRO:iCRO)
          !
       End If   !!   (vars(iValue)%croCodeBites(iCRO:iCRO).Eq."O") 
       !
    End Do   !!   While (iOTF .Lt. vars(iValue)%nOtf)
    !
    If (iSS.Ge.1) Then
       If ( .Not. vars(iIn)%doTune) Then
          segList(1)%updateDoppler = .True.                                      !  !!  normal case
          segList(1)%pDoppler      = xyPointType(0.0,0.0)
       Else
          segList(2)%updateDoppler = .True.                                      !  !!  1st subscan: NIKA tune
          segList(2)%pDoppler      = xyPointType(0.0,0.0)
       End If
    End If
    !
    nSegments = iSS
    !
    ii = vars(iValue)%croCodeCount
    If (vars(iValue)%doReference                                                 &
         &         .And.((vars(iValue)%croCodeBites(ii:ii).Eq."R"                &      
         &                   .And. (segList(nSegments)%ssType.Eq.ss%otf))        &
         &               .Or.                                                    &
         &               (vars(iValue)%croCodeBites(ii-1:ii).Eq."RC"             &      
         &                   .And. (segList(nSegments)%ssType.Eq.ss%otf))        &
         &              )                                                        &
         &        ) Then                                                         !
       !
       Call countSubscans(ii)
       Call countSegments(jj)  
       !
       iSS  = iSS+1
       segList(iSS)            =  segDefault                    ! add REFERENCE at end
       segList(iSS)%newSubscan =  .True.
       segList(iSS)%scanNumber =  nScan
       segList(iSS)%ssNumber   =  iSS
       segList(iSS)%segNumber  =  1
       segList(iSS)%ssType     =  ss%ref
       segList(iSS)%segType    =  seg%track
       segList(iSS)%angleUnit  =  aUnit
       segList(iSS)%speedUnit  =  sUnit
       segList(iSS)%flagOn     =  .False.
       segList(iSS)%flagRef    =  .True.
       segList(iSS)%pStart     =  vars(iValue)%offsetR  
       segList(iSS)%pEnd       =  vars(iValue)%offsetR  
       segList(iSS)%systemName =  vars(iValue)%systemName
       segList(iSS)%altOption  =  'tSegment'
       segList(iSS)%speedStart =  0.0
       segList(iSS)%speedEnd   =  0.0
       segList(iSS)%tSegment   =  vars(iValue)%tReference
       segList(iSS)%tRecord    =  vars(iValue)%tRecord
       !
       If (GV%doDebugMessages) Then
          Write (messageText,*)  " s #:   ", iSS, " ", segList(iSS)%ssType
          Call pakoMessage(priorityI,severityI,"OTFMAP - Analyze",messageText)
          Write (messageText,*)  "  ___ position [arcsec] ",                     &
               &                             segList(iSS)%pStart                 !
          Call pakoMessage(priorityI,severityI,"OTFMAP - Analyze",messageText)
          Write (messageText,*)  "  ___ tSegment [s]",                           &
               &                                        segList(iSS)%tSegment    !
          Call pakoMessage(priorityI,severityI,"OTFMAP - Analyze",messageText)
       End If
       !
       cCroII = vars(iValue)%croCodeBites(iCRO:iCRO)
       !
    End If
    !
    nSegments = iSS
    !
    ii = vars(iValue)%croCodeCount
    If ( vars(iValue)%croCodeBites(ii:ii).Eq."C"                  &      
         &         .And. .Not. (segList(nSegments)%ssType.Eq.ss%cs)          &
         &        ) Then
       !                                                                      ! add CAL at end
       iSS  = iSS+1
       segList(iSS)            =  segDefault                    ! CAL COLD
       segList(iSS)%newSubscan =  .True.
       segList(iSS)%scanNumber =  nScan
       segList(iSS)%ssNumber   =  iSS
       segList(iSS)%segNumber  =  1
       segList(iSS)%ssType     =  ss%cc
       segList(iSS)%segType    =  seg%track
       segList(iSS)%angleUnit  =  aUnit
       segList(iSS)%speedUnit  =  sUnit
       segList(iSS)%flagOn     =  .False.
       segList(iSS)%flagRef    =  .False.
       If (vars(iValue)%doReference) Then
          segList(iSS)%pStart  =  vars(iValue)%offsetR  
       Else
          segList(iSS)%pStart  =  segOtfII%pEnd  
       End If
       segList(iSS)%pEnd       =  segList(iSS)%pStart  
       segList(iSS)%speedStart =  0.0
       segList(iSS)%speedEnd   =  0.0
       ! TBD: case ref system
       segList(iSS)%systemName =  vars(iValue)%systemName
       segList(iSS)%altOption  =  'tSegment'
       ! TBD: time from CALIBRATE
       segList(iSS)%tSegment   =  5.0
       segList(iSS)%tRecord    =  vars(iValue)%tRecord
       Write (messageText,*)  "  subscan #:   ", iSS, " ",                       &
            &           segList(iSS)%ssType                                      !
       Call pakoMessage(priorityI,severityI,"OTFMAP "//" Analyze",messageText)
       !
       iSS = iSS+1
       segList(iSS)            =  segList(iSS-1)                ! CAL AMBIENT
       segList(iSS)%ssType     =  ss%ca
       Write (messageText,*)  "  subscan #:   ", iSS, " ",                       &
            &           segList(iSS)%ssType                                      !
       Call pakoMessage(priorityI,severityI,"OTFMAP "//" Analyze",messageText)
       !
       iSS = iSS+1
       segList(iSS)            =  segList(iSS-1)                ! CAL SKY
       segList(iSS)%ssType     =  ss%cs
       Write (messageText,*)  "  subscan #:   ", iSS, " ",                       &
            &           segList(iSS)%ssType, segList(iSS)%pStart                 !
       Call pakoMessage(priorityI,severityI,"OTFMAP "//" Analyze",messageText)
       !
       cCroII = vars(iValue)%croCodeBites(iCRO:iCRO)
       !
    End If
    !
    nSegments = iSS
    !
    Write (messageText,*)  "   number of Subscans/Segments: ", nSegments
    Call pakoMessage(priorityI,severityI,"OTFMAP "//" Analyze",messageText)
    !
    Return 
    !
  End Subroutine analyzeOtfMap
!!!
!!!
  Subroutine plotOtfMap (errorP)
    !
    !**   Variables  for Plots   ***
    Include 'inc/variables/headerForPlotMethods.inc'
    !
    !**   standard working variables   ***
    Include 'inc/variables/standardWorkingVariables.inc'
    !
    Call pako_message(seve%t,"OTFMAP",                                           &
         &  " module OtfMap, v 1.2.3 2014-12-15 --> SR: plotOtfMap ")            ! trace execution
    !
    errorP = .False.
    !
    Call configurePlots
    !
    Call plotOtfMapStart(errorP)
    !
    Call plotDIYlist(errorP)
    !
    If (errorP)                                                                  &
         &        Call pakoMessage(priorityE,severityE,                          &
         &        'OtfMap',' could not plot ')                                   !
    !
    Return
    !
  End Subroutine plotOtfMap
!!!
!!!
  Subroutine saveOtfMap(programName,LINE,commandToSave,              &
       &        iUnit, ERROR)
    !
    ! *** Variables   ***
    Include 'inc/variables/headerForSaveMethods.inc'
    !
    Call pako_message(seve%t,programName,                                        &
         &  " module OtfMap, v 1.2.3 2014-08-28 --> SR: saveOtfMap ")            ! trace execution
    !
    ERROR = .False.
    !
    contC = contNN
    !
    Include 'inc/commands/saveCommand.inc'
    !
    doContinue = .True.
    !
    contC = contCC
    !
    Include 'inc/parameters/saveStartEnd.inc'
    !
    !TBD:      Include 'inc/options/saveBalance.inc'
    Include 'inc/options/saveCroLoop.inc'
    Include 'inc/options/saveNotf.inc'
    Include 'inc/options/saveReference.inc'
    !TBD      Include 'inc/options/saveResume.inc'
    Include 'inc/options/saveStep.inc'
    Include 'inc/options/saveSystem.inc'
    Include 'inc/options/saveSpeedTotf.inc'
    ! TBD:      Include 'inc/options/saveTrecord.inc'
    Include 'inc/options/saveTreference.inc'
    !
    !D     Write (6,*) "      vars(iValue)%doTuneSet:   ", vars(iValue)%doTuneSet 
    If (.Not. vars(iValue)%doTuneSet) Then
       doContinue = .False.
       contC = contCN
    End If
    Include 'inc/options/saveZigzag.inc'
    !
    If (vars(iValue)%doTuneSet) Then
       If ( vars(iValue)%doTune) Then
          Include 'inc/options/saveTuneOffsets.inc'
          doContinue = .False.
          contC = contCN
          Include 'inc/options/saveTuneTime.inc'
       Else 
          doContinue = .False.
          contC = contCN
          Include 'inc/options/saveTuneOffsets.inc'
       End If
    End If
    !
    Write (iUnit,*) "!"
    !
    Return
  End Subroutine saveOtfMap
!!!
!!!
  Subroutine startOtfMap(programName,LINE,commandToSave,             &
       &         iUnit, ERROR)
    !
    ! *** Variables ***
    Include 'inc/variables/headerForSaveMethods.inc'
    !
    Integer                 :: ii
    Character (len=lenCh)   :: valueC
    Character (len=lenLine) :: valueComment
    Character (len=lenLine) :: messageText
    Logical                 :: errorL, errorXML
    ! 
    Logical            :: inOtfSubscan
    !
    Call pako_message(seve%t,programName,                                        &
         &  " module OtfMap, v 1.2.0 2012-02-15 ---> SR: startOtfMap ")          ! trace execution
    !
    ERROR = .False.
    ! 
    !D    Write (6,*) "   --> startOtfMap   "
    !D    Write (6,*) "   GV%observingMode ->", GV%observingMode(1:len_trim(GV%observingMode)), "<-"        
    !D    Write (6,*) "   GV%observingModePako ->", GV%observingModePako(1:len_trim(GV%observingModePako)), "<-"        
    !
    Call pakoXMLsetOutputUnit(iunit=iunit)
    Call pakoXMLsetIndent(iIndent=2)
!!OLD   Call pakoXMLsetLevel(1)
    !
    Include 'inc/startXML/generalHead.inc'
    !
    Call writeXMLset(programName,LINE,commandToSave,iUnit, ERROR)
    !
    !!! Call writeXMLversion !!! incorporated in generalHead above
    !
    Call pakoXMLwriteStartElement("RESOURCE","pakoScript",                       &
         &                         comment="save from pako",                     &
         &                         error=errorXML)                               !
    Call pakoXMLwriteStartElement("DESCRIPTION",                                 &
         &                         doCdata=.True.,                               &
         &                         error=errorXML)                               !
    !
    Include 'inc/startXML/savePakoScriptFirst.inc'
    !
    Call saveOtfMap(programName,LINE,commandToSave, iUnit, errorL)
    !                                                                       
    Call pakoXMLwriteEndElement("DESCRIPTION", error=errorXML)                                             
    Call pakoXMLwriteEndElement("RESOURCE", "pakoScript",error=errorXML)
    !
    Call writeXMLantenna(programName,LINE,commandToSave,iUnit, ERROR)
    !
    Call writeXMLreceiver(programName,LINE,commandToSave,iUnit, ERROR)
    !
    Call writeXMLbackend(programName,LINE,commandToSave,iUnit, ERROR)
    !
    Include 'inc/startXML/switchingMode.inc'
    !
    Call writeXMLsource(programName,LINE,commandToSave,iUnit, ERROR)
    !
    Include 'inc/startXML/generalScanHead.inc'
    !
    Include 'inc/startXML/conditions.inc'
    !
    ! **  Observing Mode to XML
    If (gv%doXMLobservingMode) Then
       messageText = "writing observing mode in XML format"
       Call PakoMessage(priorityI,severityI,                                     &
               &           commandToSave,messageText)                            !
       Call writeXMLotfMap(programName,LINE,commandToSave,                       &
         &         iUnit, ERROR)                                                 !
    End If
    !
    ! **  subscan list to XML
    Include 'inc/startXML/otfMapSubscansXML.inc'
    !   
    Include 'inc/startXML/generalTail.inc'
    !
    Call pako_message(seve%t,programName,                                        &
         &  " module OtfMap, <--- SR: startOtfMap ")                             ! trace execution
    !
    Return
  End Subroutine startOtfMap
!!!
!!!
  Subroutine writeXMLotfMap(programName,LINE,commandToSave,iUnit,ERROR)
    !
    ! *** Variables   ***
    Include 'inc/variables/headerForSaveMethods.inc'
    !
    Integer                 :: iMatch, nMatch, len1, len2
    Character (len=lenCh)   :: valueC, errorCode
    Character (len=lenLine) :: valueComment
    Logical                 :: errorM, errorXML
    Character (len=lenCh)   :: systemName
    !
    Call pako_message(seve%t,programName,                                        &
         &  " module OtfMap, v 1.2.3 ---> SR: writeXMLotfMap 2014-10-27")        ! trace execution
    !
    ERROR = .False.
    !
    Call pakoXMLwriteStartElement("RESOURCE","observingMode",                    &
         &                         space ="before",                              &
         &                         error=errorXML)                               !
    !
    valueC = GV%observingMode
    Call pakoXMLwriteElement("PARAM","observingMode",valueC,                     &
         &                         dataType="char",                              &
         &                         error=errorXML)                               !
    !
    Include 'inc/startXML/parametersStartEndXML.inc'
    !
    Include 'inc/startXML/optionSystemXML.inc'
    Include 'inc/startXML/optionReferenceXML.inc'
    Include 'inc/startXML/optionCroLoopXML.inc'
    Include 'inc/startXML/optionNotfXML.inc'
    Include 'inc/startXML/optionStepXML.inc'
    Include 'inc/startXML/otfmapAltOption.inc'
    Include 'inc/startXML/optionSpeedXML.inc'
    Include 'inc/startXML/optionTotfXML.inc'
    Include 'inc/startXML/optionTreferenceXML.inc'
    Include 'inc/startXML/optionZigzagXML.inc'
    !
    systemName = vars(iValue)%systemName
    If (vars(iValue)%doTune) Then 
       Include 'inc/startXML/optionTuneXML.inc'
       Include 'inc/startXML/optionTtuneXML.inc'
    End If
    !
    Include 'inc/startXML/annotationsXML.inc'
    !
    Call pakoXMLwriteEndElement("RESOURCE","observingMode",                      &
         &                         error=errorXML)                               !
    !
    Return
  End Subroutine writeXMLotfMap
!!!
!!!
End Module modulePakoOtfmap





