$KAPA = unix://kapa

macro fixmask.new
  if (($0 != 2) && ($0 != 3))
    echo "USAGE: fixmask.new (chip) [cell]"
    echo "subtract 2 from last line number for next cell"
    break
  end

  dev -n 0
  dev -n 1
  sleep 1

  dev -n 0
  showchips $1
  # resize -n 0 1150 1000
  # center {4846/2} {4868/2} -5

  $outroot = GPC1.MASK.20081109
  $chip = $1

  $startcell = -1
  if ($0 == 3)
    $startcell = $2
  else
    file $outroot.$chip.fits exists
    if ($exists)
     echo "$outroot.$chip.fits exists, need to specify starting cell"
     break
    end
  end

  for i $startcell 64
    if ($i == -1)
      rd mkc GPC1.MASK.CTE.$chip.fits
      keyword mkc NEXTEND -wd 0

      # add the mask bit names here
      keyword mkc MSKNUM   -wd 3
      keyword mkc MSKNAM00 -w DETECTOR
      keyword mkc MSKVAL00 -wd 2
      keyword mkc MSKNAM01 -w FLAT
      keyword mkc MSKVAL01 -wd 4
      keyword mkc MSKNAM02 -w DARK
      keyword mkc MSKVAL02 -wd 64

      wd mkc $outroot.$chip.fits
      continue
    else
      rd mkc GPC1.MASK.CTE.$chip.fits -x $i
      keyword mkc EXTNAME extname
      echo cell $extname

      # skip the video cells
      rd imci o4743g0247o.$chip.fits -x $i -head
      keyword imci NAXIS2 tNy
      if ($tNy > 2000) 
        echo "skipping video cell $i"
        wd mkc $outroot.$chip.fits -extend
      else     

        rd imci o4743g0247o.$chip.fits -x $i
        $Nx = 590
        $Ny = 598
        
        delete -q imc
        extract imci imc 0 0 590 598 0 0 590 598
        
        # cheat: don't use DATASEC, NAXIS1, NAXIS2: compressed image header is bad
        set imkc = (imc*(abs(imc - $F0) < $dF) + 1e6*(abs(imc - $F0) > $dF))*(mkc < 1)
        
        dev -n 1
        tvch 1; tv mkc -1 10
        tvch 2; tv imc {$F0-2*$dF} {4*$dF}
        tvch 3; tv imkc {$F0-2*$dF} {4*$dF}
        resize -n 1 745 610
        center {590/2} {598/2}
        
        $done = 0
        while ($done == 0)
          echo $extname
          echo "y - accept, z - zap, Escape - exit without accepting"
          cursor 1
          if ("$KEY" == "y") 
            $done = 1
          end
          if ("$KEY" == "Escape") 
            break
          end
          if ("$KEY" == "z") 
        	  echo "mark region with 1 & 2"
            $donezap = 0
            $skipzap = 0
        	  while ($donezap == 0)
              cursor 1
              if ("$KEY" == "h")
        	      echo "1 - LL corner"
        	      echo "2 - UR corner"
        	      echo "i - U row"
        	      echo "m - L row"
        	      echo "j - L col"
        	      echo "k - R col"
        	      echo "I - full top"
        	      echo "J - full left"
        	      echo "K - full right"
        	      echo "M - full bottom"
        	      echo "C - full cell"
        	      echo "q - stop zapping"
        	      echo "r - full row"
        	      echo "c - full col"
        	      echo "d - left side, full col"
        	      echo "f - right side, full col"
              end
              if ("$KEY" == "1")
                $xs = int($X1)
                $ys = int($Y1)
              end
              if ("$KEY" == "2")
                $xe = int($X2)
                $ye = int($Y2)
              end
              if ("$KEY" == "i")
                $ys = int($Yi)
              end
              if ("$KEY" == "m")
                $ye = int($Ym)
              end
              if ("$KEY" == "j")
                $xs = int($Xj)
              end
              if ("$KEY" == "k")
                $xe = int($Xk)
              end
              if ("$KEY" == "I")
                $ys = 0
              end
              if ("$KEY" == "M")
                $ye = 598
              end
              if ("$KEY" == "J")
                $xs = 0
              end
              if ("$KEY" == "K")
                $xe = 590
              end
              if ("$KEY" == "C")
        	      $xs = 0
        	      $xe = 590
        	      $ys = 0
        	      $ye = 598
              end
              if ("$KEY" == "q")
                $donezap = 1
              end
              if ("$KEY" == "Escape")
                $skipzap = 1
              end
              if ("$KEY" == "d")
                $ys = 0
        	      $ye = $Ny
                $xs = int($Xd)
              end
              if ("$KEY" == "f")
                $ys = 0
        	      $ye = $Ny
                $xe = int($Xf)
              end
              if ("$KEY" == "r")
                $xs = 0
                $ys = 6
        	      $xe = $Nx
        	      $ye = 8
                $donezap = 1
              end
              if ("$KEY" == "c")
                $xs = 0
                $ys = 589
        	      $xe = $Nx
        	      $ye = 591
                $donezap = 1
              end
            end            
            if ($skipzap == 0)
              zap mkc $xs $ys {$xe-$xs} {$ye-$ys} -v 2
        	    set imkc = (imc*(abs(imc - $F0) < $dF) + 1e6*(abs(imc - $F0) > $dF))*(mkc < 1)
        	    tvch 1; tv mkc -1 10
        	    tvch 3; tv imkc {$F0-2*$dF} {4*$dF}
            end
          end
          if ("$KEY" == "p") 
        	  # clip high values
        	  set mkcp = 2*(imkc > 1e5)
        	  set mkc = mkc | mkcp
        	  set imkc = (imc*(abs(imc - $F0) < $dF) + 1e6*(abs(imc - $F0) > $dF))*(mkc < 1)
        	  tvch 1; tv mkc -1 10
        	  tvch 3; tv imkc {$F0-2*$dF} {4*$dF}
          end
        end
        wd mkc $outroot.$chip.fits -extend
      end
    end
  end
  exec cp -i $outroot.$chip.fits $outroot.$chip.fits.save
