!+
! Program plot_tbt_data
! 
! Routine to read turn by turn data file and plot vertical vs horizontal position
! for each BPM or a histogram of the button signals in each BPM.
! The turn by turn data is assumed to be in two files, one for the east BPMs and one for the west
!

  program plot_tbt_data

   use gain_fit_mod
   use quick_plot

   implicit none

   integer i,m, but(4),  bin_width
   integer bin_min, bin_max, bin(4), but_min, but_max
   integer, allocatable ::  nbin(:,:)
   integer scale/1000/
   integer avg, total
   integer j
   integer ngraph
   integer east_west/0/
   integer, allocatable :: buttons(:,:)
   logical just_one
   logical hardcopy/.false./
   character*100 last/'h'/, answer, answer_east_west

   real(rp) hscale/22./, vscale/27./
   real(rp), allocatable :: x(:),y(:)

do
    call read_string(' Histogram<h> or x vs y <xy> or button sums/diffs <b> ',last,answer)
    last = answer  
    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

    if(norbits < 100)then
      print '(a,i5,a)',' The number of orbits is ',norbits,'. Chose another data set'
      cycle
    endif
    just_one = .false.
    if(bpm > 0) just_one = .true.

 ngraph = 0

 allocate(x(1:norbits),y(1:norbits))
 allocate(buttons(1:4, norbits))
 east_west=0

do
 do m=1,49
  total=0

 if(.not. just_one) then
     bpm = m + east_west
 endif

    if(all(orbit_data(1)%detector(bpm)%button(1:4) == 0))cycle
     do i=1,norbits

      but(1:4) = abs(orbit_data(i)%detector(bpm)%button(1:4))/scale
      total = total + sum(but(1:4))
     end do
   
     avg = total/4/norbits

     but_min = avg*.5
     but_max=  avg*1.5
     bin_width = avg/100
     bin_width = 35
     bin_min = float(but_min)/bin_width
     bin_max = float(but_max)/bin_width
!     bin_min = 00  !50
!     bin_max = 200 !150
!   print *,'bpm =', bpm, ' total = ', total, ' norbits = ',norbits
!   print *,' bin_min = ', bin_min, ' bin_max = ', bin_max
     allocate(nbin(1:4,0:bin_max))
     do i=0,bin_max
       nbin(1:4,i)=0
     end do

    do i=1,norbits 
      but(1:4) = orbit_data(i)%detector(bpm)%button(1:4)/scale
      bin(1:4) = but(1:4)/bin_width + .5
      buttons(1:4,i) = orbit_data(i)%detector(bpm)%button(1:4)/scale
      do j=1,4
        if(bin(j) < bin_min)bin(j) = bin_min      
        if(bin(j) > bin_max)bin(j) = bin_max      
        nbin(j,bin(j))=nbin(j,bin(j))+1

      end do
     if(sum(but(1:4))/= 0)then  
       x(i) = (but(4)-but(3)+but(2)-but(1)) * hscale/sum(but(1:4))
       y(i) = (but(4)+but(3)-but(2)-but(1)) * vscale/sum(but(1:4))
      else
       x(i)=0
       y(i)=0
     endif
     write(73,'(i, 2e12.4)')i,x(i),y(i)

    end do ! norbits
!  print '(2i)',(i,nbin(1,i),i=bin_min,bin_max)
   ngraph = ngraph + 1  


   if(just_one)then
      if(answer(1:1) == 'h')call hist_one_bpm(ngraph,bpm, bin_min, bin_max, nbin(:,:))
      if(index(answer,'x')/= 0)call xy_one_bpm(x,y)
      if(index(answer,'b')/=0)call button_sums_diffs(bpm, buttons,norbits)
      deallocate(nbin)
      exit
    else
     if(index(answer,'h')/= 0)call hist_buts(ngraph,bpm, bin_min, bin_max, nbin(:,:))
     if(index(answer,'x')/= 0)call xy_all_bpm(x,y, ngraph)
   endif
   deallocate(nbin)

  end do ! m bpm
   if(east_west==0 .and. .not. just_one) then
    call read_string('hit return to plot east detectors', 'east',answer_east_west)
    east_west = 49
    ngraph = 0
   else
    exit
  endif
  end do
 deallocate(x,y)
 deallocate(buttons)
 end do


