Program gui_demo
  Use gui
  Implicit None
  Integer, Parameter :: n_buttons = 4;
  Type (guibutton), Dimension(n_buttons) :: buttons
  Integer :: which_button  ! a helper function at end
  Integer :: i,ans   ! counter, temp. var
  Real :: cx, cy  ! cursor position
  Character :: ch ! which button A = left, D = middle, X = right
  Integer, External :: PGOPEN, PGCURS
! Initialize PGPLOT
  If (Pgopen('?') <= 0) Stop
  CALL PGPAP(10.0,0.5)  ! width = 10, aspect = 0.5 (twice as wide)
  CALL PGPAGE   ! start new page
  CALL PGSWIN(0.0,2.0,0.0,1.0) ! aspect ratio 0.5 so x = 2 
  CALL PGSCR(0, 0.4, 0.4, 0.4) ! CI,  CR, CG, CB
     
! Get buttons data from cfg file.
  call init_buttons(buttons, n_buttons, 'gui.cfg')
  do i = 1, n_buttons
    call draw_button(buttons(i))
  end do

! process each user click until Exit
  do
     cx = 0.3 ; cy = 0.3  ! initial cursor position
     ans = PGCURS(cx, cy, ch) ! wait for user to click
     i = which_button(buttons, n_buttons, cx, cy)
     if (i == 0) Cycle
     Select Case (trim(buttons(i)%label))
        Case ('Button 1')
           Call PGSCI(1)
           Call PGPTXT(0.4,0.4,10.5,0.0,'Button 1 chosen')
           Cycle
        Case ('Button 2')
           Call PGSCI(2)
           Call PGPTXT(0.4,0.4,40.5,0.0,'Button 2 chosen')
           Cycle
        Case ('Draw Circle')
           Call PGSCI(3)
           Call PGPTXT(0.4,0.4,60.5,0.0,'Dont know circle')
           Cycle
        Case ('Exit')
           Call PGSCI(4)
           Call PGPTXT(0.4,0.4,80.5,0.0,'Exiting ....')
           Exit
        Case Default
           Cycle
        End Select
    Exit    
   End do
End Program gui_demo

Integer Function which_button(buttons, n_buttons, x, y)
  ! returns which button contains x,y.  0 if none. i.e. outside
  Use gui
  Implicit None
  Integer, Intent(IN) :: n_buttons
  Type (guibutton), Dimension(n_buttons), Intent(IN) :: buttons
  Real, Intent (IN) :: x, y
 
  Integer :: i, ans
  ans = 0
  Do i = 1, n_buttons
     If (within_button(buttons(i),x,y)) Then
        ans = i
        Exit
     End If
  End Do
  which_button = ans
End Function which_button