end

# XXX this script has been disabled for write: uncommend the lines marked WWW

macro fixmask
  if (($0 != 2) && ($0 != 3))
    echo "USAGE: fixmask (chip) [cell]"
    echo "subtract 2 from last line number for next cell"
    break
  end

  dev -n 0
  dev -n 1
  sleep 1

  dev -n 0
  showchips $1
  $outroot = GPC1.MASK.FIX
  $chip = $1

  $startcell = -1
  if ($0 == 3)
    $startcell = $2
  end

  for i $startcell 64
    if ($i == -1)
      rd mkc GPC1.MASK.$chip.fits
      keyword mkc NEXTEND -wd 0
      # WWW wd mkc $outroot.$chip.fits
      continue
    else
      rd mkc GPC1.MASK.$chip.fits -x $i
      keyword mkc EXTNAME extname
      echo cell $extname

      rd imci o4596g0022f.13750.detproc.13.$chip.fits -x $i

      delete -q imc
      extract imci imc 0 0 590 598 0 0 590 598

      # cheat: don't use DATASEC, NAXIS1, NAXIS2: compressed image header is bad
      # window down -5,-5,-5,-5
      # datasec 1:590,1:598
      # keyword mkc NAXIS1 Nx
      # keyword mkc NAXIS2 Ny
      $Nx = 590
      $Ny = 598
      zap mkc 0 0 6 $Ny -v 2
      zap mkc 0 0 $Nx 6 -v 2
      zap mkc 583 0 7 $Ny -v 2
      zap mkc 0 591 $Nx 7 -v 2

      set imkc = (imc*(abs(imc - $F0) < $dF) + 1e6*(abs(imc - $F0) > $dF))*(mkc < 1)

      dev -n 1
      tvch 1; tv mkc -1 10
      tvch 2; tv imc {$F0-2*$dF} {4*$dF}
      tvch 3; tv imkc {$F0-2*$dF} {4*$dF}

      $done = 0
      while ($done == 0)
        echo $extname
        echo "y - accept, z - zap"
        cursor 1
        if ("$KEY" == "y") 
          $done = 1
        end
        if ("$KEY" == "Escape") 
          break
        end
        if ("$KEY" == "z") 
	  echo "mark region with 1 & 2"
          $donezap = 0
          $skipzap = 0
 	  while ($donezap == 0)
            cursor 1
            if ("$KEY" == "1")
              $xs = int($X1)
              $ys = int($Y1)
            end
            if ("$KEY" == "2")
              $xe = int($X2)
              $ye = int($Y2)
            end
            if ("$KEY" == "i")
              $ys = int($Yi)
            end
            if ("$KEY" == "m")
              $ye = int($Ym)
            end
            if ("$KEY" == "j")
              $xs = int($Xj)
            end
            if ("$KEY" == "k")
              $xe = int($Xk)
            end
            if ("$KEY" == "q")
              $donezap = 1
            end
            if ("$KEY" == "Escape")
              $skipzap = 1
            end
            if ("$KEY" == "d")
              $ys = 0
	      $ye = $Ny
              $xs = int($Xd)
            end
            if ("$KEY" == "f")
              $ys = 0
	      $ye = $Ny
              $xe = int($Xf)
            end
            if ("$KEY" == "r")
              $xs = 0
              $ys = 6
	      $xe = $Nx
	      $ye = 8
              $donezap = 1
            end
            if ("$KEY" == "c")
              $xs = 0
              $ys = 589
	      $xe = $Nx
	      $ye = 591
              $donezap = 1
            end
          end            
          if ($skipzap == 0)
            zap mkc $xs $ys {$xe-$xs} {$ye-$ys} -v 2
   	    set imkc = (imc*(abs(imc - $F0) < $dF) + 1e6*(abs(imc - $F0) > $dF))*(mkc < 1)
      	    tvch 1; tv mkc -1 10
      	    tvch 3; tv imkc {$F0-2*$dF} {4*$dF}
          end
        end
        if ("$KEY" == "p") 
	  # clip high values
	  set mkcp = 2*(imkc > 1e5)
	  set mkc = mkc | mkcp
 	  set imkc = (imc*(abs(imc - $F0) < $dF) + 1e6*(abs(imc - $F0) > $dF))*(mkc < 1)
      	  tvch 1; tv mkc -1 10
      	  tvch 3; tv imkc {$F0-2*$dF} {4*$dF}
        end
      end
      # WWW wd mkc $outroot.$chip.fits -extend
    end
  end
  exec cp -i $outroot.$chip.fits $outroot.$chip.fits.save