contains

 subroutine hist_buts(ngraph,ix_bpm,bin_min,bin_max, nbin)

 use gain_fit_mod
 use quick_plot
 use precision_def

 implicit none

integer nbin(:,:),ix_bpm, bin_min, bin_max
integer i,j
integer id/1/
 integer width/7/, height/7/
 integer np, ngraph, ix, iy

real(rp), allocatable :: x(:),y(:,:)
real(rp) max_y
  real(rp) xlen/1000./, ylen/800./
real(rp) bin_min_rp, bin_max_rp

logical first/.true./
character*100 word,title

if(ngraph == 1 ) then
 call qp_open_page('X', id, xlen, ylen,'POINTS')
 call qp_set_page_border (0.01_rp, 0.02_rp, 0.02_rp, 0.02_rp, '%PAGE')
 call qp_set_margin (0.02_rp, 0.02_rp, 0.015_rp, 0.015_rp, '%PAGE')
 first = .false.
endif

 if(ngraph == 1) then
   call qp_clear_page 
   call qp_draw_text (in_file, 0.1_rp, 0.98_rp,"%PAGE",height=10.0_rp,color=1)
   call qp_draw_text ("35 counts/bin", 0.9_rp, 0.95_rp,"%PAGE",height=10.0_rp,color=1)
   call qp_draw_text ("button 1", 0.9_rp, 0.92_rp,"%PAGE",height=10.0_rp,color=1)
   call qp_draw_text ("button 2", 0.9_rp, 0.90_rp,"%PAGE",height=10.0_rp,color=2)
   call qp_draw_text ("button 3", 0.9_rp, 0.88_rp,"%PAGE",height=10.0_rp,color=3)
   call qp_draw_text ("button 4", 0.9_rp, 0.85_rp,"%PAGE",height=10.0_rp,color=4)
 endif

 write(word,'(i)')ix_bpm
 call string_trim(word,word,ix)
 title = word(1:ix)
 ix = mod(ngraph-1, width) + 1
 iy = (ngraph-1)/width + 1

 call qp_set_box (ix, iy,  width,height)

allocate(x(1:bin_max),y(1:4,1:bin_max))
max_y = max(maxval(nbin(1,:)),maxval(nbin(2,:)),maxval(nbin(3,:)),maxval(nbin(4,:)))
bin_min_rp = bin_min
bin_max_rp = bin_max

do i=1,bin_max
  x(i) = float(i)
  y(1:4,i) = nbin(1:4,i)
end do

call qp_set_axis ('X', bin_min_rp, bin_max_rp)
call qp_set_axis ('Y', 0.0_rp, max_y)

call qp_draw_axes
call qp_draw_text (title, 0.8_rp, 0.85_rp,"%GRAPH",height=10.0_rp)

do j=1,4
call qp_draw_histogram (x, y(j,:), fill_color=j, fill_pattern= no_fill$, line_color=j, clip = .true.)

end do

deallocate(x,y)


return
end subroutine

 subroutine hist_one_bpm(ngraph,ix_bpm,bin_min,bin_max, nbin)

 use gain_fit_mod
 use quick_plot
 use precision_def

 implicit none

integer nbin(:,:),ix_bpm, bin_min, bin_max
integer i,j
integer id/2/
 integer width/1/, height/1/
 integer np, ngraph, ix, iy

real(rp), allocatable :: x(:),y(:,:),z(:)
real(rp) max_y
  real(rp) xlen/800./, ylen/540./
real(rp) bin_min_rp, bin_max_rp

logical first/.true./
character*100 word,title

