pro sccwritefits, filename, img, hdr, PIPELINE=pipeline, SAVEPATH=savepath, COMMENTS=comments,silent=silent,_extra=ex 
;+
; $Id: sccwritefits.pro,v 1.2 2007/08/10 17:59:49 thernis Exp $
;
; Project   : STEREO SECCHI
;                   
; Name      : sccwritefits.pro
;               
; Purpose   : Writes FITS file(s) for secchi_prep.pro
;               
; Use       : IDL> sccwritefits, name_of_fits_file, data_array, hdr_structure
;    
; Inputs    : filename STRING  name of file to save
;   	    : img      data array - image to save
;   	    : hdr      STRUCT	SECCHI header structure
;
; Keywords  : /PIPELINE - write percent polarized image from common block
;   	    : SAVEPATH = path to append to filename before saving
;   	    : COMMENTS = string array of keyword comments corresponding to hdr
;
; Outputs   : writes 1 or more FITS files
;
; Calls     : 
;
; Common    : secchi_daily - defined in daily/?.pro
;
; Category    : FITS, Calibration, IO, pipeline
;
; Written     : Nathan.Rich@nrl.navy.mil, Feb. 2007
;
; $Log: sccwritefits.pro,v $
; Revision 1.2  2007/08/10 17:59:49  thernis
; Don't even call scc_update_comments if spcomments is not defined
;
; Revision 1.1  2007/08/08 20:10:11  colaninn
; moved from prep
;
; Revision 1.5  2007/08/02 19:18:11  thernis
; Check if spcomments sec_prep common block variable is defined before calling scc_update_comments which requires it.
;
; Revision 1.4  2007/05/21 20:16:06  colaninn
; added silent keyword
;
; Revision 1.3  2007/04/13 16:04:37  nathan
; improve implementation of SAVEPATH; uncomment COMMON secchi_daily
;
; Revision 1.2  2007/04/13 14:26:49  colaninn
; uncommented common sec_prep and defined pfilename as filename
;
; Revision 1.1  2007/03/13 17:34:45  nathan
; I thought this was added?
;
;-

COMMON secchi_daily , ppimage, pphdr
COMMON sec_prep, spcomments
; spcomments needs to be updated in COMMON sec_prep ? -nr

IF keyword_set(SAVEPATH) THEN dir=savepath ELSE dir=''
pfilename = concat_dir(dir,filename)

IF ~keyword_set(silent) THEN message,'WRITING '+pfilename,/inform

IF keyword_set(COMMENTS) THEN spcomments=comments

; ---- call scc_update_comments only if spcomments is defined
if n_elements(spcomments) ne 0 then spcomments=scc_update_comments(spcomments,hdr)

hdr_string = struct2fitshead(hdr,img, /allow_crota, /dateunderscore, comments=spcomments)
writefits,pfilename,img, hdr_string

IF keyword_set(PIPELINE) THEN BEGIN
    ppfilename=concat_dir(dir,pphdr.filename)
    message,'WRITING '+ppfilename,/inform
    ppcomments=scc_update_comments(spcomments,pphdr) 
    phdr_string =  struct2fitshead(pphdr,ppimage, /allow_crota,/dateunderscore, comments = ppcomments)
    writefits,ppfilename,ppimage,phdr_string
ENDIF

END