end

# $F0 = 16000
# $F0 = 20500
$F0 = 390
$dF = 200
macro showchips
  if ($0 != 2)
    echo "USAGE: showchips (chip)"
    break
  end

  $chip = $1
  rd mk GPC1.MASK.$chip.ch.fits -x 0
  rd im o4743g0247o.$chip.ch.fits -x 0
  stats im
  $F0 = $MEDIAN
  set imk = (im*(abs(im - $F0) < $dF) + 1e6*(abs(im - $F0) > $dF))*(mk < 10)
  tvch 1; tv mk 0 10
  tvch 2; tv im {$F0-2*$dF} {4*$dF}
  tvch 3; tv imk {$F0-2*$dF} {4*$dF}
end

macro go
  for i 0 8
   for j 0 8
    if (($i == 0) && ($j == 0)) continue
    if (($i == 0) && ($j == 7)) continue
    if (($i == 7) && ($j == 0)) continue
    if (($i == 7) && ($j == 7)) continue
    showchips XY\$i\$j
    cursor
   end
  end
end

# XY43 was written with cell xy26 multiple times (same EXTNAME)
macro fix.XY43
  $input = GPC1.MASK.20081109.XY43.fits.broken
  $output = GPC1.MASK.20081109.XY43.fits.fix

  # PHU
  rd mk $input
  keyword mk NEXTEND -wd 0
  wd mk $output

  # EXT
  for i 0 66
    if ($i == 22) continue
    if ($i == 23) continue
    rd mk $input -x $i
    wd mk $output -extend
  end