if(ngraph == 1 ) then
 call qp_open_page('X', id, xlen, ylen,'POINTS')
 call qp_set_page_border (0.01_rp, 0.02_rp, 0.2_rp, 0.2_rp, '%PAGE')
 call qp_set_margin (0.02_rp, 0.02_rp, 0.015_rp, 0.015_rp, '%PAGE')
 first = .false.
endif

 if(ngraph == 1) then
   call qp_clear_page 
   call qp_draw_text (in_file, 0.1_rp, 0.98_rp,"%PAGE",height=10.0_rp,color=1)
   call qp_draw_text ("35 counts/bin", 0.9_rp, 0.95_rp,"%PAGE",height=10.0_rp,color=1)
   call qp_draw_text ("button 1", 0.9_rp, 0.92_rp,"%PAGE",height=10.0_rp,color=1)
   call qp_draw_text ("button 2", 0.9_rp, 0.90_rp,"%PAGE",height=10.0_rp,color=2)
   call qp_draw_text ("button 3", 0.9_rp, 0.88_rp,"%PAGE",height=10.0_rp,color=3)
   call qp_draw_text ("button 4", 0.9_rp, 0.85_rp,"%PAGE",height=10.0_rp,color=4)
 endif

 write(word,'(i)')ix_bpm
 call string_trim(word,word,ix)
 title = word(1:ix)
 ix = mod(ngraph-1, width) + 1
 iy = (ngraph-1)/width + 1

 call qp_set_box (1, 1,  width,height)

allocate(x(1:bin_max),z(1:bin_max),y(1:4,1:bin_max))
max_y = max(maxval(nbin(1,:)),maxval(nbin(2,:)),maxval(nbin(3,:)),maxval(nbin(4,:)))
bin_min_rp = bin_min
bin_max_rp = bin_max

do i=1,bin_max
  x(i) = float(i)
  y(1:4,i) = nbin(1:4,i)
end do
!  print '(i,2es12.4)',(i,x(i),y(1,i),i=1,bin_max)
call qp_set_axis ('X', bin_min_rp, bin_max_rp)
call qp_set_axis ('Y', 0.0_rp, max_y)

call qp_draw_axes
call qp_draw_text (title, 0.8_rp, 0.85_rp,"%GRAPH",height=10.0_rp)

do j=1,4
forall(i=1:bin_max)z(i)=y(j,i)
call qp_draw_histogram (x, z, fill_color=j, fill_pattern= no_fill$, line_color=j, clip = .false.)
pause
end do

deallocate(x,y)


return
end subroutine
!**********************************************************888
subroutine xy_all_bpm(x,y, ngraph)
 use quick_plot
 use precision_def

 implicit none 
  
 real(rp) x(:),y(:)
 real(rp) xlen/1000./, ylen/800./
 real(rp) xmin,xmax,ymin,ymax

 logical first/.true./

 integer width/7/, height/7/
 integer np, ngraph, ix, iy,i
 integer id/3/

 character*100 word,title

 write(word,'(i)')bpm
 call string_trim(word,word,ix)
 title = word(1:ix)

 ix = mod(ngraph-1, width) + 1
 iy = (ngraph-1)/width + 1


if(ngraph == 1 ) then
 call qp_open_page('X', id, xlen, ylen,'POINTS')
 call qp_set_page_border (0.01_rp, 0.02_rp, 0.02_rp, 0.02_rp, '%PAGE')
 call qp_set_margin (0.02_rp, 0.02_rp, 0.015_rp, 0.015_rp, '%PAGE')
 first = .false.
