 program gain_tbt

   use bmad
   use gain_fit_mod
   use tbt_mod
   use super_recipes_mod
   use fio
   
   implicit none

  type range_struct
   real(rp) range(0:10)
  end type

  type button_gain_struct
   character*9 label
   type (range_struct) button(0:3)
  end type

  type (button_gain_struct) table0_bpm_data(0:120), table1_bpm_data(0:120)
  type (orbit_struct) orbit_data_save(300000)

   integer i
   integer ix
   integer det(4)
   integer j
   integer index
   integer m
!   integer dets(100)
   integer status
   integer monitor
   integer i1/0/,i2
   integer n
   integer good
   integer n_so_far
   integer norbits_save
   integer files_so_far
   integer lun24,lun25,lun26,lun27,lun29,lun44
   integer max_nonlin_positions/0/
   
   logical read_current_from_butns_file
   character*100 name, file, file_fit
   character*100 out_file
   character*1 answer, ans
   character*120 old_comments_list(100)
   character*100 fit_gain_file
   character*100 type
   character*1 cint
   character*1 yn
   character*20 rd_files(20)
   character*16 directory


   real(rp) hscale/22./, vscale/27./, rms,chsi
   real(rp) Bpmmp(4), Bppmm(4), Bpmpm(4), den/1./
   real(rp) current
   real(rp), allocatable :: xx(:), yy(:), a(:), sig(:)
   real(rp), dimension(:,:), allocatable :: covar, alpha 
   real(rp) alambda
   real(rp) chisq
   real(rp) but(4)
   real(rp) dc_dg(4)
   real(rp) avg(3), std(3), test, b_max(3), b_min(3)
   real(rp) fit_g(4), fit_r(4), fit_gain(0:120,4), fit_rms(0:120,4), c_avg, c_sig
   real(rp) chis_1
   real(rp) gain_save(5,4), dc_dg_num(4), chis_num
   real(rp) d2c_dg2(4,4), b(4,4), gain_error(4)
   real(rp) chis_save(5), const_save(5), covar_save(1:5,1:5,1:5)
   real(rp) horz, vert, h_max, h_min, v_max, v_min
   real(rp) bpm_mat(4,0:120), bpm_gain(4,0:120), bpm_min/100./, bpm_max/0./
   real(rp) gain_save_arb(4,4), gain_arb(4)
   real(rp) avg_x, avg_y
   real(rp) chis
   real(rp) Bpppp, Bpppp2
   real(rp) average_gain(1:5), rms_gain(1:5)
 
   logical, allocatable ::  maska(:)
   logical just_one/.false./
   logical another

   call create_output_directory(directory)
   expert = .false.

!  print '(a,$)', ' Real or fake data ? '
!  accept *, answer
  call read_string(' Expert mode ? ','N',answer )
  if(answer(1:1) == 'Y' .or. answer(1:1) == 'y')expert = .true. 

  answer = 'R'
  call str_upcase(answer,answer)

  index = 0  
 if(answer(1:1) == 'F')then
 
   call get_fake_data

 else  !real data

