#include <cstdio>
#include <hal/drivers/flash.h>
#include <hal/devices.h>
#include <hal/drivers/pwm.h>

int cmd_frequency(int argc, char *argv[])
{
	if (argc != 2)
	{
		printf("%s: error, syntax: ADDRESS %s FREQUENCY\n\n", argv[0], argv[0]);
	}
	else
	{
		pwm_file pwm;
		pwm.freq = -1;

		sscanf(argv[1], "%f", &pwm.freq);

		if (pwm.freq <= configure_file.max_freq && pwm.freq >= configure_file.min_freq)
		{
			flash_file * p_flash_file;

			fseek(p_pwm, (int) (&pwm.freq) - (int) (&pwm), SEEK_SET);
			fwrite(&pwm.freq, sizeof(pwm_file::freq), 1, p_pwm);
			fflush(p_pwm);

			decltype(p_flash_file->frequency) frequency = pwm.freq;
			fseek(p_flash, (int) (&p_flash_file->frequency) - (int) (p_flash_file), SEEK_SET);
			fwrite(&frequency, sizeof(flash_file::frequency), 1, p_flash);
			fflush(p_flash);

			printf("%s: the frequency is set to: %fHz\n\n", argv[0], pwm.freq);
		}
		else
		{
			printf("%s: error, frequency input: %s is not in range: %f~%f\n\n", argv[0], argv[1], configure_file.min_freq,
			    configure_file.max_freq);
		}
	}

	fflush(stdout);
}
