#! /bin/csh -f
# Process CFSR GRIB2 -> flat binaries (step 1), with JP2 auto-conversion.
# be tolerant of unmatched globs like CFSR_*.dat
set nonomatch

# --- Paths / env ---
set proj_root = "/work"
if ( ! -d "$proj_root" ) set proj_root = "/home/ssm-user/GETD_IIJA"

# use the mounted/static wgrib2 if WGRIB2 not set by the caller
if ( $?WGRIB2 ) then
  set mywgrib2 = "$WGRIB2"
else
  set mywgrib2 = "/opt/wgrib2s/wgrib2"
endif

# make sure tmp_dir exists (yours was $OUT_DATA_DIR/tmp; keep that if you set it)
if ( ! $?tmp_dir ) then
  if ( $?OUT_DATA_DIR ) then
    set tmp_dir = "$OUT_DATA_DIR/tmp"
  else
    # safe fallback if OUT_DATA_DIR isn’t exported
    set tmp_dir = "$proj_root/data/tmp"
  endif
endif
if ( ! -d "$tmp_dir" ) mkdir -p "$tmp_dir"

# input root inside container
set meteo_in_dir = "$proj_root/CFSR_INSO"

# ecCodes tools needed for JPEG2000 -> simple conversion
set grib_get = `which grib_get`
set grib_set = `which grib_set`
if ( ! -x "$grib_get" || ! -x "$grib_set" ) then
  echo "ERROR: grib_get/grib_set not found. Install ecCodes tools inside container."; exit 2
endif

echo "C SHELL script to process the CFSR data"
echo "Using wgrib2: $mywgrib2"

# --- CLI parsing from your original script ---
if ( $#argv == 2 ) then
  echo "Convert input DOY to month and day"
  set dummy = `$BIN_DIR/month_day.x $1 $2`
  set mm = $dummy[1]
  set dd = $dummy[2]
  echo "Convert $2 into Month $mm Day $dd"
  set month = $mm
  set day = $dd
else if ( $#argv != 3 ) then
  if ( $2 < 10 ) then
    set month = "0"$2
  else
    set month = $2
  endif
  if ( $3 < 10 ) then
    set day = "0"$3
  else
    set day = $3
  endif
else
  echo "Usage: $0 [Year] [Month] [Day]"
  echo "Example: $0 2013 8 1"
  goto error
endif

begin:
set icount = 0
set year = $1
echo "Extracting data from CFSR on ${year}${month}${day}"

# Preclean (avoid 'No match.')
rm -f $tmp_dir/CFSR_*.dat

# Loop hours/forecasts like your script
set thour = 0
foreach hour (00 06 12 18)
  foreach fhour (000 003)
    echo $thour
    set hfile = "CFSR_INSO_"$year$month$day"_"$hour"00_"$fhour".grb2"
   set in_grib2_file = "$meteo_in_dir/$year/$hfile"
   echo $in_grib2_file
   if ( -e "$in_grib2_file" ) then
     @ icount ++

     if ( $thour < 10 ) then
       set hourflag = "0"$thour
     else
       set hourflag = $thour
     endif

     # --- (1) detect packing type (csh-safe) ---
     # NOTE: no bash-style 2>/dev/null here
     set pt = `grib_get -p packingType "$in_grib2_file"`
     # echo "packingType=$pt"   # (optional debug)

     # --- (2) repack JP2/JPEG to simple once, then read with wgrib2 ---
     set F = "$in_grib2_file"
     set repack_tmp = ""
     if ( "$pt" =~ *jpeg* || "$pt" == "grid_jpeg2000" ) then
       set repack_tmp = "/tmp/repack_${year}${month}${day}_${hour}_${fhour}_$$.grb2"
       grib_set -s packingType=grid_simple "$in_grib2_file" "$repack_tmp"
       set F = "$repack_tmp"
     endif

      # ---- Extractions ----
      $mywgrib2 "$F" -match "DLWRF:surface"  -bin $tmp_dir/CFSR_DLWRF$hourflag.dat   -no_header -little_endian
      $mywgrib2 "$F" -match "DSWRF:surface"  -bin $tmp_dir/CFSR_DSWRF$hourflag.dat   -no_header -little_endian
      $mywgrib2 "$F" -match "(TMP):surface"  -bin $tmp_dir/CFSR_TMPLST$hourflag.dat  -no_header -little_endian
      $mywgrib2 "$F" -match "LHTFL:surface"  -bin $tmp_dir/CFSR_LHTFL$hourflag.dat   -no_header -little_endian
      $mywgrib2 "$F" -match "HGT:surface"    -bin $tmp_dir/CFSR_HGTSFC$hourflag.dat  -no_header -little_endian
      $mywgrib2 "$F" -match "PRES:surface"   -bin $tmp_dir/CFSR_PRESSFC$hourflag.dat -no_header -little_endian
      $mywgrib2 "$F" -match "SPFH:1 hybrid level"      -bin $tmp_dir/CFSR_SPFHSFC$hourflag.dat -no_header -little_endian
      $mywgrib2 "$F" -match "TMP:0.995 sigma level"    -bin $tmp_dir/CFSR_TMPSFC$hourflag.dat  -no_header -little_endian
      $mywgrib2 "$F" -match "UGRD:0.995 sigma level"   -bin $tmp_dir/CFSR_UGRD$hourflag.dat    -no_header -little_endian
      $mywgrib2 "$F" -match "VGRD:0.995 sigma level"   -bin $tmp_dir/CFSR_VGRD$hourflag.dat    -no_header -little_endian
      $mywgrib2 "$F" -match "(TMP):(100|150|200|250|300|350|400|450|500|550|600|650|700|750|800|850|900|925|950|975|1000) mb:"  -bin $tmp_dir/CFSR_TMP$hourflag.dat  -no_header -little_endian
      $mywgrib2 "$F" -match "(SPFH):(100|150|200|250|300|350|400|450|500|550|600|650|700|750|800|850|900|925|950|975|1000) mb:" -bin $tmp_dir/CFSR_SPFH$hourflag.dat -no_header -little_endian
      $mywgrib2 "$F" -match "(HGT):(100|150|200|250|300|350|400|450|500|550|600|650|700|750|800|850|900|925|950|975|1000) mb:"  -bin $tmp_dir/CFSR_HGT$hourflag.dat  -no_header -little_endian

    if ( "$repack_tmp" != "" && -e "$repack_tmp" ) rm -f "$repack_tmp"
    endif
    @ thour = $thour + 3
  end
end

echo "Total $icount input files found"

# Continue to next stage (unchanged)
$BIN_DIR/getd.x -m GETD_CFS_STEP1.cfg $year $month $day

exit 0
error:
exit 1
