#!/bin/bash

# Must provide a file argument
if [ $# -lt 1 ]; then
    echo "Usage: $0 <input_file>"
    exit 1
fi
input_file="$1"

# Check if the file exists
if [ ! -f "$input_file" ]; then
    echo "Error: File '$input_file' not found!"
    exit 1
fi

# Find out how many variables the formula has 
# (this is used for fixing up the assignment printed out by kissat)
while IFS= read -r line; do
    if [[ $line == p\ * ]]; then
        read -r _ _ N _ <<< "$line"
        break
    fi
done < "$1"

# Check if N was set
if [ -z "$N" ]; then
    echo "Error: No 'p' line found in $1" >&2
    exit 1
fi

# Run satsuma only if N < 5000000, to make sure we don't reach 32GB memory limit 
if [ "$N" -lt 5000000 ]; then
    ./satsuma --silent --proof-dense-crossover 60 --component-limit 500000 --order-model-limit 750000 --dense-model-limit 20000000 --add-reduced-as-unit --preprocess-cnf-unit -f "$input_file" --proof-file proof.out --out-file temporary.cnf
    # Run kissat on the processed file
    ./kissat -q --no-binary --witnessmaxvar="$N" temporary.cnf proof.out
else
    echo "pseudo-Boolean proof version 3.0" > 'proof.out'
    # Run kissat directly on the original file
    ./kissat -q --no-binary --witnessmaxvar="$N" "$input_file" proof.out
fi

# If UNSAT, we should finish the proof file
if [ $? -eq 20 ]; then
    echo "output NONE;" >> proof.out
    echo "conclusion UNSAT;" >> proof.out
    echo "end pseudo-Boolean proof;" >> proof.out
fi

# Cleanup
if [ -f "temporary.cnf" ]; then 
    rm temporary.cnf
fi