!  print '(a,$)',' Orbit or Turn by turn data ? '
!  accept *, answer
  answer = 'T'  
  call str_upcase(answer, answer)

  if(answer(1:1) == 'T')then



     n_so_far = 0
     files_so_far=0
    another = .true.
    do while (another)     ! add together as many RD files as you like
       call in4get(' Compute positions (x,y) using nonlin BPM for N orbits (def N=0) ',max_nonlin_positions)
       call get_turn_by_turn(directory, max_nonlin_positions)
       files_so_far = files_so_far + 1
       rd_files(files_so_far) = in_file_0
       
       
       print *,' Norbits = ',norbits
       print *,' Number of orbits so far ',n_so_far+norbits
       if(norbits + n_so_far > 300000)exit
       !     orbit_data_save = orbit_data
       do i = 1, norbits
          orbit_data(i + n_so_far) = orbit_data(i)
       end do
       n_so_far = n_so_far + norbits
       norbits_save = n_so_far
       print '(a,$)',' Another RD file ? (y/n) '
       read(5,'(a)')yn
       !      if(index(yn,'n') /= 0) another = .false.
       if(yn(1:1) == 'n')another = .false.

    end do




    do
      print '(a,$)',' which bpm ? (-1 for all)'
      accept *,bpm
      if(any(dets(1:100) == bpm) .or. bpm == -1)exit
      print *,' No data for bpm ',bpm,'  choose another'
      print *,' Available bpms are: '
      print '(20i4)', dets(1:100)
    end do

    out_file = trim(in_file_0)//'_out'
    lun26=lunget()
    open(lun26, file=trim(directory)//'/'//out_file)
    lun27=lunget()
    open(lun27,file = trim(directory)//'/'//trim(in_file_0)//'_err')
    
    print '(a,a)',' Data written to file ',out_file 
    if(gain_correct == gain_and_pedestal_correct$) type = 'gain_and_pedestal_correction'
    if(gain_correct == pedestal_correct$) type = 'pedestal but no gain correction'
    if(gain_correct == no_correct$) type = 'no_gain_or_pedestal_correction'
    write(lun26,'(a7,i2,a1,a12, i2,a1)')'mfiles=',files_so_far,';', 'array file[',files_so_far,']'
    do i=1,files_so_far
       write(lun26,'(a5,i2,a3,a1,a,a1)') 'file[',i,']= ', '"',trim(rd_files(i)),'"'
    end do
    
    write(lun26, '(a,1x,i2,a,1x,a,a)')' gain_correct = ',gain_correct,',', trim(type), ' to tbt data' 
    write(lun26,'(a7,13(a12),4x,2a12)') &
              '! BPM ','h_min','h_max','h_max-h_min','v_min','v_max', &
                        'v_max-v_min',' gain(1)',' gain(2)',' gain(3)',' gain(4)','const','chis','name','button ave','rms but ave'

    write(lun27,'(a7,i2,a1,a12, i2,a1)')'mfiles=',files_so_far,';', 'array file[',files_so_far,']'
    do i=1,files_so_far
       write(lun27,'(a5,i2,a3,a1,a,a1)') 'file[',i,']= ', '"',trim(rd_files(i)),'"'
    end do
    write(lun27, '(3x,a3,4(4x,5a12),2x,24x,a12,12x,24x,a12,12x,a12)')'bpm', ' ', ' ','1/gain',' ', 'chis', ' ',' ','1/gain',' ', 'chis', ' ',' ','1/gain',' ', 'chis', ' ',' ','1/gain',' ', 'chis', ' ',&
         'average gain','rms_gain'
    
    lun29 = lunget()
    open(lun29, file=trim(directory)//'/'//'orbit.dat')
    write(lun29,'(a10,2a12)')'bpm', 'avg_x', 'avg_y'
    print '(a,4i)',' gain_tbt,1,50 ',orbit_data(1)%detector(50)%button(1:4)  
  else

     call get_orbit_data

   endif ! orbit or turn by turn
  endif ! real or fake data

 weight =0.
!  print '(a,$)',' Weight ?'
!  accept *,weight

  answer = 'N'
  if(expert)call read_string(' Read fitted gains ','N',answer )
  call str_upcase(answer,answer)
  if(answer(1:1) == 'Y')then
   call read_cbpmii_button_gain(fit_gain_file,old_comments_list, table0_bpm_data, table1_bpm_data)
  do m=0,120
   fit_gain(m,3) = table0_bpm_data(m)%button(0)%range(0)
   fit_gain(m,1) = table0_bpm_data(m)%button(1)%range(0)
   fit_gain(m,2) = table0_bpm_data(m)%button(2)%range(0)
   fit_gain(m,4) = table0_bpm_data(m)%button(3)%range(0)
!   print '(i,4e12.4)',m,fit_gain(m,1:4)
   if(any(abs(1-fit_gain(m,:))>0.3))fit_gain(m,1:4)=1
  end do
  endif


99  continue

 ! for bpm fit_bpm_idx(0) translate the 4 buttons into 2 vertical and 2 horizontal positions and print
 if(bpm > 0)just_one = .true.    !just do the one chosen

 j=0
 lun44=lunget()
 open(lun44,file=trim(directory)//'/file_list.dat')

 do m=0,120

   if(just_one == .false.)bpm = m
   if(all(orbit_data(1)%detector(bpm)%button(1:4) == 0))then
      cycle ! no data for this bpm
      print *,' no data for bpm ', bpm
   endif
   good = 0
   do i=1,norbits_save
      if(all(orbit_data(i)%detector(bpm)%button(1:4) == 0))then
         print '(a,1x,i10,1x,a,1x,i10)',' No data for bpm ', bpm,' on orbit ',i
      else
         good = good+1
         orbit_data(good)%detector(bpm) = orbit_data(i)%detector(bpm)
      endif
   end do
   norbits = good
   print '(i10,1x,a,1x,i10)',norbits,' orbits for BPM ',bpm

   if(expert .and. just_one)then
      call read_string(' Swap ? ','N',ans )
      call str_upcase(ans,ans)
      if(ans(1:1) == 'Y')then
         print '(a,$)',' Pair to swap (i.e. 2,3) '
         accept *, i1,i2
      endif
   endif

   if(bpm < 100) write(name,'(i)')bpm
   if(bpm >= 89)name = bpm_names(bpm)
   name=bpm_names(bpm)
   print '(i,a)', bpm, name
   call string_trim(name,name,ix)
   file = 'BPM_'//name(1:ix)//'.dat'
   file_fit = 'BPM_'//name(1:ix)//'.dat_fit'
   write(lun44,'(a)')file
   !  print *,file
   lun24=lunget()
   open(lun24, file=trim(directory)//'/'//file)
   gain(1:4) = 1.
   write(11,'(a,i)')' BPM = ',bpm

   write(lun24,'(a7,i2,a1,a12, i2,a1)') 'mfiles=',files_so_far,';', 'array file[',files_so_far,']'
   do i=1,files_so_far
      write(lun24,'(a5,i2,a3,a1,a,a1)') 'file[',i,']= ', '"',trim(rd_files(i)),'"'
   end do

   write(lun24,'(a)')'&button_sums'
   write(lun24,'(a9, i5)')' index = ', index
   write(lun24,'(a7, i5)')' BPM = ', bpm
   write(lun24,'(a8,4e12.4)')' gain = ', gain
   write(lun24,'(a11,e12.4)')' const = ',const 
   write(lun24,'(a18)')' delta_h =  0.  '
   write(lun24,'(a18)')' delta_v =  0.  '
   write(lun24,'(a)')'#/'
   write(lun24,*)  
   write(lun24,*)  
   write(lun24,'(a1,13a12)')'#',' ', ' ', '', '', '', &
        'Bpmpm.G X ', '','','','',''
   write(lun24,'(a1,13a12)')'#','x', 'y', 'Bpmmp.G', 'Bpmpm.G', 'Bppmm.G', &
               'Bppmm.G/I', 'I','button 1','button 2','button 3','button 4'

   h_max=-99
   v_max=-99
   h_min = 99
   v_min = 99

   do i=1,norbits
      but(1:4) = orbit_data(i)%detector(bpm)%button(1:4)
      if(i1 /= 0)then !swap
         but(i1) = orbit_data(i)%detector(bpm)%button(i2)
         but(i2) = orbit_data(i)%detector(bpm)%button(i1)
         orbit_data(i)%detector(bpm)%button(1:4) = but(1:4)
      endif
      if(answer(1:1) == 'Y')then
!            if( all(fit_rms(bpm,1:4)<0.05))then
         if(all(fit_gain(bpm,:) /= 0))then
            orbit_data(i)%detector(bpm)%button(1:4) = orbit_data(i)%detector(bpm)%button(1:4)/fit_gain(bpm,1:4)
!           if(i == 1)print '(a, i,4e12.4)',' fitted_gain_correction, bpm: ',bpm, fit_gain(bpm,1:4)
         endif
      endif
      det(1:4) = orbit_data(i)%detector(bpm)%button(1:4)
      but(1:4) = orbit_data(i)%detector(bpm)%button(1:4)
     
      current = orbit_data(i)%current

      current = 1 !all button instensities are normalized by g.b      

      if(any(det(1:4) == 0))cycle
      
      call xy_position(bpm,det,horz, vert)
!      horz = float(det(4)+det(2)-det(3)-det(1))/sum(det)*hscale
!      vert = float(det(4)-det(2)+det(3)-det(1))/sum(det)*vscale
      orbit_data(i)%detector(bpm)%x = horz
      orbit_data(i)%detector(bpm)%y = vert
!      horz = orbit_data(i)%detector(bpm)%x
!      vert = orbit_data(i)%detector(bpm)%y
      h_max = max(horz,h_max)
      h_min = min(horz, h_min)
      v_max = max(vert,v_max)
      v_min = min(vert, v_min)
         
!     write(11,'(4f12.4)')v1,v2,h1,h2
      write(11,'(4e12.4)') but
      call bvecs(but, Bpmmp,Bpmpm,Bppmm)
      Bpmmp = Bpmmp/dot_product(gain,but)
      Bpmpm = Bpmpm/dot_product(gain,but)
      Bppmm = Bppmm/dot_product(gain,but)
      
      write(lun24,'(13e12.4)')orbit_data(i)%detector(bpm)%x, orbit_data(i)%detector(bpm)%y, &
           dot_product(Bpmmp,gain), dot_product(Bpmpm,gain), dot_product(Bppmm,gain), &
           dot_product(Bpmpm,gain)*dot_product(Bppmm,gain)/ current, current,but
   end do
   avg_x = sum(orbit_data(1:norbits)%detector(bpm)%x)/norbits
   avg_y = sum(orbit_data(1:norbits)%detector(bpm)%y)/norbits
   write(lun29,'(i10,2es12.4)')bpm, avg_x, avg_y
   !      call get_avg_std(avg, std, b_max, b_min)
   
   close(unit=lun24)
   
   if((bpm >=7 .and. bpm <48) .or. (bpm>=52 .and. bpm <= 92))then
      const_save(:)=1.1
   elseif(bpm >= 48 .and. bpm <=51)then
      const_save= 1.4
   else
      const_save(:)=0.64
   endif
   
   call fit_gains(chis_save, gain_save, const_save, covar_save)
   
   gain(1:4)=0.
   chis=0
   n=0
   do i=1,4
      if(any(gain_save(i,:) == 0))cycle
      gain(1:4) = gain(1:4) + gain_save(i,1:4)
      const = const + const_save(i)
      chis = chis + chis_save(i)
      n=n+1
   end do
   gain(1:4) = gain(1:4)/n
   const = const/n
   chis = chis/n
   !  gain(1:4) = gain_save(4,1:4)

   lun25=lunget()
   open(lun25, file = trim(directory)//'/'//trim(file_fit))
   
   write(lun25,'(a,a1,4es12.4,a1)')' gain = ','"',gain,'"'
   write(lun25,'(a11,a1,es12.4,a1)')' delta_h = ','"',h_max - h_min,'"'
   write(lun25,'(a11,a1,es12.4,a1)')' delta_v = ','"', v_max-v_min,'"'
   write(lun25,'(a11,a1,e12.4,a1)')' const = ','"',const,'"' 
   write(lun25,'(a11,a1,e12.4,a1)')' chis_deg = ','"',chis/norbits,'"'
   write(lun25,'(a17,a1,es12.4,a1,es12.4,a1,es12.4,a1,es12.4,a1)') 'array gains[4] = ','[',gain(1),',',gain(2),',',gain(3),',',gain(4),']'
   write(lun25,'(a)')'exit'
   
   write(lun25,'(a)')'&button_sums'
   write(lun25,'(a9, i5)')' index = ', index
   write(lun25,'(a7, i5)')' BPM = ', bpm
   write(lun25,'(a8,4e12.4)')' gain = ', gain
   write(lun25,'(a11,e12.4)')' const = ',const 
   write(lun25,'(a11,e12.4)')' delta_h = ', h_max - h_min
   write(lun25,'(a11,e12.4)')' delta_v = ', v_max-v_min
   write(lun25,'(a)')'#/'
   write(lun25,*)
   write(lun25,*)
   write(lun25,'(a1,10a12)')'#','','','', '', '', 'Bpmpm.G X', '', ''
   write(lun25,'(a1,10a12)')'#','x','y', 'Bpmmp.G', 'Bpmpm.G', 'Bppmm.G', 'Bppmm.G/I', 'I', 'chis_1'

   write(lun25,'(a)')'covariance matrix'
   do ind = 1,5
      write(lun25,'(/,a,i10,a,es12.4,a,4es12.4)')'ind= ',ind,' chisq=', chis_save(ind),' gain = ',(gain_save(ind,j),j=1,4)
      do i=1,5
         write(lun25,'(5es12.4)')(covar_save(ind,i,j),j=1,5)
      end do
   end do
   write(lun25,'(/)')
   Bpppp=0  !sum of buttons
   Bpppp2 = 0  !sum of squars
   do i=1,norbits
      but(1:4) = orbit_data(i)%detector(bpm)%button(1:4)
      call bvecs(but, Bpmmp,Bpmpm,Bppmm)
      Bpmmp = Bpmmp / dot_product(gain_save(1,1:4),but)
      Bpmpm = Bpmpm / dot_product(gain_save(1,1:4),but)
      Bppmm = Bppmm / dot_product(gain_save(1,1:4),but)
      Bpppp = Bpppp+dot_product(gain_save(1,1:4), but)
      Bpppp2 = Bpppp2+dot_product(gain_save(1,1:4),but) ** 2
      chis_1 = chi(gain_save(1,1:4), const_save(1), but, current)
      write(lun25,'(10e12.4)')orbit_data(i)%detector(bpm)%x, orbit_data(i)%detector(bpm)%y,&
           dot_product(Bpmmp,gain_save(1,1:4)), dot_product(Bpmpm,gain_save(1,1:4)), dot_product(Bppmm,gain_save(1,1:4)), &
           dot_product( Bpmpm,gain_save(1,1:4))*dot_product(Bppmm,gain_save(1,1:4))*const_save(1)/ current, current, chis_1
    
   end do

   close(lun25) 

!   forall(i=1:4)gain_save_arb(i,1:4) = arb_gain(1:4,bpm)*gain_save(i,1:4)
!   forall(i=1:4)gain_save_arb(i,1:4) = 4*gain_save_arb(i,1:4)/sum(gain_save_arb(i,1:4))
!   gain_arb(1:4) = (gain_save_arb(1,1:4)+gain_save_arb(2,1:4)+gain_save_arb(3,1:4)+gain_save_arb(4,1:4))/4.
!   if(just_one)print '(a,4f12.4)',' gain including arbitrary multiplier ',gain_arb(1:4)

!   do i=1,4
!      if(all(gain_save(i,:)/=0))gain_save(i,1:4) = 4*gain_save(i,1:4)/sum(gain_save(i,1:4))
!   end do
   gain(1:4) = (gain_save(1,1:4)) !+gain_save(2,1:4)+gain_save(3,1:4)+gain_save(4,1:4))/n
   const = sum(const_save)/n
   do i=1,4
      average_gain(i) = sum(gain_save(1:4,1)/gain_save(1:4,i))/4
      rms_gain(i) = sum((gain_save(1:4,1)/gain_save(1:4,i))**2)
      rms_gain(i) = sqrt(abs(rms_gain(i) - 4*average_gain(i)**2))
   end do
   
   write(lun26, '(i7,12e12.4,4x,a12,4x,2es12.4)')bpm, h_min,h_max,h_max-h_min,v_min,v_max,v_max-v_min, 1./gain, const, chis/norbits,bpm_names(m), &
        Bpppp/norbits, sqrt((Bpppp2- Bpppp**2/norbits)/norbits)
   
   write(lun27, '(3x,i4,5(3x,5es12.4),4x,8es12.4,4x,a12)')bpm, (gain_save(ind,1)/gain_save(ind,1:4), chis_save(ind), ind=1,5), average_gain(1:4), rms_gain(1:4),bpm_names(m)
   j=j+1  
   bpm_max = max(float(bpm), bpm_max)
   bpm_min = min(float(bpm), bpm_min)
   bpm_gain(1:4,j) = 1/gain(1:4)
   bpm_mat(1:4,j) = bpm 
 
   if(just_one) exit
end do ! do m=1,120 cycle through bpms

close(unit=lun26)
close(unit=lun44)
close(lun27)
close(unit=lun29)

print '(a,a)','output written to directory ',trim(directory)

call plot_gains(bpm_max, bpm_min, bpm_gain, bpm_mat,j)

 end

subroutine plot_gains(bpm_max, bpm_min, bpm_gain, bpm_mat,j)
  use gain_fit_mod
  use quick_plot
  use precision_def

  implicit none
  real(rp) x(0:100,4),y(0:100,4)
  real(rp) bpm_mat(4,0:100), bpm_gain(4,0:100), bpm_min, bpm_max
  
  real(rp) xlen/800./, ylen/540./
  integer id,i ,j
  integer ix
  character*100 title/'Fitted Gains'/
  character*100 out_file
  character*3 device, ans

  out_file = trim(in_file_0)
  ix = index(out_file,'.')

  device = 'X'
  do 
 
     if(device(1:1) == 'X')call qp_open_page('X', id, xlen, ylen,'POINTS')
 
     if(device(1:2) == 'PS') call qp_open_page('PS-L',plot_file=out_file(1:ix)//'ps')
     if(device(1:3) == 'GIF') call qp_open_page('GIF-L',plot_file=out_file(1:ix)//'gif')

     call qp_set_page_border (0.02_rp, 0.02_rp, 0.04_rp, 0.04_rp, '%PAGE')
     call qp_set_margin (0.02_rp, 0.02_rp, 0.015_rp, 0.015_rp, '%PAGE')

     call qp_set_box (1,1,1,1)
     title = trim(title)//out_file(1:ix)
     call qp_calc_and_set_axis ('X', bpm_min,bpm_max, 4, 8, 'GENERAL')
     call qp_calc_and_set_axis ('Y', 0.8_rp,1.2_rp, 4, 8, 'GENERAL')
     call qp_draw_axes ("BPM", "gain",trim(title))
     ! call qp_set_symbol_attrib (2, color = red$, height = 10.0_rp)
     call qp_set_symbol_attrib ('plus', color = 'red', height = 10.0_rp)

     do i = 1,j
        call qp_draw_data (bpm_mat(1:4,i),bpm_gain(1:4,i),draw_line = .true., symbol_every = 1)
        !  call qp_draw_text (title, 0.8_rp, 0.1_rp,"%GRAPH",height=10.0_rp)
        
     end do
     if(device /= 'X')then
        call qp_close_page
        exit
     endif
     print '(a,$)' ,' Postscript (p) or Gif (g) '
     call read_string('Postscript (p) or Gif (g) ? ', 'no',ans)
     call upcase_string(ans)
     if(index(ans,'N') /= 0) exit
     if(index(ans,'P')/= 0)device = 'PS' 
     if(index(ans,'G')/= 0)device = 'GIF' 
     
  end do

  return
  

end

subroutine  xy_position(bpm,det,h, v)
  use precision_def
  implicit none
  integer bpm, det(4)
  real(rp) h, v
  real(rp) sum_all

  sum_all = sum(det(1:4))
  select case(bpm)

! 48W/E

  case (48, 51)
    v = .0287*(det(3)+det(4)-det(1)-det(2))/sum_all   ! fit to L0 Horz data spring 1999
    h = .0287*(det(2)+det(4)-det(3)-det(1))/sum_all   ! q2 q48 45 degrees, elliptical pipe

! 49W/E

  case (49, 50)
    v = .035*(det(3)+det(4)-det(1)-det(2))/sum_all  ! q49  45 degree, 4" diam
    h = .035*(det(2)+det(4)-det(3)-det(1))/sum_all  ! changed from .042 to .035, dec89 RML

! south arc       x5c to 9w
     
  case (1,7)
    v = .0104*(det(3)+det(4)-det(1)-det(2))/sum_all
    h = .0102*(det(2)+det(4)-det(3)-det(1))/sum_all

! south arc       x1a to x5b
    
  case (93,110)    
    v = .0104*(det(3)+det(4)-det(1)-det(2))/sum_all
    h = .0102*(det(2)+det(4)-det(3)-det(1))/sum_all
  
! normal arc detectors

  case default
    
    v = .0198*(det(3)+det(4)-det(1)-det(2))/sum_all
    h = .0259*(det(2)+det(4)-det(3)-det(1))/sum_all
 end select
 return
end subroutine xy_position
