;+
; Project     :	SOHO - CDS
;
; Name        :	GET_SERIES_ID()
;
; Purpose     :	Returns an internal CDHS ID for a table.
;
; Explanation : Interrogates the series_id database to find whether table has already been used. 
;               If already used then returns the CDHS ID assigned to
;               it else gives the table a new ID and enters it into the database.
;
; Use         : <get_series_id, series>
;
; Inputs      : iseries = structure containing study info for current study.
;                 tags used :
;                    .cdhsid = the internal CDHS ID used to reference the table
;                    .vs     = character string indicating the software version
;                              of the code used to create the table.
;                    .id     = integer planning database ID for the table.
;                    .var    = integer planning database variation for the table.
;                    .reus   = a character indicating whether the table is re-usable 
;                    .sft    = a character indicating whether solar feature tracking
;                              is to be used. 
;                    .istate = structure containing initial state of study information.
;                    .rpt    = character indicating whether series is to be repeated 
;                              indefinitely.
;                    .repn   = integer giving no. of times to repeat last raster
;                              and IEF flags.
;                    .range  = integer giving acceptable range from home position
;                              of mirror and slit pointing adjustments
;                    .dsolx  = deferred solar x pointing for study
;                    .dsoly  = deferred solar y pointing for study
;                    .flagst = character indicating whether flag study or not
;                    .nextst = cdhs id of next study
;
; Opt. Inputs : None.
;
; Outputs     : Structure array containing table information with CDHS ID and table OK
;               entries set.
;               Note that studies may span more than one series table so that
;               for studies array may contain more than one entry. 
;                    .cdhsid = the internal CDHS ID used to reference the table
;                    .ok     = an integer flag indicating whether table has already 
;                                    been loaded onto the CDS.
;
; Opt. Outputs:	None.
;
; Keywords    : DUPLICATE : if set forces a new CDHS ID for the table.
;
; Calls       :	dbopen, db_info, dbbuild, dbfind, dbext, dbclose,
;               get_utc, rem_dup.
;                
; Common      :	None.
;
; Restrictions:	None.
;
; Side effects:	None.
;
; Category    :	Command preparation.
;
; Prev. Hist. :	None.
;
; Written     :	Version 0.0, Martin Carter, RAL, 14/10/94
;
; Modified    :	Version 0.1, Martin Carter, RAL, 28/11/94
;                            Added proforma.
;                       0.2, Martin Carter, RAL, 15/02/95
;                            Started CDHS IDs from default offsets and 
;                            added max. ID check
;                       0.3, MKC, 2/3/95
;                            Added repn and sft to table info,
;                            Removed the dexwin and vdswin tables from the tableID database.
;                       0.4, MKC, 18/4/95
;                            Adapted from get_cdhs_id.
;                            Added solarx and solary to database.
;                       0.5, MKC, 18/5/95
;                            Modified series structure to include state.
;                       0.6, MKC, 24/5/95
;                            Modified seriesID database to include slitn.
;                       0.7  MKC, 31/5/95
;                            Changed series_ID and rasterID databases to series_id and raster_id
;                       0.8, MKC, 10/8/95
;                            Added rpt tag to series structure.
;                       0.9, MKC, 25/9/95
;                            Pointed SW at duplicate database.
;                       1.0, MKC, 29/9/95
;                            Added .repn tag to series.
;                       1.1, MKC, 24/10/95
;                            Added /silent keyword to dbbuild.
;                       1.2, MKC 7/11/95
;                            Added gsetid.
;                       1.3, 1/12/95
;                            Added range to series table structure.
;                       1.4, 6/12/95
;                            Added dsolx, dsoly to series structure.
;                       1.5, 14/12/95
;                            Added fseries to cope with reverse study processing.
;                       1.6, 3/1/96
;                            Added flag study tag to series structure.
;                       1.7, 9/10/96
;                            Removed fseries and used nextst tag instead.
;                       1.8, MKC, 27/4/98
;                            Current implementation of detailed studies does not check for reusability.
;                            This means that get_series_id is not used in current software.
;                            Studies may span more than one series table. The software treats multiple
;                            CDHSIDs returned as the different series tables for the study. 
;                            Multiple copies returned will cause problems.
;                            To get round can update the software version number ! 
;                            Current implementation of alternative studies allows 2 versions of
;                            a table to be active on CDHS. This will cause a similar problem to the
;                            above. Can be fixed by making one version non-reusable.
;
; Version     :	Version 1.8, 27/4/98
;-
;**********************************************************