end

# XY43 was written with cell xy26 multiple times (same EXTNAME)
macro fix.headers
  if ($0 != 2)
    echo "USAGE: fix.headers (chip)"
    break
  end

  $input = GPC1.MASK.20081109.$1.fits.broken
  $output = GPC1.MASK.20081109.$1.fits.fix

  # PHU
  rd mk $input
  keyword mk NEXTEND -wd 0

  keyword -d mk AIRMASS
  keyword -d mk FILTERID
  keyword -d mk POSANGLE
  keyword -d mk RADECSYS
  keyword -d mk COMRA   
  keyword -d mk COMDEC  
  keyword -d mk OBSTYPE 
  keyword -d mk OBJECT  
  keyword -d mk ALT     
  keyword -d mk AZ      
  keyword -d mk MJD-OBS 
  keyword -d mk DETTEM  
  keyword -d mk M1X     
  keyword -d mk M1Y     
  keyword -d mk M1Z     
  keyword -d mk M1TIP   
  keyword -d mk M1TILT  
  keyword -d mk M2X     
  keyword -d mk M2Y     
  keyword -d mk M2Z     
  keyword -d mk M2TIP   
  keyword -d mk M2TILT  
  keyword -d mk ENVTEM  
  keyword -d mk ENVHUM  
  keyword -d mk ENVWIN  
  keyword -d mk ENVDIR  
  keyword -d mk TELTEMM1
  keyword -d mk TELTEMMS
  keyword -d mk TELTEMM2
  keyword -d mk TELTEMSP
  keyword -d mk TELTEMTR
  keyword -d mk TELTEMEX
  keyword -d mk PONTIME 
  keyword -d mk EXPREQ  

  date -var date
  keyword mk DATE -w "$date"
  keyword mk DATE -wc "Date of File Creation"
  keyword mk COMMENT -ws "Mask Image Generated for IPP by EAM"

  keyword mk ORIGIN   -w "PS1"               ; keyword mk ORIGIN   -wc "IfA Pan-STARRS 1"
  keyword mk INSTRUME -w "gpc1"              ; keyword mk INSTRUME -wc "Instrument Name"                               
  keyword mk IMNAXIS1 -wd               4846 ; keyword mk IMNAXIS1 -wc "OTA image width in unbinned pixels"            
  keyword mk IMNAXIS2 -wd               4868 ; keyword mk IMNAXIS2 -wc "OTA image height in unbinned pixels"           
  keyword mk IMTM1_1  -wf        -1.00000000 ; keyword mk IMTM1_1  -wc "IMage Transform Matrix. A unit vector in the"  
  keyword mk IMTM1_2  -wf         0.00000000 ; keyword mk IMTM1_2  -wc " serial (fast) direction of amplifier readout" 
  keyword mk IMTM2_1  -wf         0.00000000 ; keyword mk IMTM2_1  -wc "And a unit vector in parallel (slow) direction"
  keyword mk IMTM2_2  -wf         1.00000000 ; keyword mk IMTM2_2  -wc " of amplifier readout"                         
  keyword mk CELLGAP1 -wd                 18 ; keyword mk CELLGAP1 -wc "Cell gap between columns (in unbinned pixels") 
  keyword mk CELLGAP2 -wd                 12 ; keyword mk CELLGAP2 -wc "Cell gap between rows (in unbinned pixels")    
  keyword mk CNAXIS1  -wd                590 ; keyword mk CNAXIS1  -wc "Cell imaging size in unbinned pixel columns"   
  keyword mk CNAXIS2  -wd                598 ; keyword mk CNAXIS2  -wc "Cell imaging size in unbinned pixel rows"      
  keyword mk CNPIX1   -wd                  0 ; keyword mk CNPIX1   -wc "Offset in unbinned pixel cols to readout start"
  keyword mk CNPIX2   -wd                  0 ; keyword mk CNPIX2   -wc "Offset in unbinned pixel rows to readout start"
  keyword mk CCDBIN1  -wd                  1 ; keyword mk CCDBIN1  -wc "Binning factor along axis 1"                   
  keyword mk CCDBIN2  -wd                  1 ; keyword mk CCDBIN2  -wc "Binning factor along axis 2"                   
  keyword mk PRESCAN1 -wd                  0 ; keyword mk PRESCAN1 -wc "Prescan count on axis 1"                       
  keyword mk PRESCAN2 -wd                  0 ; keyword mk PRESCAN2 -wc "Prescan count on axis 2"                       
  keyword mk OVRSCAN1 -wd                 34 ; keyword mk OVRSCAN1 -wc "Overscan count on axis 1"                      
  keyword mk OVRSCAN2 -wd                 10 ; keyword mk OVRSCAN2 -wc "Overscan count on axis 2"                      
  keyword mk COMMENT  -ws ""
  keyword mk COMMENT  -ws " Iraf coordinates "
  keyword mk COMMENT  -ws " ---------------- "
  keyword mk CCDSUM   -w  "1 1"              ; keyword mk CCDSUM   -wc "Binning factors"
  keyword mk DETSIZE  -w  "[1:4846,1:4868]"  ; keyword mk DETSIZE  -wc "Iraf total image pixels in full mosaic"

  wd mk $output

  # EXT
  for i 0 64
    rd mk $input -x $i

