 subroutine fit_gains( chis_save, gain_save, const_save, covar_save)

! in this version first use g(2:4) as parameters with g(1) = 1.
! Then fit again with g(1:3) as parameters with g(4) = 1
! Gain_save(1,:) is the gains with g(1) =1.
! gain_save(4,:) is the gains with g(4) = 1.


   use bmad
   use gain_fit_mod
   use super_recipes_mod
   use cesr_read_data_mod
   use nr

   implicit none

    type (super_mrqmin_storage_struct) storage

   integer i
   integer ix
   integer det(4)
   integer j
   integer index,in
   integer m
   integer detectors(100)
   integer status
   integer monitor
   integer, save :: ref
   integer try

   logical read_current_from_butns_file

   character*100 name, file, file_fit
   character*1 answer
   real(rp) v1, v2, h1, h2, x, y
   real(rp) hscale/22./, vscale/27./, rms,chis
   real(rp) Bpmmp(4), Bppmm(4), Bpmpm(4), den/1./
   real(rp) current
   real(rp), allocatable :: xx(:), yy(:), a(:), sig(:)
  real(rp), allocatable :: covar(:,:),alpha(:,:)   
   real(rp) alambda
   real(rp) chisq
   real(rp) but(4)
   real(rp) dc_dg(5)
   real(rp) avg(3), std(3), test, b_max(3), b_min(3)
   real(rp) fit_g(4), fit_r(4), fit_gain(0:100,4), fit_rms(0:100,4), c_avg, c_sig
   real(rp) chis_1
   real(rp) gain_save(5,4), dc_dg_num(4), chis_num, chis_save(5)
   real(rp) d2c_dg2(5,5), b(5,5), gain_error(5)
   real(rp) const_save(5)
   real(rp) covar_save(1:5,1:5,1:5)
   real(rp) chis_last

   logical, allocatable ::  maska(:)
   logical just_one/.false./
   logical first/.true./
   nterms = norbits  ! + 1  20240321

      nvar = 5
      allocate(xx(1:nterms), yy(1:nterms), sig(1:nterms))
      allocate(a(1:nvar), maska(1:nvar))
      allocate(alpha(1:nvar,1:nvar), covar(1:nvar, 1:nvar))
      gain_save(:,:)=0.
      if(first)then
         !    print '(a,$)',' Set reference button to (1:4) ? '
         !    accept *,ref
         first = .false.
      endif
      do ind = 1,5
!         if(ind /= 1)cycle
         print '(/,a,i)',' ind = ',ind
         gain = [1.1,1.05,0.95,0.9]
         if(ind < 5)gain(ind)=1
         const = const_save(1)
         intercept = 0.

!         call slope(gain, const, intercept)
!         call chi_square(gain,const, chis, dc_dg)


         !      gain = gain/gain(ind)
         forall (i = 1:nterms) xx(i) = i 
         yy(1:nterms) = 0.
         sig(1:nterms) = 1.
         call gain_to_a(gain,a,ind)
         a(5) = const

         alambda = -1
         maska(:) = .true.
         maska(ind) = .false.
         
         call chi_square(gain,const, chis, dc_dg)
         print '(a9,e12.4,a,4e12.4, a8,e12.4)',' chis2 = ',chis, ' gain ', gain(1:4), ' const = ', const

         !    print '(a,e12.4,a,e12.4,a,e12.4)',' chisq = ', chisq,' chis = ', chis,  '  alambda = ', alambda
         try=0

         do i = 1,3
         maska(:)=.false.