endif

 if(ngraph == 1) then
   call qp_clear_page 
   call qp_draw_text (in_file, 0.1_rp, 0.98_rp,"%PAGE",height=10.0_rp,color=1)
   call qp_draw_text('horizontal is x [mm]',0.85_rp,0.95_rp,"%PAGE",height=10.0_rp, color=1)
   call qp_draw_text('vertical is y [mm]', 0.85_rp,0.93_rp,"%PAGE",height=10.0_rp, color=1)
 endif

 call qp_set_box (ix, iy,  width,height)
 xmin=minval(x)
 xmax=maxval(x)
 ymin=minval(y)
 ymax=maxval(y)
 call qp_calc_and_set_axis ('X', minval(x),maxval(x), 4, 4, 'GENERAL')
 call qp_calc_and_set_axis ('Y', minval(y),maxval(y), 4, 4, 'GENERAL')
 call qp_draw_axes
 call qp_set_symbol_attrib (1, color = red$, height = 1.0_rp)
 call qp_draw_data (x, y,draw_line = .false., symbol_every = 1)
 call qp_draw_text (title, 0.8_rp, 0.1_rp,"%GRAPH",height=10.0_rp)
 return
end subroutine xy_all_bpm

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

subroutine xy_one_bpm(x,y)
 use quick_plot
 use precision_def

 implicit none 
  
 real(rp) x(:),y(:)
 real(rp) xlen/800./, ylen/540./
 real(rp) xmin, xmax, ymin, ymax

 logical first/.true./

 integer width/1/, height/1/
 integer np, ix, iy,i
 integer id/3/

 character*100 word,title

 write(word,'(i)')bpm
 call string_trim(word,word,ix)
 title = word(1:ix)

 ix = mod(ngraph-1, width) + 1
 iy = (ngraph-1)/width + 1


