;MAKEMAG,SEQ,FIRST,LAST,OUT=OUTFILE
;  Purpose: Calculates magnetograms from a sequence of filtergrams and writes to        disk (if outfile is present), or loads into M (if supplied in call)
;  Input: SEQ (string): Sequencename of filtergrams (without extension)
;         FIRST (int): Beginning exposure in sequence to use
;         LAST (int): Last exposure in sequence to use
;         OUTFILE: Name of outputfile (extension will be sequential counter)
;         M: Variable to load (last calculated) magnetogram into
;  Output: Creates diskfile(s) containing magnetogram(s)
;  Needs: MAG_SETUP, RDVELTABLE, RDMAGSEQ, VELCALC, CHGFITSVAL, FITSHEADER,
;        FZHEADER, FITSW, FZW
;  History: I. Zayer, LPARL, Sep. 1992

pro makemag,seq,first,last,out=out,m
@mag_setup

  rdveltable,lookupname,obs,true
  wfits=strupcase(writeformat) eq 'FITS'
  rfzero=strupcase(readformat) eq 'F0'
  new=0
  for start=first,last,scanlen+skip do begin
    rdmagseq,readformat,seq,start,scanlen,i1,i2,i3,i4,hdr,pol='l'
    vl=velcalc(i1,i2,i3,i4,hdr,obs,true)
    rdmagseq,readformat,seq,start,scanlen,i1,i2,i3,i4,hdr,pol='r'
    if wfits then hdr=fitsheader(hdr) else hdr=fzheader(hdr)
    vr=velcalc(i1,i2,i3,i4,hdr,obs,true)
    if strupcase(startpol) eq 'R' then m=vr-vl else m=vl-vr
    comment='Magnetic splitting calculated from '+seq+', images no.'+$
      strtrim(string(start),2)+' to '+strtrim(string(start+scanlen-1),2)
    if wfits then begin
      chgfitsval,hdr,'FRAME','Magnetogram'
      chgfitsval,hdr,'COMMENT',comment & endif $
    else begin
      hdr.frame=[byte('MAGNETOGRM'),13]
      hdr.comment=comment
    endelse
    if keyword_set(out) then begin
      new=new+1
      ext=strtrim(string(new),2)
      for i=1,4-strlen(ext) do ext='0'+ext
      fnam='.'+ext+newname(hdr)
      if out eq 1 then fnam=seq+fnam else fnam=out+fnam
      strput,fnam,'B',strlen(fnam)-1
      if wfits then fitsw,fnam+'.fits',v,hdr else fzw,fnam+'.f0',v,hdr
    endif
  endfor

end