Input validation and calculation function