;+
; Project     : SOHO - CDS
;
; Name        : XCDS_BOOK
;
; Purpose     : add or return CDS study from bookmark save file
;
; Category    : planning
;
; Explanation :
;
; Syntax      : IDL> xcds_book,book_study
;
; Examples    :
;
; Inputs      : STUDY = study to add
;
; Opt. Inputs : None
;
; Outputs     : STUDY = selected study
;
; Opt. Outputs: None
;
; Keywords    : ERR   = error messages
;               ADD   = set to add study to bookmark list
;
; Common      : None
;
; Restrictions: None
;
; Side effects: None
;
; History     : Version 1,  17-Aug-1996,  D M Zarro.  Written
;
; Contact     : DZARRO@SOLAR.STANFORD.EDU
;-


pro xcds_book,study,err=err,_extra=extra,add=add,group=group

;-- initialize and read bookmark file

err=''
caller=get_caller(stat)
if stat then xkill,/all
widget_control,/hour
delvarx,bookmarks
bookmark_file=concat_dir(getenv('HOME'),'.xstudy_book.genx')
cfind=loc_file(bookmark_file,count=count)
if count gt 0 then restgen,bookmarks,file=bookmark_file

;-- add study to bookmarks

if keyword_set(add) then begin
 if datatype(study) ne 'STC' then astudy={study_id:-1,studyvar:-1} else astudy=study
 if (astudy.study_id lt 0) or (astudy.studyvar lt 0) then begin
  err='STUDY_ID and VARIATION required.' & goto,quit
 endif

 if exist(bookmarks) then begin
  chk=where((astudy.study_id eq bookmarks.study_id) and $
            (astudy.studyvar eq bookmarks.studyvar) and $
            (astudy.title_id eq bookmarks.title_id),cnt)
  if cnt gt 0 then begin
   err='Study already bookmarked.'
   goto,quit
  endif
 endif

 widget_control,/hour
 temp={study_id:0l,title_id:0l,studyvar:0l,acronym:'',title:''}
 copy_struct,rep_tag_name(astudy,'OBS_PROG','ACRONYM'),temp
 temp.title=strmid(trim(temp.title),0,50)

 bookmarks=concat_struct(bookmarks,temp)
 bstudy=bookmarks.acronym
 sorder = sort([bstudy])
 bookmarks=bookmarks(sorder)

;-- list and select from bookmarks

endif else begin
 if exist(bookmarks) then begin
  xlist,bookmarks,index,title='Bookmarked Studies',/modal,$
        group=group,_extra=extra,/select
  widget_control,/hour
  if index gt -1 then begin
   bstudy_id=bookmarks(index).study_id
   bstudyvar=bookmarks(index).studyvar
   bstudy=get_cds_study(bstudy_id,bstudyvar,err=err)
   if err eq '' then study=bstudy else err=err+' -- check DB'
  endif
 endif else begin
  err='Sorry, no bookmarked studies found.'
  goto,quit
 endelse
endelse

;-- save bookmarks

if exist(bookmarks) then savegen,file=bookmark_file,bookmarks,/xdr,/notype else $
 rm_file,bookmark_file

quit:


if err ne '' then xack,err,group=group

return & end
