PRO DBREPAIR, DBNAME
;
    ON_ERROR, 2
    COMMON DB_COM,QDB,QITEMS,QDBREC
;
;  Check the number of parameters.
;
    IF N_PARAMS() NE 1 THEN MESSAGE, 'Syntax:  DBREPAIR, DBNAME'
;
;  Check the privilege.
;
    IF !PRIV LT 4 THEN MESSAGE, $
        '!PRIV must be 4 or greater to repair a database'
;
;  Open the database.
;
    DBOPEN, DBNAME, 1, UNAVAIL=UNAVAIL
    IF UNAVAIL EQ 1 THEN MESSAGE, 'Unable to open database '+DBNAME
;
;  Make sure the database is in external format.
;
    IF NOT DB_INFO('external', DBNAME) THEN BEGIN
        MESSAGE, /CONTINUE, 'Not in external format'
        MESSAGE, /CONTINUE, 'Database ' + DBNAME +  $
            ' does not need to be repaired'
        GOTO, FINISH
    ENDIF
;
;  Find out if any of the items are arrays.
;
    NVALUES = DB_ITEM_INFO('nvalues')
    IF MAX(NVALUES) EQ 1 THEN BEGIN
        MESSAGE, /CONTINUE, 'No arrays'
        MESSAGE, /CONTINUE, 'Database ' + DBNAME +  $
            ' does not need to be repaired'
        GOTO, FINISH
    ENDIF
;
;  Find out if the database is empty.
;
    IF DB_INFO('entries', DBNAME) EQ 0 THEN BEGIN
        MESSAGE, /CONTINUE, 'Database ' + DBNAME + ' is empty'
        MESSAGE, /CONTINUE, 'Database ' + DBNAME +  $
            ' does not need to be repaired'
        GOTO, FINISH
    ENDIF
;
;  Make sure that the user really wants to repair the file.
;
    PRINT,'Printing out first 5 values of each multidimensional array'
    W = WHERE(NVALUES GT 1)
    NVALUES = NVALUES(W)
    NAMES = DB_ITEM_INFO('name', W)
    FOR I_NAME = 0,N_ELEMENTS(NAMES)-1 DO BEGIN
        DBEXT,1,NAMES(I_NAME),TEMP
        PRINT, NAMES(I_NAME) + ':', TEMP(0:4<(NVALUES(I_NAME)-1))
    ENDFOR
    ANSWER = ''
    READ,'Are you sure you want to repair this database? (Y/N): ',ANSWER
    IF STRUPCASE(STRMID(ANSWER,0,1)) NE 'Y' THEN GOTO, FINISH
;
;  Step through each record, and repair it.
;
    N_ENTRIES = DB_INFO('entries', DBNAME)
    FOR I=0,N_ENTRIES-1 DO BEGIN
        ENTRY = QDBREC(I)
        DB_ENT2HOST, ENTRY, 0, /REPAIR_MODE
        DB_ENT2EXT, ENTRY
        QDBREC(I) = ENTRY
    ENDFOR
;
    MESSAGE, /INFORMATION, 'Database ' + DBNAME + ' repaired'
;
;  Exit point.
;
FINISH:
    DBCLOSE
;
    RETURN
    END