# delete these:
    keyword mk -d CHECKSUM
    keyword mk -d DATASUM
    keyword mk -d EXPTIME
    keyword mk -d DARKTIME

# we currently have:
# OK: DATASEC = '[1:590,1:598]'      / Trim section                                  
# OK: LTM1_1  =                   -1 / Orientation in x compared to the rest of the c
# OK: LTM2_2  =                    1 / Orientation in y compared to the rest of the c
# OK: CCDSUM  = '1 1     '           / Binning in x                                  
# OK: IMNPIX1 =                  590 / Position of (0,0) on the chip                 
# OK: IMNPIX2 =                  610 / Position of (0,0) on the chip                 

# insert these as is
    keyword mk LTM1_1 LT11
    keyword mk LTM2_2 LT22

    keyword mk CCDSUM   -w "1 1"                ; keyword mk CCDSUM  -wc "Binning factors"
    keyword mk BIASSEC  -w "[0:0,0:0]"          ; keyword mk BIASSEC -wc "Overscan (bias) area"
    keyword mk DETSIZE  -w "[1:4846,1:4868]"    ; keyword mk DETSIZE -wc "Iraf total image pixels in full mosaic"
    keyword mk ATM1_1   -wf $LT11               ; keyword mk ATM1_1  -wc "Iraf amplifier transformation matrix"
    keyword mk ATM2_2   -wf $LT22               ; keyword mk ATM2_2  -wc "Iraf amplifier transformation matrix"

# need to get the parity of these right:
# DETSEC  = '[590:1,1:598]'      / Iraf mosaic area of the detector              
# DETSEC  = '[590:1,611:1208]'   / Iraf mosaic area of the detector              
# DETSEC  = '[IMNPIX1:IMNPIX1-NAXIS1+1,IMNPIX2+1:IMNPIX2+NAXIS2]'
# DETSEC  = '[IMNPIX1:IMNPIX1-NAXIS1+1,IMNPIX2+1:IMNPIX2+NAXIS2]'
# LTV1    =         591.00000000 / Iraf image transformation vector              
# LTV2    =        -610.00000000 / Iraf image transformation vector              
# ATV1    =         591.00000000 / Iraf amplifier transformation vector          
# ATV2    =        -610.00000000 / Iraf amplifier transformation vector          

    wd mk $output -extend
  end
end

