with open('crates/fluids/coolprop-sys/src/lib.rs', 'r') as f:
    text = f.read()

# Replace CoolProp_PropsSI with PropsSI
text = text.replace('CoolProp_PropsSI(', 'PropsSI(')
text = text.replace('CoolProp_Props1SI(', 'Props1SI(')
text = text.replace('CoolProp_get_global_param_string(', 'get_global_param_string(')
text = text.replace('CoolProp_get_fluid_param_string(', 'get_fluid_param_string(')

# Fix strings to c strings for PropsSI arguments
text = text.replace(
    'PropsSI(prop, b\'P\' as c_char, p, b\'T\' as c_char, t, fluid_c.as_ptr())',
    'PropsSI(c"D".as_ptr(), c"P".as_ptr(), p, c"T".as_ptr(), t, fluid_c.as_ptr())'
)
text = text.replace(
    'PropsSI(prop, b\'P\' as c_char, p, b\'H\' as c_char, h, fluid_c.as_ptr())',
    'PropsSI(c"D".as_ptr(), c"P".as_ptr(), p, c"H".as_ptr(), h, fluid_c.as_ptr())'
)
text = text.replace(
    'PropsSI(prop, b\'T\' as c_char, t, b\'Q\' as c_char, q, fluid_c.as_ptr())',
    'PropsSI(c"D".as_ptr(), c"T".as_ptr(), t, c"Q".as_ptr(), q, fluid_c.as_ptr())'
)
text = text.replace(
    '''        b'P' as c_char,
        p,
        b'Q' as c_char, // Q for quality
        x,
        fluid_c.as_ptr(),''',
    '''        c"P".as_ptr(),
        p,
        c"Q".as_ptr(), // Q for quality
        x,
        fluid_c.as_ptr(),'''
)

text = text.replace('let prop = property.as_bytes()[0] as c_char;', 'let prop_c = std::ffi::CString::new(property).unwrap();')
text = text.replace('c"D".as_ptr()', 'prop_c.as_ptr()')

# Fix is_fluid
text = text.replace(
'''pub unsafe fn is_fluid_available(fluid: &str) -> bool {
    let fluid_c = CString::new(fluid).unwrap();
    CoolProp_isfluid(fluid_c.as_ptr()) != 0
}''',
'''pub unsafe fn is_fluid_available(fluid: &str) -> bool {
    let fluid_c = CString::new(fluid).unwrap();
    # CoolProp C API does not expose isfluid, so we try fetching a property
    let res = Props1SI(fluid_c.as_ptr(), c"Tcrit".as_ptr());
    if res.is_finite() && res != 0.0 { true } else { false }
}'''
)

text = text.replace('CoolProp_CriticalPoint(fluid_c.as_ptr(), b\'T\' as c_char)', 'Props1SI(fluid_c.as_ptr(), c"Tcrit".as_ptr())')
text = text.replace('CoolProp_CriticalPoint(fluid_c.as_ptr(), b\'P\' as c_char)', 'Props1SI(fluid_c.as_ptr(), c"pcrit".as_ptr())')
text = text.replace('CoolProp_CriticalPoint(fluid_c.as_ptr(), b\'D\' as c_char)', 'Props1SI(fluid_c.as_ptr(), c"rhocrit".as_ptr())')

with open('crates/fluids/coolprop-sys/src/lib.rs', 'w') as f:
    f.write(text)