!         maska(5) = .true.       
         in = mod(i+ind,6) + int((i+ind)/6)
         maska(in)=.true.
         maska(mod(in+1,6)+int((in+1)/6))=.true.
            call mrqmin(xx, yy, sig, a, maska,covar,alpha,chisq, mrqmin_funcs, alambda)  !fit with each of coefficients in order
            print '(a9,e12.4,a,4e12.4, a8,e12.4,a8,e12.4)',' chis2 = ',chisq, ' gain ',    a(1:4),' const = ', a(5), ' alambda = ', alambda
         end do

         alambda = 0
         call mrqmin(xx, yy, sig, a, maska,covar,alpha,chisq, mrqmin_funcs, alambda)  !fit with each of coefficients inorder
         print *,' '
         maska(:) = .true.
         maska(ind) = .false.
         alambda = -1
         
         do while(alambda < 1e10)
            call mrqmin(xx, yy, sig, a, maska,covar,alpha,chisq, mrqmin_funcs, alambda)  !fit with each of coefficients in order
            call a_to_gain(gain,a,ind)
            const = a(5)
            print '(a9,e12.4,a,4e12.4, a8,e12.4,a8,e12.4)',' chis2 = ',chisq, ' gain ',    gain(1:4),' const = ', const, ' alambda = ', alambda
            if(alambda < 1.e-21 .or. try >100)exit
            try = try+1
         end do
         alambda = 0.

         !         call super_mrqmin(yy,sig, a, chisq, mrqmin_funcs, storage, alambda, status, maska)
         call mrqmin(xx, yy, sig, a, maska,covar,alpha,chisq, mrqmin_funcs, alambda)  !fit with each of coefficients inorder
         call a_to_gain(gain,a,ind)
         const = a(5)
         gain_save(ind,1:4) = gain(1:4)
         chis_save(ind) = chisq
         const_save(ind) = const
         covar_save(ind,1:nvar,1:nvar)=covar(1:nvar,1:nvar)

         print '(a8,a9,e12.4,a,4e12.4, a8,e12.4)','final',' chis2 = ',chisq, ' gain ', gain(1:4), ' const = ', const
!  print '(a,e12.4,a,e12.4)',' chisq = ', chisq,'    chis = ',chis
!  print '(/,a)',  ' Covariance matrix '
!  print '(4e12.4)',storage%covar(1:nvar,1:nvar) 
!         call slope(gain, const, intercept)
!         call chi_square(gain,const, chis, dc_dg)
!    call h_matrix(gain, const, chis, d2c_dg2)
!    print '(a9,e12.4,a,4e12.4, a8,e12.4)',' chis2 = ',chis, ' gain ', gain(1:4), ' const = ', const
!    print '(a,4e12.4)',' dc_dg = ',dc_dg(1:4)
!    print '(i4,4e12.4, a8,e12.4)',bpm, gain(1)/gain(1:4), ' const = ', const
!    print '(/,a)',' h_matrix'
!    print '(4e14.6)',d2c_dg2(1:4,1:4)
!    print '(a,4e14.6)',' sigma = ',(sqrt(2*chis/d2c_dg2(i,i)),i=1,4)
!    b(1:5,1)=1.
!    call gaussj(d2c_dg2, b)
!    print '(/,a)','inverse h_matrix'
!    print '(4e14.6)',d2c_dg2(1:4,1:4)
!    do i=1, 5
!     gain_error(i)= sqrt(abs(2*chis*d2c_dg2(i,i)))
!    end do
!    print '(a,4e14.6)',' sigma = ',gain_error


! write(26, '(i4,11e12.4)')bpm,  b_max, b_min, gain(1)/gain, const 
! write(27, '(i4,9e12.4)')bpm, gain(1)/gain, chis, gain_error

      end do !ind 

     deallocate(xx, yy, sig)
     deallocate(a, maska)

 end

!***************************************************************

subroutine read_orbit(orbit, detect, current)

use precision_def
use gain_fit_mod

implicit none

! type bpm_struct
!  integer  button(4)
!   real(rp) x,y, phase_h, phase_v
! end type

  type(bpm_struct) detect(0:120)

  integer orbit
  integer det, ok
  integer Elec_ind, Pos_ind
  integer ierr

  real(rp) elec_cur(9), pos_cur(9)
  real(rp) current

  character*100 prefix, file, line, short_line
  character*6 word
  character*2 subdir

  write(word,'(i6)')orbit
  subdir = word(2:3)
  prefix = '/nfs/cesr/mnt/orbit/'//subdir//'/'

  write(file,'(a23,a6,i6)')trim(prefix),'butns.',orbit

!  print *, file

  do  while(.true.)
   read(1,'(a)')line
   Elec_ind = index(line,'E T1')
   Pos_ind = index(line, 'P T1')
   if(Elec_ind/= 0)read(line(elec_ind+7:),*)elec_cur
   if(Pos_ind/= 0)read(line(pos_ind+7:),*)pos_cur
   if(line(1:1) == 'c')cycle