!if(first ) then
 call qp_open_page('X', id, xlen, ylen,'POINTS')
 call qp_set_page_border (0.04_rp, 0.04_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')
 first = .false.
!endif

! if(ngraph == 1) then
   call qp_clear_page 
   call qp_draw_text (in_file, 0.1_rp, 0.98_rp,"%PAGE",height=10.0_rp,color=1)
!   call qp_draw_text('horizontal is x [mm]',0.85_rp,0.95_rp,"%PAGE",height=10.0_rp, color=1)
!   call qp_draw_text('vertical is y [mm]', 0.85_rp,0.93_rp,"%PAGE",height=10.0_rp, color=1)
! endif

 xmin=minval(x)
 xmax=maxval(x)
 ymin=minval(y)
 ymax=maxval(y)
 call qp_set_box (ix, iy,  width,height)
 call qp_calc_and_set_axis ('X', minval(x),maxval(x), 4, 4, 'GENERAL')
 call qp_calc_and_set_axis ('Y', minval(y),maxval(y), 4, 4, 'GENERAL')
 call qp_draw_axes('Horizontal[mm]','Vertical[mm]')
 call qp_set_symbol_attrib (1, color = red$, height = 10.0_rp)
 call qp_draw_data (x, y,draw_line = .false., symbol_every = 1)
 call qp_draw_text (title, 0.8_rp, 0.1_rp,"%GRAPH",height=10.0_rp)
 return
end subroutine xy_one_bpm
!********************************************************
subroutine button_sums_diffs(bpm,buttons,norbits)

use precision_def

implicit none

integer norbits, bpm
integer buttons(:,:)
integer but(1:4)
integer ix

real(rp), allocatable :: x(:), y(:)
real(rp) hscale/22./, vscale/27./

character*100 word, bpm_word, title

allocate(x(norbits),y(norbits))

  write(word,'(i)')bpm
  call string_trim(word,word,ix)
  title = "Detector "//word(1:ix)
!normal
   do i=1,norbits
    but(1:4) = buttons(1:4,i)
    x(i) = but(1)-but(2)-but(3)+but(4)
    y(i) = ( but(1)-but(2)+but(3)-but(4)) * (but(1)+but(2)-but(3)-but(4))
   end do

  word  = "i >< i"
  call plot_button_products(x,y,1,title,word)

! 3 >< 4
   do i=1,norbits
    but(1:4) = buttons(1:4,i)
    x(i) = but(1)-but(2)-but(4)+but(3)
    y(i) = ( but(1)-but(2)+but(4)-but(3) ) * (but(4)+but(2)-but(4)-but(3))
   end do

  word  = " 3><4 "
  call plot_button_products(x,y,2,title,word)

! 1 >< 3
   do i=1,norbits
    but(1:4) = buttons(1:4,i)
    x(i) = but(3)-but(2)-but(1)+but(4)
    y(i) = ( but(3)-but(2)+but(1)-but(4) ) * (but(3)+but(2)-but(1)-but(4))
   end do

  word  = " 1><3 "
  call plot_button_products(x,y,3,title,word)

! 2 >< 4
   do i=1,norbits
    but(1:4) = buttons(1:4,i)
    x(i) = but(1)-but(4)-but(3)+but(2)
    y(i) = ( but(1)-but(4)+but(3)-but(2) ) * (but(1)+but(4)-but(3)-but(2))
   end do

  word  = " 2 >< 4"
  call plot_button_products(x,y,4,title,word)

! 1 >< 2
   do i=1,norbits
    but(1:4) = buttons(1:4,i)
    x(i) = but(2)-but(1)-but(3)+but(4)
    y(i) = ( but(2)-but(1)+but(3)-but(4) ) * (but(2)+but(1)-but(3)-but(4))
   end do

  word  = " 1 >< 2 "
  call plot_button_products(x,y,5,title,word)

!  cross diff
   do i=1,norbits
    but(1:4) = buttons(1:4,i)
    x(i) = (but(2)-but(1)-but(3)+but(4)) * hscale /sum(but)
    y(i) = ( but(4)+but(1)-but(3)-but(2) ) * vscale  /sum(but)
   end do

  word  ="k(4+1-3-2)/\gS\f"
  call plot_button_products(x,y,6,title,word)



deallocate(x,y)

end subroutine button_sums_diffs

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

subroutine plot_button_products(x,y, ngraph,title,word)

 use gain_fit_mod
 use quick_plot
 use precision_def

 implicit none 
  
 real(rp) x(:),y(:)
 real(rp) xlen/1000./, ylen/800./

 logical first/.true./

 integer width/2/, height/3/
 integer np, ngraph, ix, iy,i
 integer id/3/

 character*100 word,title

 ix = mod(ngraph-1, width) + 1
 iy = (ngraph-1)/width + 1


if(ngraph == 1 ) then
 call qp_open_page('X', id, xlen, ylen,'POINTS')
 call qp_set_page_border (0.01_rp, 0.02_rp, 0.02_rp, 0.02_rp, '%PAGE')
 call qp_set_margin (0.04_rp, 0.04_rp, 0.04_rp, 0.04_rp, '%PAGE')
 first = .false.
endif

 if(ngraph == 1) then
   call qp_clear_page 
   call qp_draw_text (in_file, 0.1_rp, 0.98_rp,"%PAGE",height=10.0_rp,color=1)
!   call qp_draw_text('horizontal axis = B\d+--+\u',0.85_rp,0.95_rp,"%PAGE",height=10.0_rp, color=1)
!   call qp_draw_text('vertical axis = (B\d+-+-\u)B(\d++--\u)', 0.85_rp,0.93_rp,"%PAGE",height=10.0_rp, color=1)
   call qp_draw_text (title, 0.6_rp, 0.98_rp,"%PAGE",height=10.0_rp,color=1)
 endif

 call qp_set_box (ix, iy,  width,height)
 call qp_calc_and_set_axis ('X', minval(x),maxval(x), 4, 4, 'GENERAL')
 call qp_calc_and_set_axis ('Y', minval(y),maxval(y), 4, 4, 'GENERAL')
 if(index(word,'<')/= 0)call qp_draw_axes('B\d+--+\u','(B\d+-+-\u)B(\d++--\u)')
 if(index(word,'<') == 0)call qp_draw_axes('Horizontal position[mm]','(\gD\f -/\gS\f )k [mm]')
 call qp_set_symbol_attrib (1, color = red$, height = 1.0_rp)
 call qp_draw_data (x, y,draw_line = .false., symbol_every = 1)
 call qp_draw_text (word, 0.8_rp, 0.1_rp,"%GRAPH",height=10.0_rp)
 return

end subroutine plot_button_products

end