FUNCTION get_series_id, iseries, DUPLICATE=duplicate

  ; check if table defined and if not return new CDHS ID

  ; get local copy of table

  table = iseries

  ; define first cdhs ID 
  ; NB First 12 series tables are reserved or modified on power up
  ;     Tables start at 0.
  ; The first 10 series tables have IDs 0-9.
  ; The next 2 series tables have IDs 0xFFFE, 0xFFFF.
  ; Start the CDHS Ids so that they keep track with the table index.

  first_id = 12 

  ; set priviledge to update database

  !PRIV = 2

  ; open table ID database for updating

  dbopen, 'dseries_id', 1

  ; check if table exists already

  ; check database has some entries
  ; else dbfind will flag error

  nentries = db_info ( 'entries' )

  IF nentries(0) EQ 0 THEN BEGIN

    ; database is empty

    ; table does not exist

    table.ok = 0

    ; set first entry

    table.cdhsid = first_id

    ; Get current utc time in string format

    get_utc, timenow, /ECS

    ; create new entry in database

    dbbuild, timenow, table.vs, table.cdhsid, table.id, table.var,                     $
                      table.reus, table.sft, table.istate.solarx, table.istate.solary, $
                      table.istate.slitn, table.istate.gsetid, table.rpt, table.repn,  $
                      table.range, table.dsolx, table.dsoly, table.nextst, table.flagst, $
                      /SILENT

  ENDIF ELSE BEGIN

    ; set up search criteria

    search = 'ID=' + STRING(table.id) + ',VAR=' + STRING(table.var) 

    list = dbfind ( search, /SILENT)

    ; list is array of entries in database
    ; if no entries then list contains a zero
    ; valid entries start at 1 

    IF list(0) GE 1 THEN BEGIN

      ; refine search criteria

      search = 'SW_VERSION=' + table.vs + $
               ',REUS=Y' + $
               ',SFT=' + table.sft + $
               ',SOLARX=' + STRING ( table.istate.solarx ) + $
               ',SOLARY=' + STRING ( table.istate.solary ) + $
               ',SLITN=' + STRING ( table.istate.slitn ) + $
               ',GSETID=' + STRING ( table.istate.gsetid ) + $
               ',RPT=' + table.rpt + $
               ',REPN=' + STRING ( table.repn ) + $
               ',RANGE=' + STRING ( table.range ) + $
               ',DSOLX=' + STRING ( table.dsolx ) + $
               ',DSOLY=' + STRING ( table.dsoly ) + $
               ',FSTDY=' + STRING ( table.nextst ) + $
               ',FLAGST=' + table.flagst

      list = dbfind ( search, list, /SILENT)

    ENDIF

    ; list may have more than one entry corresponding
    ; to more than one table needed

    ; does table not exist or table is not re-usable or duplicate explicitly requested

    IF (list(0) LT 1) OR (table.reus EQ 'N') OR KEYWORD_SET(duplicate) THEN BEGIN

      ; table does not exist, create new table ID entry

      table.ok = 0

      ; get next CDHS ID

      ; extract last cdhs ID 

      dbext, [ LONG ( nentries ) ], 'CDHS_ID', cdhsids   

      table.cdhsid = cdhsids(0) + 1   

      IF table.cdhsid EQ 32768 THEN MESSAGE, 'MAXIMUM CDHSID REACHED'

      ; Get current utc time in string format

      get_utc, timenow, /ECS

      ; create new entry in database

      dbbuild, timenow, table.vs, table.cdhsid, table.id, table.var,                     $
                        table.reus, table.sft, table.istate.solarx, table.istate.solary, $
                        table.istate.slitn, table.istate.gsetid, table.rpt, table.repn,  $
                        table.range, table.dsolx, table.dsoly, table.nextst, table.flagst, $
                        /SILENT

    ENDIF ELSE BEGIN

      ; table does exist, extract table entry

      table.ok = 1

      ; remove any duplicates

      list = list ( rem_dup ( list ) )

      ; get table entry

      dbext, list, 'CDHS_ID', cdhsids
 
      ; set IDs

      IF N_ELEMENTS(cdhsids) EQ 1 THEN BEGIN 

        table.cdhsid = cdhsids(0)

      ENDIF ELSE BEGIN

        ; get duplicate copies of table

        table = REPLICATE (  table, N_ELEMENTS(cdhsids) )    
     
        table.cdhsid = cdhsids

      ENDELSE

    ENDELSE

  ENDELSE

  ; close table ID database

  dbclose, 'dseries_id'

  ; reset priviledges

  !PRIV = 1  

  ; return results

  RETURN, table

END