!   read(1,'(a)')line
!   print *,line
   read(line,*)det,detect(det)%button(1:4),ok
!   print *,det, detect(det)%button
   if(det == 100)exit
  end do
  close(unit=1)  
  current = elec_cur(1)+pos_cur(1)
 return
 end
!
!***************************************************
!
subroutine read_turn_by_turn

use precision_def
use gain_fit_mod

implicit none

  integer orbit
  integer det, ok
  integer ix
  integer i
  integer j !, dets(100)
  integer m
  integer turn, phase_h, phase_v
  integer ios

  real(rp) current
  real(rp) button(4),x,y
  real(rp) pedestal(4)
!  real(rp) f/10000./
  real(rp) f/1./

  character*140 file, line, bpm_name, string
  character*140 new_file

  logical next_bpm/.true./

  do m=0,100
   orbit_data(1)%detector(m)%button(1:4) = 0
  end do

  print '(a)',in_file
  file = in_file 
  open(unit=1,file = file, type= "old", readonly, IOSTAT=ios )
  if(ios  /= 0)then
   ix = index(file,'/archive')
   new_file = file(1:ix-1)//file(ix+8:)
   print '(a)',new_file
   open(unit=1,file = new_file, type= "old", readonly, IOSTAT=ios)
  endif
 
  j=0
  do  while(.true.)
   read(1,'(a)', end =99)line
!   if(index(line, 'CERN Current Reading')/= 0)then
!      read(1,'(a)')line
!      read(line(2:),*)ix,current
!   endif
   current = 1.
   if(index(line,'Location') /= 0 .or. index(line,'LOCATION') /= 0)then
      ix = index(line,':')
      read(line(ix+2:),*)bpm_name
      call string_trim(bpm_name,bpm_name,ix)
      read(bpm_name(1:ix-1),'(i)')bpm
      if(bpm_name(ix:ix) == 'E')bpm = 99-bpm
!      print *,bpm_name, bpm
       j = j+1
       dets(j) = bpm       
      i=0
      next_bpm = .true.
      cycle
   endif
   if(index(line, 'Pedestal') /= 0)then
     read(1,'(a)') line
     read(1,'(a)') line
     read(line(13:),*) pedestal(3), pedestal(1), pedestal(2), pedestal(4)
!    print '(a12,4f12.4)',' Pedestal = ', pedestal
    cycle
   endif

!   if(index(line,'Phase Data')/=0)then
!    next_phase = .false.
!    cycle
!   endif

   if(index(line,'#') /= 0 .and. index(line,'--- Bunch 1 ---') == 0)cycle
   if(line(1:10) == '          ')cycle
   if(index(line,'--- Bunch 1 ---'))then
     next_bpm=.false.
     cycle
   endif
   if(next_bpm)cycle

   i = i + 1
   if(i > 10000)then
     print '(a)',' i > 1000 in subroutine read_turn_by_turn '
      exit
   endif

!   print *,i, line
    x=0
    y=0
    phase_h=0
    phase_v=0
    if(index(in_file,'RDe')/= 0)then
     read(line, *,iostat=ios)button(3), button(1), button(2), button(4),x,y
    else
     read(line, *,iostat=ios)button(3), button(1), button(2), button(4),x,y,turn,phase_h,phase_v
    endif
   if(ios /= 0)cycle
   if(any(abs(button(1:4)) < 100))cycle
   orbit_data(i)%detector(bpm)%button(1:4) = abs(button(1:4)*1000) !-pedestal(1:4))*f
   orbit_data(i)%detector(bpm)%x = x
   orbit_data(i)%detector(bpm)%y = y
   orbit_data(i)%detector(bpm)%phase_h = phase_h*twopi/512
   orbit_data(i)%detector(bpm)%phase_v = phase_v*twopi/512
!   print *,det, detector(det)%button
   orbit_data(i)%current = current
   norbits = i
  if(i == 1 .and. bpm == 50 )print '(6i)',i,bpm,orbit_data(i)%detector(bpm)%button(1:4)
  end do

99 continue
  close(unit=1)  

 return
 end

!
!***************************************************
!
subroutine read_turn_by_turn_cbpm1

use precision_def
use gain_fit_mod

