#!/usr/bin/env python3
# encoding=UTF-8

# Copyright © 2014-2021 Jakub Wilk <jwilk@jwilk.net>
# SPDX-License-Identifier: MIT

import argparse
import math
import sys

...  # Python 3 is required

in_to_mm = 25.4

def printf(s, *args, **kwargs):
    print(s.format(*args, **kwargs))

def main():
    ap = argparse.ArgumentParser()
    if sys.version_info < (3, 10):
        # https://bugs.python.org/issue9694
        ap._optionals.title = 'options'
    ap.add_argument('x_px', metavar='XRES', type=int, help='width in pixels')
    ap.add_argument('y_px', metavar='YRES', type=int, help='height in pixels')
    ap.add_argument('d_in', metavar='DIAM', type=float, help='diameter in inches')
    options = ap.parse_args()
    # virtual size:
    x_px = options.x_px
    y_px = options.y_px
    a_px = x_px * y_px
    d_px = math.hypot(x_px, y_px)
    print('virtual size:')
    printf('- width:    {:5.0f} px', x_px)
    printf('- height:   {:5.0f} px', y_px)
    printf('- diameter: {:5.0f} px', d_px)
    printf('- area:     {:5.2f} Mpx', a_px / 1E6)
    d_mm = options.d_in * in_to_mm
    print()
    # physical size:
    print('physical size:')
    x_mm = d_mm / d_px * x_px
    y_mm = d_mm / d_px * y_px
    a_mm = x_mm * y_mm
    printf('- width:    {:5.0f} mm', x_mm)
    printf('- height:   {:5.0f} mm', y_mm)
    printf('- diameter: {:5.0f} mm', d_mm)
    printf('- area:     {:5.0f} cm²', a_mm / 100)
    print()
    # physical size of one pixel:
    print('physical size of one pixel:')
    printf('- width:    {:5.2f} mm', x_mm / x_px)
    printf('- height:   {:5.2f} mm', y_mm / y_px)
    printf('- area:     {:4.3f} mm²', a_mm / a_px)
    print()
    # physical movie size:
    for aspect in [(4, 3), (16, 9)]:
        mx_to_my = aspect[1] / aspect[0]
        printf('{}:{} movie size:', *aspect)
        mx_mm = x_mm
        my_mm = mx_mm * mx_to_my
        if my_mm > y_mm:
            my_mm = y_mm
            mx_mm = my_mm / mx_to_my
        md_mm = math.hypot(mx_mm, my_mm)
        ma_mm = mx_mm * my_mm
        assert mx_mm < x_mm + 0.1
        assert my_mm < y_mm + 0.1
        assert md_mm < d_mm + 0.1
        assert ma_mm < a_mm + 0.1
        printf('- width:    {:5.0f} mm', mx_mm)
        printf('- height:   {:5.0f} mm', my_mm)
        printf('- diameter: {:5.0f} mm', md_mm)
        printf('- area:     {:5.0f} cm²', ma_mm / 100)
        print()

if __name__ == '__main__':
    main()

# vim:ts=4 sts=4 sw=4 et
