;---------------------------------------------------------------------------
; Document name: mk_plan_tail.pro
; Created by:    Liyun Wang, GSFC/ARC, May 26, 1995
;
; Last Modified: Mon Mar  4 10:39:43 1996 (lwang@achilles.nascom.nasa.gov)
;---------------------------------------------------------------------------
;
FUNCTION mk_plan_tail, plan, plans, error=error
;+
; PROJECT:
;       SOHO - CDS
;
; NAME:
;       MK_PLAN_TAIL()
;
; PURPOSE: 
;       Find the last plan entry in the current plan block
;
; EXPLANATION:
;       
; CALLING SEQUENCE: 
;       result = mk_plan_tail(plan, plans)
;
; INPUTS:
;       PLAN  - The plan entry to be examined 
;       PLANS - List of plans 
;
; OPTIONAL INPUTS: 
;       None.
;
; OUTPUTS:
;       RESULT - The last plan entry in the block where PLAN is in
;
; OPTIONAL OUTPUTS:
;       None.
;
; KEYWORD PARAMETERS: 
;       ERROR - Returned error message; null string for no error
;
; CALLS:
;       None.
;
; COMMON BLOCKS:
;       None.
;
; RESTRICTIONS: 
;       None.
;
; SIDE EFFECTS:
;       None.
;
; CATEGORY:
;       
; PREVIOUS HISTORY:
;       Written May 26, 1995, Liyun Wang, GSFC/ARC
;
; MODIFICATION HISTORY:
;       Version 1, created, Liyun Wang, GSFC/ARC, May 26, 1995
;
; VERSION:
;       Version 1, May 26, 1995
;-
;
   ON_ERROR, 2
   error = ''
   IF NOT exist(plan) THEN $
      MESSAGE, 'Syntax: result = mk_plan_tail(plan, plans)'

   IF NOT exist(plans) THEN BEGIN
      error = 'Syntax: result = mk_plan_tail(plan, plans)'
      MESSAGE, error, /cont
      RETURN, plan
   ENDIF
   
   itime = get_plan_itime(plan)
   plans = mk_plan_sort(plans, /by_time)
   idx = mk_plan_where(plan,plans, status = in_db)
   IF in_db THEN BEGIN
;---------------------------------------------------------------------------
;     Look for gaps
;---------------------------------------------------------------------------
      tplan = plan
      no_gap = 1
      tgap =  1.d0
      nn = N_ELEMENTS(plans)-1
      WHILE (no_gap) DO BEGIN
         IF idx LT nn THEN BEGIN
            gap = plans(idx+1).(itime)-tplan.(itime+1)
            IF  gap LT tgap THEN BEGIN
               idx = idx+1
               tplan = plans(idx)
            ENDIF ELSE no_gap = 0
         ENDIF ELSE no_gap = 0
      ENDWHILE
      tplan = plans(idx)
   ENDIF ELSE BEGIN
      error = 'The given plan entry is not in the list of plans.'
      MESSAGE, error, /cont
      RETURN, plan
   ENDELSE
   RETURN, tplan
END

;---------------------------------------------------------------------------
; End of 'mk_plan_tail.pro'.
;---------------------------------------------------------------------------
