#!/usr/bin/perl -w
# Plot_function:
#    VERSION: Version 1 (16 October 2003)
#    PURPOSE: Calculates points of a function to plot within Excel
#             Function should be put in subroutine Function
#             Range of x should be specified in CONSTANTS section
#             Value for dx should be specified in CONSTANTS section
#    OUTPUT FILES: Tab-delimited text file with the following two fields:
#         x       f(x)

############## LIBRARIES AND PRAGMAS ################
  use strict;

#################### CONSTANTS ######################

  my $dx = .5;           # Time increment, in sec
  my $x_start = 0;       # Lowest x of range
  my $x_end = 5;         # Highest x of range
  my $header = "points"; # First line that appears in output file
  my $LF = "\n";         # Linefeed
  my $tab = "\t";        # Tab

#################### VARIABLES ######################

  my $x;
  my $y;

###################### FILES ########################

  my $output_path = 'function_output.txt';
  open OUTPUT_FILE, ">$output_path" or die "Can't open $output_path: $!\n";

################### MAIN PROGRAM ####################
# x goes from $x_start to $x_end
# At each time point, y is calculated from user-defined function

  Print_header($header);

  for ($x=$x_start; $x <= $x_end; $x = $x + $dx) {
     $y = f($x);
     Output_point($x,$y);
  }

#################### SUBROUTINES ####################

#### F (x)         User-defined function
#    Calculates rate of change for each metabolite
#    Reaction is S --> P
  sub f {
    my ($x) = @_;             # Concentrations of substrate and product
    my $k = 1;                # Rate constant of 1 sec/M
    my $f_of_x;               # Any function (may be multiline)
    $f_of_x = exp(-$k*$x);
    return $f_of_x;
  }

#### PRINT_HEADER (header)
#    Prints first line of output file (identification)
  sub Print_header {
    print $header, $LF;
    print OUTPUT_FILE $header, $LF;
  }

#### OUTPUT_POINT
#    Prints x and y
  sub Output_point {
    print join("\t", @_), $LF;
    print OUTPUT_FILE join("\t",@_), $LF;
  }