macro mask.fraction

  # make an output images which has 4x4 pixels per cell (256x256)
  mcreate out 256 256

  $CameraMasked = 0
  $CameraAllPix = 0

  for ix 0 8
    for iy 0 8
      if (($ix == 0) && ($iy == 0)) continue
      if (($ix == 0) && ($iy == 7)) continue
      if (($ix == 7) && ($iy == 0)) continue
      if (($ix == 7) && ($iy == 7)) continue

      sprintf file GPC1.MASK.FIX.XY%d%d.fits $ix $iy
      for Ix 0 8
        for Iy 0 8
          sprintf cell xy%d%d $Ix $Iy
	  rd mk $file -n $cell
          clip mk 0 0 1 1
          stats -q mk
          $CameraMasked = $CameraMasked + $TOTAL
          $CameraAllPix = $CameraAllPix + $NPIX
          $frac = $TOTAL / $NPIX
          if ($ix < 4)
            zap out {4*(8*($ix + 1) - $Ix - 1)} {4*(8*($iy + 1) - $Iy - 1)} 4 4 -v $frac
          else
            zap out {4*(8*$ix + $Ix)} {4*(8*$iy + $Iy)} 4 4 -v $frac
          end
        end
      end
    end
  end

  wd out fraction.fits -bitpix -32 -bzero 0.0 -bscale 1.0
end

macro mask.fraction.cte

  # make an output images which has 4x4 pixels per cell (256x256)
  mcreate out 256 256

  $CameraMasked = 0
  $CameraAllPix = 0

  for ix 0 8
    for iy 0 8
      if (($ix == 0) && ($iy == 0)) continue
      if (($ix == 0) && ($iy == 7)) continue
      if (($ix == 7) && ($iy == 0)) continue
      if (($ix == 7) && ($iy == 7)) continue

      sprintf file GPC1.MASK.CTE.XY%d%d.fits $ix $iy
      for Ix 0 8
        for Iy 0 8
          sprintf cell xy%d%d $Ix $Iy
	  rd mk $file -n $cell
          clip mk 0 0 1 1
          stats -q mk
          $CameraMasked = $CameraMasked + $TOTAL
          $CameraAllPix = $CameraAllPix + $NPIX
          $frac = $TOTAL / $NPIX
          if ($ix < 4)
            zap out {4*(8*($ix + 1) - $Ix - 1)} {4*(8*($iy + 1) - $Iy - 1)} 4 4 -v $frac
          else
            zap out {4*(8*$ix + $Ix)} {4*(8*$iy + $Iy)} 4 4 -v $frac
          end
        end
      end
    end
  end

  wd out fraction.cte.fits -bitpix -32 -bzero 0.0 -bscale 1.0
end

macro pics

  resize 710 560
  tv out 0.0 1.0
  tvcolors rainbow
  point red CIRCLE 128 128 133 133
  jpeg -name mask-full-focalplane.jpg

  set x = xramp(out)
  set y = yramp(out)
  set r = sqrt((x-128)^2 + (y-128)^2)
  set rm = (r < 133)
  set rf = out * rm
  tv rf
  jpeg -name mask-unvignetted.jpg
  
  stats -q out
  fprintf "masked fraction (full focal plane): %.3f" {$TOTAL/(4^2*8^2*60)}

  stats -q rf
  fprintf "masked fraction (unvignetted region): %.3f" {$TOTAL/(3.14*133^2)}

end

macro pics.cte

  rd out fraction.cte.fits
  resize 710 560
  tv out 0.0 1.0
  tvcolors rainbow
  point red CIRCLE 128 128 133 133
  jpeg -name mask-full-focalplane.cte.jpg

  set x = xramp(out)
  set y = yramp(out)
  set r = sqrt((x-128)^2 + (y-128)^2)
  set rm = (r < 133)
  set rf = out * rm
  tv rf
  jpeg -name mask-unvignetted.cte.jpg
  
  stats -q out
  fprintf "masked fraction (full focal plane): %.3f" {$TOTAL/(4^2*8^2*60)}

  stats -q rf
  fprintf "masked fraction (unvignetted region): %.3f" {$TOTAL/(3.14*133^2)}

end
