#!/bin/bash -x

# --- Configuration ---
# Input binary file name
INPUT_BINARY_FILE="input.bin"

# Output NetCDF file name
OUTPUT_NETCDF_FILE="output.nc"

# Grid description file (e.g., grid.txt)
# This file defines the horizontal grid of your data.
# Example content for grid.txt (for a global 1x1 degree grid):
# gridtype = regular
# xsize = 360
# ysize = 180
# xfirst = 0.5
# xinc = 1.0
# yfirst = -89.5
# yinc = 1.0
GRID_DESCRIPTION_FILE="grid.txt"

# Number of variables in your binary file
# If your binary file contains multiple variables concatenated, specify the count.
# For a single variable, set this to 1.
NUMBER_OF_VARIABLES=1

# Number of vertical levels (if applicable)
# If your data has a vertical dimension, specify the number of levels.
# If not, set to 1 or adjust the cdo command accordingly.
NUMBER_OF_LEVELS=1

# Variable name (e.g., temperature, pressure)
VARIABLE_NAME="temperature"

# Units of the variable (e.g., K, Pa)
VARIABLE_UNITS="K"

# Long name of the variable
VARIABLE_LONG_NAME="temperature"

# Missing value (if a specific value in the binary file represents missing data)
# If no specific missing value, you can remove '-setctomiss' from the cdo command.
MISSING_VALUE=-9999.0

# --- Check for CDO installation ---
if ! command -v cdo &> /dev/null
then
    echo "CDO could not be found. Please install CDO to run this script."
    echo "On Debian/Ubuntu: sudo apt-get install cdo"
    echo "On CentOS/RHEL: sudo yum install cdo"
    echo "Or compile from source: https://code.mpimet.mpg.de/projects/cdo/wiki/Cdo"
    exit 1
fi

# --- Create a dummy binary file for demonstration if it doesn't exist ---
if [ ! -f "${INPUT_BINARY_FILE}" ]; then
    echo "Creating a dummy binary file for demonstration: ${INPUT_BINARY_FILE}"
    # Example: Create a binary file with 360*180*1 values (for a 1x1 global grid, 1 level)
    # This generates random float values. Adjust as needed for your actual data size.
    # For a simple example, let's create a file with 64800 values (360x180)
    python3 -c \
	    "import struct, random; with open('${INPUT_BINARY_FILE}', 'wb') \
	    as f: for _ in range(360 * 180 * ${NUMBER_OF_LEVELS} * ${NUMBER_OF_VARIABLES}): \
	    f.write(struct.pack('<f', 273.15 + random.uniform(-10, 10)))"
    echo "Dummy binary file created."
fi

# --- Create a dummy grid description file if it doesn't exist ---
if [ ! -f "${GRID_DESCRIPTION_FILE}" ]; then
    echo "Creating a dummy grid description file: ${GRID_DESCRIPTION_FILE}"
    cat << EOF > "${GRID_DESCRIPTION_FILE}"
gridtype = regular
xsize = 360
ysize = 180
xfirst = 0.5
xinc = 1.0
yfirst = -89.5
yinc = 1.0
EOF
    echo "Dummy grid description file created."
fi

echo "Starting conversion..."
echo "Input binary: ${INPUT_BINARY_FILE}"
echo "Output NetCDF: ${OUTPUT_NETCDF_FILE}"
echo "Grid description: ${GRID_DESCRIPTION_FILE}"

# --- CDO Conversion Command ---
# Steps:
# 1. setgrid: Applies the horizontal grid definition from GRID_DESCRIPTION_FILE.
# 2. setzaxis: Defines the vertical axis if NUMBER_OF_LEVELS > 1.
# 3. setctomiss: Replaces the specified MISSING_VALUE with NetCDF missing value.
# 4. setname: Sets the variable name.
# 5. setunit: Sets the variable units.
# 6. setlongname: Sets the variable long name.
# 7. -f nc: Specifies the output format as NetCDF.
# 8. -v: Verbose output (optional, remove if not needed).

# If you have multiple variables in the binary file, you might need to use 'splitvar'
# or process each variable separately depending on how they are structured.
# This script assumes a single variable or a simple concatenation that can be
# handled by 'setgrid' and 'setzaxis' for the overall file structure.

# If NUMBER_OF_LEVELS is 1, we don't need setzaxis.
if [ "${NUMBER_OF_LEVELS}" -gt 1 ]; then
    CDO_ZAXIS_COMMAND="-setzaxis,levels=${NUMBER_OF_LEVELS}"
else
    CDO_ZAXIS_COMMAND=""
fi
cdo -f nc -v \
    ${CDO_ZAXIS_COMMAND} \
    -setgrid,"${GRID_DESCRIPTION_FILE}" \
    "${INPUT_BINARY_FILE}" /dev/stdout | \
cdo -setctomiss,"${MISSING_VALUE}" \
    -setname,"${VARIABLE_NAME}" \
    -setunit,"${VARIABLE_UNITS}" \
    /dev/stdin "${OUTPUT_NETCDF_FILE}"

# --- Verification ---
if [ $? -eq 0 ]; then
    echo "Conversion successful! Output file: ${OUTPUT_NETCDF_FILE}"
    echo "You can inspect the NetCDF file using 'ncdump -h ${OUTPUT_NETCDF_FILE}'"
else
    echo "Conversion failed. Please check the error messages above."
fi

