  program gain_tbt

   use gain_fit_mod
   use tbt_mod
   use super_recipes_mod

   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)

   integer i
   integer ix
   integer det(4)
   integer j
   integer index
   integer m
!   integer dets(100)
   integer status
   integer monitor
   integer i1/0/,i2

   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


   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(4,4), dc_dg_num(4), chis_num
   real(rp) d2c_dg2(4,4), b(4,4), gain_error(4)
   real(rp) chis_save(4), const_save(4)
   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

   logical, allocatable ::  maska(:)
   logical just_one/.false./

   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

    call get_turn_by_turn
 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'
 open(unit = 26, file = out_file)
 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(26, '(a,1x,i2,a,1x,a,a)')' gain_correct = ',gain_correct,',', trim(type), ' to tbt data' 
 write(26,'(a7,11(a12))') &
              '! 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'

open(unit=29, file = 'orbit.dat')
write(29,'(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
 open(unit=44,file='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

 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 >= 100)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(44,'(a)')file
!  print *,file
   open(unit=24, file = file)
   gain(1:4) = 1.
   write(11,'(a,i)')' BPM = ',bpm

   write(24,'(a)')'&button_sums'
   write(24,'(a9, i5)')' index = ', index
   write(24,'(a7, i5)')' BPM = ', bpm
   write(24,'(a8,4e12.4)')' gain = ', gain
   write(24,'(a11,e12.4)')' const = ',const 
   write(24,'(a18)')' delta_h =  0.  '
   write(24,'(a18)')' delta_v =  0.  '
   write(24,'(a)')'/'

   write(24,'(13a12)')' ', ' ', '', '', '', &
           'Bpmpm.G X ', '','','','',''
   write(24,'(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
      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
        if(any(det(1:4) == 0))cycle

           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
           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)
          write(24,'(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(29,'(i10,2es12.4)')bpm, avg_x, avg_y
!      call get_avg_std(avg, std, b_max, b_min)

   close(unit=24)

    call fit_gains(chis_save, gain_save, const_save)

!  print '(/,a,i)',' bpm = ',bpm
!  do i=1,4
!   print '(4e12.4,1x,2e12.4)', 1./gain_save(i,1:4), const_save(i), chis_save(i)
!  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))/4.
   const = sum(const_save)/4.
!  gain(1:4) = gain_save(4,1:4)

 open(unit=25, file = file_fit)

   write(25,'(a)')'&button_sums'
   write(25,'(a9, i5)')' index = ', index
   write(25,'(a7, i5)')' BPM = ', bpm
   write(25,'(a8,4e12.4)')' gain = ', gain
   write(25,'(a11,e12.4)')' const = ',const 
   write(25,'(a11,e12.4)')' delta_h = ', h_max - h_min
   write(25,'(a11,e12.4)')' delta_v = ', v_max-v_min
   write(25,'(a)')'/'
   write(25,'(10a12)')'','',&
       '', '', '', &
       'Bpmpm.G X', '', ''
   write(25,'(10a12)')'x','y',&
       'Bpmmp.G', 'Bpmpm.G', 'Bppmm.G', &
       'Bppmm.G/I', 'I', 'chis_1'

  do i=1,norbits
    but(1:4) = orbit_data(i)%detector(bpm)%button(1:4)
    call bvecs(but, Bpmmp,Bpmpm,Bppmm)
    chis_1 = chi(gain, const, but, current)
     write(25,'(10e12.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, chis_1
    
   end do

   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)

   forall(i=1:4)gain_save(i,1:4) = 4*gain_save(i,1:4)/sum(gain_save(i,1:4))
   gain(1:4) = (gain_save(1,1:4)+gain_save(2,1:4)+gain_save(3,1:4)+gain_save(4,1:4))/4.
   const = sum(const_save)/4.

 write(26, '(i7,11e12.4)')bpm, h_min,h_max,h_max-h_min,v_min,v_max,v_max-v_min, 1./gain, const 
 write(27, '(3x,i4,9e12.4)')bpm, gain(1)/gain, chis_1, gain_error
 j=j+1  
 bpm_max = max(float(bpm), bpm_max)
 bpm_min = min(float(bpm), bpm_min)
 bpm_gain(1:4,j) = 1/gain
 bpm_mat(1:4,j) = bpm 
 
  if(just_one) exit
  end do ! do m=1,100 cycle through bpms

  close(unit=26)
  close(unit=44)

   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 ('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
close(unit=29)
return
end