implicit none

  integer orbit
  integer det, ok
  integer ix
  integer i
  integer j !, dets(100)
  integer bpm_last
  integer ix1, ixw, ixe
  integer turn

  real(rp) current
  real(rp) button(4)
  real(rp) pedestal(4)
  real(rp)r1,r2,r3
  integer i1,i2,i3,i4,i5
  character h1,h2,h3,h4

  character*100 file, bpm_name, string
  character*230 line

  file = in_file

  open(unit=1,file = file, type= "old", readonly)

   bpm_last=-1
   j=0
   do  while(.true.)
   read(1,'(a)', end =99)line
   if(index(line,'CESR BPM Raw')/=0)cycle
   if(index(line,'NUM ACTIVE')/=0)cycle
   current = 1.
   call string_trim(line, line, ix1)
   ix=index(line,'CESR BPM')
   if(ix == 0)cycle
      read(line(1:ix1),'(i)')turn 
      i = 1+turn
      line = line(ix+8:)
      ixw = index(line(1:8),'W')
      ixe = index(line(1:8),'E')
      ix=max(ixw,ixe)
      read(line(ix-2:ix-1),'(i)')bpm
      if(ixe /= 0)bpm=99-bpm
      if(bpm /= bpm_last)then
       j=j+1
      endif
      bpm_last = bpm
      read(line(ix+1:), *)r1,r2,r3,i1,h1,h2,h3,h4, i2,i3,i4,i5,button(3), button(1), button(2), button(4)
!   if(any(button(1:4) < 100))cycle
      orbit_data(i)%detector(bpm)%button(1:4) = button(1:4)*10000
!      print *,bpm, orbit_data(i)%detector(bpm)%button
      orbit_data(i)%current = current
      norbits = i
  end do

99 continue
  close(unit=1)  

 return
 end

!******************************************************************

 subroutine get_fake_data
    use bmad
   use gain_fit_mod

   implicit none

   integer ios
   integer i
   integer j

   character*100 name, file, file_fit
   real(rp)  x, y, but(4)
   
  
  file = 'fake.dat'
  print '(a,$)',' Fake file name (e.g. fake.dat) '
  accept *, file
  open(unit = 1, file = file, status='old', iostat=ios)

  i=1
  bpm = 1

  do 
   if(i>1000)exit
   read(1,*,end=99)j, x,y, but(1:4)
   print '(i,2e12.4,2x,4e12.4)',j,x,y,but
!   if(abs(x) > 6 .or. abs(y) > 6)cycle
   orbit_data(i)%detector(bpm)%x = x
   orbit_data(i)%detector(bpm)%y = y
   orbit_data(i)%detector(bpm)%button(1:4) = 1000000 * but(1:4)
   orbit_data(i)%current = 1.
   i=i+1
  end do

99 continue
  norbits = min(1000,i-1)

  return

 end

!****************************************************************************8

subroutine get_turn_by_turn(directory, max_nonlin_positions)

  use precision_def
  use gain_fit_mod
  use tbt_mod
  use cesr_read_data_mod
  use tbt_interface

 implicit none

 type (tbt_all_data_struct) tbt
 character*100  out_file
 character*3 subdir
 character*100 file
 character*100 string, def_file_name/' '/
 character*3 answer
 character*100 def_arb_name/'manual_gain_set.dat'/
 character*100 junk
 character*10 bunch_word

 character*16 directory
 
! integer dets(100)
 integer ix
 integer number/0/
 integer ios, i
 integer iu, tbt_file_type ! type 1 cbpm1, type 2 cbpmii before 3/25/2011, type 3 cbpmiii after 3/25/2011, type 4 cbpmii RDe
 integer dummy
 integer arb_but(0:120)
 integer m,j
 integer one_lower
 integer bunch, bunch_ix, ped_bunch, ped_bunch_ix
 integer max_turns
 integer, save :: lun
 integer max_nonlin_positions

 logical init_needed/.true./,err/.false./

 real(rp) but(4)
! real(rp) arb_gain(1:4,0:120)
 
!   if(index(in_file_0,'e.') == 0)then
    call number_to_true_number(number, 'TBT', number,err, .true.) 
    write(def_file_name,'(i6)')number
    if(def_file_name == ' ')def_file_name = trim(in_file_0) 
!   print '(a,$)',' Turn by turn data file ? e.g. "RD-000652.dat" , or "0652", or "0"  '
!   file_name = trim(in_file_0)
   print '(a,a)',' file_name = ', trim(def_file_name)
   call read_string(' Turn by turn data file ? (def = '//trim(def_file_name)//') ',def_file_name, string) 
!   print '(a,a,a,$)',' Turn by turn data file ? ',trim(in_file_0),' '
!   read(*,'(a)')string
    print '(a,a)',' file_name = ', trim(string)
   call string_trim(string,string, ix)
   if(ix /= 0 .and. ix /= len(string))in_file_0 = string
   def_file_name = string

   number=-999999
   if(ix == 1)then
     number = 0
   elseif(in_file_0(1:1) == '-')then
     read(in_file_0(1:ix),'(i)')number
   elseif(ix==4)then
      read(in_file_0(1:4),'(i4)')number
      in_file_0 = 'RD-00'//in_file_0(1:4)//'.dat'     
   elseif(ix==5)then
      read(in_file_0(1:5),'(i5)')number
      in_file_0 = 'RD-0'//in_file_0(1:5)//'.dat'     
   elseif(ix==6)then
      read(in_file_0(1:6),'(i6)')number
      in_file_0 = 'RD-'//in_file_0(1:6)//'.dat'     
   endif
   print '(a,i,a,i)',' number = ', number
   one_lower = number
   if(number>-999999)then
      call number_to_true_number(number, 'TBT', number,err, .true.) 
   if(one_lower <= 0)number = number - 1
   endif
   in_file = in_file_0
   print '(a,a,a,i)',' in_file = ', trim(in_file), ' true number = ', number 
   call string_trim(in_file, in_file, ix)

!   if(index(in_file, 'RD-')/= 0)then
   if(number > -999999 )then
     tbt_file_type = 2
     iu = lunget()
     subdir = in_file(5:6)
     if(in_file(4:4)/='0')subdir=in_file(4:6)
     in_file = '/nfs/cesr/archive/instr/cbpm_data/tsharc/raw/'//subdir//'/'//in_file(1:ix)
     open(unit=iu, file=in_file, status='OLD', iostat=ios)

    tbt_file_type = 2

     if(ios ==0)then
      do i=1,10
       read(iu,'(a)')string
       if(index(string,'File_Version') /= 0 .and. index(string,'3')/= 0)tbt_file_type = 3
      end do
      close(unit= iu)
     else
      tbt_file_type=3
    endif
   endif
!  tbt_file_type=3
   if(in_file(1:3) == 'RDe')then
     tbt_file_type = 4
     subdir = in_file(6:7)
     in_file = '/nfs/cesr/archive/instr/cbpm_data/tsharc/raw/'//subdir//'/'//in_file(1:ix)
   endif
   if(in_file(1:4) == 'cbpm')then
     tbt_file_type = 1
     subdir = in_file(6:7) 
     in_file = '/nfs/cesr/archive/instr/cbpm_data/sharc/raw/'//subdir//'/'//in_file(1:ix)
   endif

if(tbt_file_type /= 3)print '(a,a)',' in_file = ', in_file
 
   dets(1:100)=0
    print *,' tbt_file_type = ', tbt_file_type
   select case(tbt_file_type)
     case(1)
      call read_turn_by_turn_cbpm1
    case(2)
     call read_turn_by_turn
    case(3)
     gain_correct = gain_and_pedestal_correct$
     print '(a)',' Correct tbt data for gain and pedestal ? '
     print '(a,$)',' (1=no_correct, 2=pedestal correct, 3=gain and pedestal correct ) '
     read(*,'(i)')dummy
     select case(dummy)
      case(1)
        gain_correct = no_correct$
      case(2)
        gain_correct = pedestal_correct$
      case(3)
        gain_correct = gain_and_pedestal_correct$
     end select
     
     print '(a,i)',' gain correct = ', dummy

     call tbt_read_data_file(number, gain_correct, .true., tbt, err, use_last_turn = .true., tbt_nturn_avg=max_nonlin_positions)
     print '(a,i7,a,es12.3)',' Success reading file ',number, ' total_current= ',tbt%total_current
     
     if(err)then
         print '(a,i7)',' error reading file ', number
         stop
     endif

     call tbt_read_data_file(number-1, gain_correct, .false., tbt, err, use_last_turn = .true.,  tbt_nturn_avg = max_nonlin_positions)
     print '(a,i7,a,es12.4)',' Success reading file ',number-1, ' total_current= ',tbt%total_current
     
     if(err)then
         print '(a,i7)',' error reading file ', number-1
         stop
     endif

     bunch=1
10   print '(a,$)',' Bunch number? '
     read(5,*) bunch_word
     if(bunch_word(1:3) /= '   ')read(bunch_word,*)bunch
     print '(a,i10)',' bunch = ', bunch
     print '(a,$)','Pedestal bunch number ? (0 if none)'
     read(5,*) bunch_word
     if(bunch_word(1:3) /= '   ')read(bunch_word,*)ped_bunch
     print '(a,i10)',' pedestal bunch = ', ped_bunch
     ped_bunch_ix = 0
     bunch_ix = 0
     do i=1,size(tbt%bunch(:))
      if(bunch == (tbt%bunch(i)%ix_bunch+1)/2)bunch_ix = i
      if(ped_bunch == (tbt%bunch(i)%ix_bunch+1)/2)   ped_bunch_ix = i
     end do
     if(bunch_ix == 0)then
      print '(a,i10,60i5)',' there is data for bunches ', (tbt%bunch(1:size(tbt%bunch(:)))%ix_bunch+1)/2
      print '(a)',' try again'
      goto 10
     endif
     if(ped_bunch_ix == 0) print *,' There is no pedestal bunch'
     call read_turn_by_turn_3(tbt,bunch_ix, ped_bunch_ix)
     call write_rdfile_list(number, directory)
     call write_rdfile_list(number-1, directory)
  end select

! here we want to have the option to read a file with arbitrary multipliers for each BPM button
! and apply to the data

   answer = 'N'
   if(expert)then 
     print '(a,$)',' Read file of arbitrary multipliers ? '
     read(5,*)answer
   endif
   if(answer(1:1) == 'y' .or. answer(1:1) == 'Y')then
    print '(a,a)',' file_name = ', trim(def_arb_name)
    call read_string(' Manual gain set file ? (def = '//trim(def_arb_name)//') ',def_arb_name, string) 
    open(unit = iu, file = trim(string), readonly)
! read multipliers
    arb_gain(1:4,0:120) = 1.
    i=0
    do while(.true.)
     i=i+1
     read(iu,'(a)', end=99)string
    print '(a)',string
     if(index(string(1:5),'!')/= 0)cycle

     read(string,*, end=99)arb_but(i), arb_gain(1:4,i)

     arb_gain(1:4,arb_but(i)) = arb_gain(1:4,i) ! index gains by button
     print '(i,4f12.4)', arb_but(i),arb_gain(1:4,arb_but(i))
                         
    end do
99 continue

! apply multipliers
     do bpm = 0,120
       do i =1,norbits
         orbit_data(i)%detector(bpm)%button(1:4) =  arb_gain(1:4,bpm)*orbit_data(i)%detector(bpm)%button(1:4)
       end do
     end do

   print *,' arbitrary multipliers applied'
  endif   !end of loop to apply arbitrary multipliers

  return
  end

!*****************************************************************

 subroutine read_turn_by_turn_3(tbt,nbunch, empty_bunch)

   use fio   
   use precision_def
   use gain_fit_mod
   use tbt_mod

 implicit none

 type (tbt_all_data_struct) tbt
 integer j,m,i
 integer nbunch, empty_bunch
 integer iturns
 integer, save :: norbits_save(0:120)
 integer itot
 integer number_of_turns
 integer, save :: max_turns
 
 real(rp) but(1:4), current
 real(rp) but_ped(1:4)
 logical first/.true./

 if(first)then
    norbits_save(:)=0
    max_turns=0
    number_of_turns=0
    do i=0,120
       number_of_turns = max(size(tbt%bunch(nbunch)%bpm(i)%turn), number_of_turns)
    end do    
    print '(i10,a)', number_of_turns,' turns collected'
    call in4get('Limit turns to: (CR use all)  ',max_turns)
    first=.false.
 endif
 

! current=1.

  do m=0,120
   orbit_data(1)%detector(m)%button(1:4) = 0
  end do
  j=0
  do bpm=0,120
     bpm_names(bpm) = tbt%bpm(bpm)%name
     if(tbt%bunch(nbunch)%bpm(bpm)%data_ok == .false.)cycle
     !      print '(a,i10)', ' bunch ', (tbt%bunch(nbunch)%ix_bunch+1)/2
     j=j+1
     dets(j) = bpm
     i=0
     itot = 0 !norbits_save(bpm)
     number_of_turns = size(tbt%bunch(nbunch)%bpm(bpm)%turn)
     if(max_turns /= 0)number_of_turns = min(number_of_turns,max_turns)
     do iturns = 1, number_of_turns
        if(empty_bunch /= 0)then
           but_ped(1:4)=tbt%bunch(empty_bunch)%bpm(bpm)%turn(iturns)%button(1:4)
        else
           but_ped(1:4) = 0
        endif

        but(1:4) = tbt%bunch(nbunch)%bpm(bpm)%turn(iturns)%button(1:4) - but_ped(1:4)
        !       print '(a,i,4e12.4)', ' but ',bpm, but(1:4)
        if(any(abs(but(1:4)) < 100))cycle
        i=i+1
        itot=itot+1
        orbit_data(itot)%detector(bpm)%button(1:4) = nint(abs(but(1:4))*1000)
        orbit_data(itot)%detector(bpm)%x = tbt%bunch(nbunch)%bpm(bpm)%turn(i)%x
        orbit_data(itot)%detector(bpm)%y = tbt%bunch(nbunch)%bpm(bpm)%turn(i)%y
        orbit_data(itot)%current = tbt%total_current
        norbits_save(bpm)=itot
        norbits = itot
     end do
  end do
!  print '(a,4i)',' get_turn_by_turn ,1,50 ',orbit_data(1)%detector(50)%button(1:4)


 return

 end

!***********************************************************

subroutine get_orbit_data

 use gain_fit_mod
 implicit none

   integer fit_bpm_idx(0:100)/101* -1/, orbit(1000),sigma_cutoff, chisq_cutoff

   integer ios
   integer i
   integer ix
   integer det(4)
   integer j
   integer bpm_index
!   integer dets(100)

   logical read_current_from_butns_file
   character*100 line
   character*100  name, file, file_fit, out_file
   character*1 answer

   namelist /bpm_gain_anal_params/ fit_bpm_idx, read_current_from_butns_file, sigma_cutoff, chisq_cutoff, orbit

    do 

      print '(a)', ' Input command file ? '
      print '(a )', ' This can be a bpm gain anal input file, e.g. "bpm_gain_anal_1.input" '
      print '(a)','   or, ORM data, e.g. "steering_2009-DEC-18.cal" '
      print '(a,$)', ' Input command file : '
      read(*, '(a)') in_file
      call string_trim (in_file, in_file, ix)
      if (ix == 0)in_file = 'bpm_gain_anal_1.input'

      out_file = trim(in_file)//'_out'      
      open(unit=1, file = in_file, status='old', iostat=ios)
      
       if(ios == 0)then
         exit
        else
         type '(/,a)',' ERROR: CANNOT OPEN FILE: ', trim(in_file)
       endif

     end do

     read(1,'(a)')line

     if(index(line,'&bpm_gain_anal_params') /= 0)then

       rewind(1)
       read(1,nml=bpm_gain_anal_params, iostat=ios)

        if(ios /= 0)then
         print *, ' ERROR READING ', trim(in_file)

         rewind(1)
         read(1,nml=bpm_gain_anal_params)
        endif

      else

        call read_the_list( orbit)

        forall(i=0:100) fit_bpm_idx(i) = i


     endif
      
     close(unit=1)

 ! how many detectors are there?
 
  i=0
  do j=0,100
   if (fit_bpm_idx(j) /= -1)i=i+1
  end do

 print *,' Detectors with data '
 print '(10(i2,a1,i4,a1))',(j,'-',fit_bpm_idx(j),',',j=0,i-1)
 print '(a,$)',' Index ? '
 read(5,*) bpm_index
 print *,' index=', bpm_index,  ' fit_bpm_idx(bpm_index)=',fit_bpm_idx(bpm_index)

   bpm=fit_bpm_idx(bpm_index)

 norbits=0
 do i=1,1000
  if(orbit(i) == 0)cycle

  call read_orbit(orbit(i),orbit_data(i)%detector, orbit_data(i)%current)
!  print '(1x,a6,i3,a7,i2,a9,4i)', 'orbit=',i,' bpm=',bpm,' button=',orbit_data(i)%detector(bpm)%button
  norbits=norbits+1
 end do

 open(unit=26, file = out_file)
 print '(a,a)',' Data written to file ', out_file
 return
end

!***************************************************

subroutine read_the_list( orbit)

 use gain_fit_mod
 
 implicit none

! character*100 in_file
 character*100 line

 character*4 steer

 integer orbit(1000)
 integer cu1,cu2,dcu,orbit1, orbit2
 integer i

 real(rp) fit_cal, corstr_cal, ratio, error

  open(unit=1, file=in_file, readonly)

   i=0
   do 
    read(1,'(a)', end=99)line
     if((line(1:1) /= 'H' .and. line(1:1) /= 'V') .or. index(line,'Error') /= 0)cycle

      read(line,*)steer, cu1, cu2, dcu, orbit1, orbit2, fit_cal, corstr_cal, ratio, error
      i=i+1
      orbit(i) = orbit1
      i=i+1
      orbit(i) = orbit2

  end do

99 continue

return
end

!************************************

 subroutine get_avg_std(avg, std, b_max, b_min)

  use gain_fit_mod
  implicit none
  real(rp) but(4)
  real(rp) Bpmmp(4), Bppmm(4), Bpmpm(4), sum_b(3)
  real(rp) avg(3) , std(3), b_max(3), b_min(3), b(3)
  integer i

  sum_b = 0.
  std = 0.
  b_min = 1e19
  b_max = -1e19

  do i=1,norbits
    but(1:4) = orbit_data(i)%detector(bpm)%button(1:4)
    call bvecs(but, Bpmmp, Bpmpm, Bppmm)
    b(1) = dot_product(Bpmmp,gain)
    b(2) = dot_product(Bpmpm,gain)
    b(3) = dot_product(Bppmm,gain)
    sum_b(1:3) =  b(1:3) + sum_b(1:3)
    b_max(1:3) = max(b_max(1:3), b(1:3))
    b_min(1:3) = min(b_min(1:3), b(1:3))
  end do

  avg(1:3) = sum_b(1:3)/norbits

  do i=1,norbits
    but(1:4) = orbit_data(i)%detector(bpm)%button(1:4)
    call bvecs(but, Bpmmp, Bpmpm, Bppmm)
    std(1) = std(1) + (dot_product(Bpmmp,gain) - avg(1) ) **2
    std(2) = std(2) + (dot_product(Bpmpm,gain) - avg(2) ) **2
    std(3) = std(3) + (dot_product(Bppmm,gain) - avg(3) ) **2
  end do

   std(1:3) = sqrt(std(1:3)/norbits)

  return
 end
    
   subroutine gain_to_a(gain, a, ind)
   use precision_def

   implicit none
    real(rp) a(5), gain(4)
    integer ind

    a(1:4)= gain

     return
   end

   subroutine a_to_gain(gain,a,ind)

   use precision_def

   implicit none
    real(rp) a(5), gain(4)
    integer ind
     gain=a(1:4)
     return
   end

   subroutine write_rdfile_list(number,directory)
     use gain_fit_mod
     use precision_def
     use sim_utils
     implicit none

     logical first/.true./
     integer number
     integer, save :: lun, num_files
     character*2 iword
     character*16 directory

     if(first) then
        lun = lunget()
        open(unit=lun, file=trim(directory)//'/RDfiles_fitted.dat')
        num_files=0
        first=.false.
     endif
     
     num_files = num_files+1
     
     if(num_files < 10)then
        write(iword,'(i1)')num_files
        write(lun,'(a11,a1,i6,a1)')'rdfile['//iword(1:1)//'] = ','"',number,'"'
        write(lun,'(a12,a1,i6,a1)')'norbits['//iword(1:1)//'] = ','"',norbits,'"'
     endif
     if(num_files >=10)then
        write(iword,'(i2)')num_files
        write(lun,'(a12,a2,i6,a2)')'rdfile['//iword//'] = ','"',number,'"'
        write(lun,'(a13,a2,i6,a2)')'norbits['//iword//'] = ','"',norbits,'"'
     endif

     return
   end subroutine write_rdfile_list
   
